-
Notifications
You must be signed in to change notification settings - Fork 0
/
webr-worker.js
2986 lines (2968 loc) · 89.1 KB
/
webr-worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
// node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js
var require_XMLHttpRequest = __commonJS({
"node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js"(exports, module2) {
var fs = require("fs");
var Url = require("url");
var spawn = require("child_process").spawn;
module2.exports = XMLHttpRequest2;
XMLHttpRequest2.XMLHttpRequest = XMLHttpRequest2;
function XMLHttpRequest2(opts) {
"use strict";
opts = opts || {};
var self = this;
var http = require("http");
var https = require("https");
var request;
var response;
var settings = {};
var disableHeaderCheck = false;
var defaultHeaders = {
"User-Agent": "node-XMLHttpRequest",
"Accept": "*/*"
};
var headers = Object.assign({}, defaultHeaders);
var forbiddenRequestHeaders = [
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"content-transfer-encoding",
"cookie",
"cookie2",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"via"
];
var forbiddenRequestMethods = [
"TRACE",
"TRACK",
"CONNECT"
];
var sendFlag = false;
var errorFlag = false;
var abortedFlag = false;
var listeners = {};
this.UNSENT = 0;
this.OPENED = 1;
this.HEADERS_RECEIVED = 2;
this.LOADING = 3;
this.DONE = 4;
this.readyState = this.UNSENT;
this.onreadystatechange = null;
this.responseText = "";
this.responseXML = "";
this.response = Buffer.alloc(0);
this.status = null;
this.statusText = null;
var isAllowedHttpHeader = function(header) {
return disableHeaderCheck || header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1;
};
var isAllowedHttpMethod = function(method) {
return method && forbiddenRequestMethods.indexOf(method) === -1;
};
this.open = function(method, url, async, user, password) {
this.abort();
errorFlag = false;
abortedFlag = false;
if (!isAllowedHttpMethod(method)) {
throw new Error("SecurityError: Request method not allowed");
}
settings = {
"method": method,
"url": url.toString(),
"async": typeof async !== "boolean" ? true : async,
"user": user || null,
"password": password || null
};
setState(this.OPENED);
};
this.setDisableHeaderCheck = function(state) {
disableHeaderCheck = state;
};
this.setRequestHeader = function(header, value) {
if (this.readyState != this.OPENED) {
throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");
}
if (!isAllowedHttpHeader(header)) {
console.warn('Refused to set unsafe header "' + header + '"');
return false;
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send flag is true");
}
headers[header] = value;
return true;
};
this.getResponseHeader = function(header) {
if (typeof header === "string" && this.readyState > this.OPENED && response.headers[header.toLowerCase()] && !errorFlag) {
return response.headers[header.toLowerCase()];
}
return null;
};
this.getAllResponseHeaders = function() {
if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
return "";
}
var result = "";
for (var i in response.headers) {
if (i !== "set-cookie" && i !== "set-cookie2") {
result += i + ": " + response.headers[i] + "\r\n";
}
}
return result.substr(0, result.length - 2);
};
this.getRequestHeader = function(name) {
if (typeof name === "string" && headers[name]) {
return headers[name];
}
return "";
};
this.send = function(data) {
if (this.readyState != this.OPENED) {
throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send has already been called");
}
var ssl = false, local = false;
var url = Url.parse(settings.url);
var host;
switch (url.protocol) {
case "https:":
ssl = true;
case "http:":
host = url.hostname;
break;
case "file:":
local = true;
break;
case void 0:
case "":
host = "localhost";
break;
default:
throw new Error("Protocol not supported.");
}
if (local) {
if (settings.method !== "GET") {
throw new Error("XMLHttpRequest: Only GET method is supported");
}
if (settings.async) {
fs.readFile(unescape(url.pathname), function(error, data2) {
if (error) {
self.handleError(error, error.errno || -1);
} else {
self.status = 200;
self.responseText = data2.toString("utf8");
self.response = data2;
setState(self.DONE);
}
});
} else {
try {
this.response = fs.readFileSync(unescape(url.pathname));
this.responseText = this.response.toString("utf8");
this.status = 200;
setState(self.DONE);
} catch (e) {
this.handleError(e, e.errno || -1);
}
}
return;
}
var port = url.port || (ssl ? 443 : 80);
var uri = url.pathname + (url.search ? url.search : "");
headers["Host"] = host;
if (!(ssl && port === 443 || port === 80)) {
headers["Host"] += ":" + url.port;
}
if (settings.user) {
if (typeof settings.password == "undefined") {
settings.password = "";
}
var authBuf = new Buffer(settings.user + ":" + settings.password);
headers["Authorization"] = "Basic " + authBuf.toString("base64");
}
if (settings.method === "GET" || settings.method === "HEAD") {
data = null;
} else if (data) {
headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
if (!headers["Content-Type"]) {
headers["Content-Type"] = "text/plain;charset=UTF-8";
}
} else if (settings.method === "POST") {
headers["Content-Length"] = 0;
}
var agent = opts.agent || false;
var options = {
host,
port,
path: uri,
method: settings.method,
headers,
agent
};
if (ssl) {
options.pfx = opts.pfx;
options.key = opts.key;
options.passphrase = opts.passphrase;
options.cert = opts.cert;
options.ca = opts.ca;
options.ciphers = opts.ciphers;
options.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
}
errorFlag = false;
if (settings.async) {
var doRequest = ssl ? https.request : http.request;
sendFlag = true;
self.dispatchEvent("readystatechange");
var responseHandler = function(resp2) {
response = resp2;
if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
settings.url = response.headers.location;
var url2 = Url.parse(settings.url);
host = url2.hostname;
var newOptions = {
hostname: url2.hostname,
port: url2.port,
path: url2.path,
method: response.statusCode === 303 ? "GET" : settings.method,
headers
};
if (ssl) {
newOptions.pfx = opts.pfx;
newOptions.key = opts.key;
newOptions.passphrase = opts.passphrase;
newOptions.cert = opts.cert;
newOptions.ca = opts.ca;
newOptions.ciphers = opts.ciphers;
newOptions.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
}
request = doRequest(newOptions, responseHandler).on("error", errorHandler);
request.end();
return;
}
setState(self.HEADERS_RECEIVED);
self.status = response.statusCode;
response.on("data", function(chunk) {
if (chunk) {
var data2 = Buffer.from(chunk);
self.responseText += data2.toString("utf8");
self.response = Buffer.concat([self.response, data2]);
}
if (sendFlag) {
setState(self.LOADING);
}
});
response.on("end", function() {
if (sendFlag) {
sendFlag = false;
setState(self.DONE);
}
});
response.on("error", function(error) {
self.handleError(error);
});
};
var errorHandler = function(error) {
self.handleError(error);
};
request = doRequest(options, responseHandler).on("error", errorHandler);
if (opts.autoUnref) {
request.on("socket", (socket) => {
socket.unref();
});
}
if (data) {
request.write(data);
}
request.end();
self.dispatchEvent("loadstart");
} else {
var contentFile = ".node-xmlhttprequest-content-" + process.pid;
var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
fs.writeFileSync(syncFile, "", "utf8");
var execString = "var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http" + (ssl ? "s" : "") + ".request;var options = " + JSON.stringify(options) + ";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('" + syncFile + "');});response.on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});}).on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});" + (data ? "req.write('" + JSON.stringify(data).slice(1, -1).replace(/'/g, "\\'") + "');" : "") + "req.end();";
var syncProc = spawn(process.argv[0], ["-e", execString]);
var statusText;
while (fs.existsSync(syncFile)) {
}
self.responseText = fs.readFileSync(contentFile, "utf8");
syncProc.stdin.end();
fs.unlinkSync(contentFile);
if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
var errorObj = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, ""));
self.handleError(errorObj, 503);
} else {
self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, "$1");
var resp = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, "$1"));
response = {
statusCode: self.status,
headers: resp.data.headers
};
self.responseText = resp.data.text;
self.response = Buffer.from(resp.data.data, "base64");
setState(self.DONE, true);
}
}
};
this.handleError = function(error, status) {
this.status = status || 0;
this.statusText = error;
this.responseText = error.stack;
errorFlag = true;
setState(this.DONE);
};
this.abort = function() {
if (request) {
request.abort();
request = null;
}
headers = Object.assign({}, defaultHeaders);
this.responseText = "";
this.responseXML = "";
this.response = Buffer.alloc(0);
errorFlag = abortedFlag = true;
if (this.readyState !== this.UNSENT && (this.readyState !== this.OPENED || sendFlag) && this.readyState !== this.DONE) {
sendFlag = false;
setState(this.DONE);
}
this.readyState = this.UNSENT;
};
this.addEventListener = function(event, callback) {
if (!(event in listeners)) {
listeners[event] = [];
}
listeners[event].push(callback);
};
this.removeEventListener = function(event, callback) {
if (event in listeners) {
listeners[event] = listeners[event].filter(function(ev) {
return ev !== callback;
});
}
};
this.dispatchEvent = function(event) {
if (typeof self["on" + event] === "function") {
if (this.readyState === this.DONE && settings.async)
setImmediate(function() {
self["on" + event]();
});
else
self["on" + event]();
}
if (event in listeners) {
for (let i = 0, len = listeners[event].length; i < len; i++) {
if (this.readyState === this.DONE)
setImmediate(function() {
listeners[event][i].call(self);
});
else
listeners[event][i].call(self);
}
}
};
var setState = function(state) {
if (self.readyState === state || self.readyState === self.UNSENT && abortedFlag)
return;
self.readyState = state;
if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
self.dispatchEvent("readystatechange");
}
if (self.readyState === self.DONE) {
let fire;
if (abortedFlag)
fire = "abort";
else if (errorFlag)
fire = "error";
else
fire = "load";
self.dispatchEvent(fire);
self.dispatchEvent("loadend");
}
};
}
}
});
// webR/compat.ts
var IN_NODE = typeof process !== "undefined" && process.release && process.release.name === "node" && typeof process.browser === "undefined";
var loadScript;
if (globalThis.document) {
loadScript = (url) => new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = url;
script.onload = () => resolve();
script.onerror = reject;
document.head.appendChild(script);
});
} else if (globalThis.importScripts) {
loadScript = async (url) => {
try {
globalThis.importScripts(url);
} catch (e) {
if (e instanceof TypeError) {
await Promise.resolve().then(() => __toESM(require(url)));
} else {
throw e;
}
}
};
} else if (IN_NODE) {
loadScript = async (url) => {
const nodePathMod = (await Promise.resolve().then(() => __toESM(require("path")))).default;
await Promise.resolve().then(() => __toESM(require(nodePathMod.resolve(url))));
};
} else {
throw new Error("Cannot determine runtime environment");
}
// webR/utils.ts
function promiseHandles() {
const out = {
resolve: (_value) => {
},
reject: (_reason) => {
},
promise: null
};
const promise = new Promise((resolve, reject) => {
out.resolve = resolve;
out.reject = reject;
});
out.promise = promise;
return out;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function replaceInObject(obj, test, replacer, ...replacerArgs) {
if (obj === null || typeof obj !== "object") {
return obj;
}
if (test(obj)) {
return replacer(obj, ...replacerArgs);
}
if (Array.isArray(obj) || ArrayBuffer.isView(obj)) {
return obj.map(
(v) => replaceInObject(v, test, replacer, ...replacerArgs)
);
}
return Object.fromEntries(
Object.entries(obj).map(([k, v], i) => [k, replaceInObject(v, test, replacer, ...replacerArgs)])
);
}
function newCrossOriginWorker(url, cb) {
const req = new XMLHttpRequest();
req.open("get", url, true);
req.onload = () => {
const worker = new Worker(URL.createObjectURL(new Blob([req.responseText])));
cb(worker);
};
req.send();
}
function isCrossOrigin(urlString) {
if (IN_NODE)
return false;
const url1 = new URL(location.href);
const url2 = new URL(urlString, location.origin);
if (url1.host === url2.host && url1.port === url2.port && url1.protocol === url2.protocol) {
return false;
}
return true;
}
function throwUnreachable(context) {
let msg = "Reached the unreachable";
msg = msg + (context ? ": " + context : ".");
throw new Error(msg);
}
// webR/chan/task-common.ts
var SZ_BUF_DOESNT_FIT = 0;
var SZ_BUF_FITS_IDX = 1;
var SZ_BUF_SIZE_IDX = 0;
var transferCache = /* @__PURE__ */ new WeakMap();
function transfer(obj, transfers) {
transferCache.set(obj, transfers);
return obj;
}
function isUUID(x) {
return typeof x === "string" && x.length === UUID_LENGTH;
}
var UUID_LENGTH = 63;
function generateUUID() {
const result = Array.from({ length: 4 }, randomSegment).join("-");
if (result.length !== UUID_LENGTH) {
throw new Error("comlink internal error: UUID has the wrong length");
}
return result;
}
function randomSegment() {
let result = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16);
const pad = 15 - result.length;
if (pad > 0) {
result = Array.from({ length: pad }, () => 0).join("") + result;
}
return result;
}
// webR/chan/message.ts
function newRequest(msg, transferables) {
return newRequestResponseMessage(
{
type: "request",
data: {
uuid: generateUUID(),
msg
}
},
transferables
);
}
function newResponse(uuid, resp, transferables) {
return newRequestResponseMessage(
{
type: "response",
data: {
uuid,
resp
}
},
transferables
);
}
function newRequestResponseMessage(msg, transferables) {
if (transferables) {
transfer(msg, transferables);
}
return msg;
}
function newSyncRequest(msg, data) {
return {
type: "sync-request",
data: { msg, reqData: data }
};
}
var encoder = new TextEncoder();
var decoder = new TextDecoder("utf-8");
function encodeData(data) {
return encoder.encode(JSON.stringify(data));
}
function decodeData(data) {
return JSON.parse(decoder.decode(data));
}
// webR/chan/task-main.ts
var encoder2 = new TextEncoder();
async function syncResponse(endpoint, data, response) {
try {
let { taskId, sizeBuffer, dataBuffer, signalBuffer } = data;
const bytes = encodeData(response);
const fits = bytes.length <= dataBuffer.length;
Atomics.store(sizeBuffer, SZ_BUF_SIZE_IDX, bytes.length);
Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, +fits);
if (!fits) {
const [uuid, dataPromise] = requestResponseMessage(endpoint);
dataBuffer.set(encoder2.encode(uuid));
await signalRequester(signalBuffer, taskId);
dataBuffer = (await dataPromise).dataBuffer;
}
dataBuffer.set(bytes);
Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, 1);
await signalRequester(signalBuffer, taskId);
} catch (e) {
console.warn(e);
}
}
function requestResponseMessage(ep) {
const id = generateUUID();
return [
id,
new Promise((resolve) => {
if (IN_NODE) {
ep.once("message", (message) => {
if (!message.id || message.id !== id) {
return;
}
resolve(message);
});
} else {
ep.addEventListener("message", function l(ev) {
if (!ev.data || !ev.data.id || ev.data.id !== id) {
return;
}
ep.removeEventListener("message", l);
resolve(ev.data);
});
}
if (ep.start) {
ep.start();
}
})
];
}
async function signalRequester(signalBuffer, taskId) {
const index = (taskId >> 1) % 32;
let sleepTime = 1;
while (Atomics.compareExchange(signalBuffer, index + 1, 0, taskId) !== 0) {
await sleep(sleepTime);
if (sleepTime < 32) {
sleepTime *= 2;
}
}
Atomics.or(signalBuffer, 0, 1 << index);
Atomics.notify(signalBuffer, 0);
}
// webR/chan/queue.ts
var _promises, _resolvers, _add, add_fn;
var AsyncQueue = class {
constructor() {
__privateAdd(this, _add);
__privateAdd(this, _promises, void 0);
__privateAdd(this, _resolvers, void 0);
__privateSet(this, _resolvers, []);
__privateSet(this, _promises, []);
}
put(t) {
if (!__privateGet(this, _resolvers).length) {
__privateMethod(this, _add, add_fn).call(this);
}
const resolve = __privateGet(this, _resolvers).shift();
resolve(t);
}
async get() {
if (!__privateGet(this, _promises).length) {
__privateMethod(this, _add, add_fn).call(this);
}
const promise = __privateGet(this, _promises).shift();
return promise;
}
isEmpty() {
return !__privateGet(this, _promises).length;
}
isBlocked() {
return !!__privateGet(this, _resolvers).length;
}
get length() {
return __privateGet(this, _promises).length - __privateGet(this, _resolvers).length;
}
};
_promises = new WeakMap();
_resolvers = new WeakMap();
_add = new WeakSet();
add_fn = function() {
__privateGet(this, _promises).push(
new Promise((resolve) => {
__privateGet(this, _resolvers).push(resolve);
})
);
};
// webR/payload.ts
function webRPayloadError(payload) {
const e = new Error(payload.obj.message);
e.name = payload.obj.name;
e.stack = payload.obj.stack;
return e;
}
function isWebRPayload(value) {
return value && typeof value === "object" && "payloadType" in value && "obj" in value;
}
function isWebRPayloadPtr(value) {
return isWebRPayload(value) && value.payloadType === "ptr";
}
// webR/chan/channel.ts
var _parked;
var ChannelMain = class {
constructor() {
this.inputQueue = new AsyncQueue();
this.outputQueue = new AsyncQueue();
__privateAdd(this, _parked, /* @__PURE__ */ new Map());
}
async read() {
return await this.outputQueue.get();
}
async flush() {
const msg = [];
while (!this.outputQueue.isEmpty()) {
msg.push(await this.read());
}
return msg;
}
write(msg) {
this.inputQueue.put(msg);
}
async request(msg, transferables) {
const req = newRequest(msg, transferables);
const { resolve, reject, promise } = promiseHandles();
__privateGet(this, _parked).set(req.data.uuid, { resolve, reject });
this.write(req);
return promise;
}
resolveResponse(msg) {
const uuid = msg.data.uuid;
const handles = __privateGet(this, _parked).get(uuid);
if (handles) {
const payload = msg.data.resp;
__privateGet(this, _parked).delete(uuid);
if (payload.payloadType === "err") {
handles.reject(webRPayloadError(payload));
} else {
handles.resolve(payload);
}
} else {
console.warn("Can't find request.");
}
}
};
_parked = new WeakMap();
// webR/chan/task-worker.ts
var decoder2 = new TextDecoder("utf-8");
var _scheduled, _resolved, _result, _exception, _syncGen;
var SyncTask = class {
constructor(endpoint, msg, transfers = []) {
__privateAdd(this, _scheduled, false);
__privateAdd(this, _resolved, void 0);
__privateAdd(this, _result, void 0);
__privateAdd(this, _exception, void 0);
__privateAdd(this, _syncGen, void 0);
this.syncifier = new _Syncifier();
this.endpoint = endpoint;
this.msg = msg;
this.transfers = transfers;
__privateSet(this, _resolved, false);
}
scheduleSync() {
if (__privateGet(this, _scheduled)) {
return;
}
__privateSet(this, _scheduled, true);
this.syncifier.scheduleTask(this);
__privateSet(this, _syncGen, this.doSync());
__privateGet(this, _syncGen).next();
return this;
}
poll() {
if (!__privateGet(this, _scheduled)) {
throw new Error("Task not synchronously scheduled");
}
const { done, value } = __privateGet(this, _syncGen).next();
if (!done) {
return false;
}
__privateSet(this, _resolved, true);
__privateSet(this, _result, value);
return true;
}
*doSync() {
const { endpoint, msg, transfers } = this;
const sizeBuffer = new Int32Array(new SharedArrayBuffer(8));
const signalBuffer = this.signalBuffer;
const taskId = this.taskId;
let dataBuffer = acquireDataBuffer(UUID_LENGTH);
const syncMsg = newSyncRequest(msg, {
sizeBuffer,
dataBuffer,
signalBuffer,
taskId
});
endpoint.postMessage(syncMsg, transfers);
yield;
if (Atomics.load(sizeBuffer, SZ_BUF_FITS_IDX) === SZ_BUF_DOESNT_FIT) {
const id = decoder2.decode(dataBuffer.slice(0, UUID_LENGTH));
releaseDataBuffer(dataBuffer);
const size2 = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);
dataBuffer = acquireDataBuffer(size2);
endpoint.postMessage({ id, dataBuffer });
yield;
}
const size = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);
return decodeData(dataBuffer.slice(0, size));
}
get result() {
if (__privateGet(this, _exception)) {
throw __privateGet(this, _exception);
}
if (__privateGet(this, _resolved)) {
return __privateGet(this, _result);
}
throw new Error("Not ready.");
}
syncify() {
this.scheduleSync();
this.syncifier.syncifyTask(this);
return this.result;
}
};
_scheduled = new WeakMap();
_resolved = new WeakMap();
_result = new WeakMap();
_exception = new WeakMap();
_syncGen = new WeakMap();
var _Syncifier = class {
constructor() {
this.nextTaskId = new Int32Array([1]);
this.signalBuffer = new Int32Array(new SharedArrayBuffer(32 * 4 + 4));
this.tasks = /* @__PURE__ */ new Map();
}
scheduleTask(task) {
task.taskId = this.nextTaskId[0];
this.nextTaskId[0] += 2;
task.signalBuffer = this.signalBuffer;
this.tasks.set(task.taskId, task);
}
waitOnSignalBuffer() {
const timeout = 50;
for (; ; ) {
const status = Atomics.wait(this.signalBuffer, 0, 0, timeout);
switch (status) {
case "ok":
case "not-equal":
return;
case "timed-out":
if (interruptBuffer[0] !== 0) {
handleInterrupt();
}
break;
default:
throw new Error("Unreachable");
}
}
}
*tasksIdsToWakeup() {
const flag = Atomics.load(this.signalBuffer, 0);
for (let i = 0; i < 32; i++) {
const bit = 1 << i;
if (flag & bit) {
Atomics.and(this.signalBuffer, 0, ~bit);
const wokenTask = Atomics.exchange(this.signalBuffer, i + 1, 0);
yield wokenTask;
}
}
}
pollTasks(task) {
let result = false;
for (const wokenTaskId of this.tasksIdsToWakeup()) {
const wokenTask = this.tasks.get(wokenTaskId);
if (!wokenTask) {
throw new Error(`Assertion error: unknown taskId ${wokenTaskId}.`);
}
if (wokenTask.poll()) {
this.tasks.delete(wokenTaskId);
if (wokenTask === task) {
result = true;
}
}
}
return result;
}
syncifyTask(task) {
for (; ; ) {
this.waitOnSignalBuffer();
if (this.pollTasks(task)) {
return;
}
}
}
};
var dataBuffers = [];
function acquireDataBuffer(size) {
const powerof2 = Math.ceil(Math.log2(size));
if (!dataBuffers[powerof2]) {
dataBuffers[powerof2] = [];
}
const result = dataBuffers[powerof2].pop();
if (result) {
result.fill(0);
return result;
}
return new Uint8Array(new SharedArrayBuffer(2 ** powerof2));
}
function releaseDataBuffer(buffer) {
const powerof2 = Math.ceil(Math.log2(buffer.byteLength));
dataBuffers[powerof2].push(buffer);
}
var interruptBuffer = new Int32Array(new ArrayBuffer(4));
var handleInterrupt = () => {
interruptBuffer[0] = 0;
throw new Error("Interrupted!");
};
function setInterruptHandler(handler) {
handleInterrupt = handler;
}
function setInterruptBuffer(buffer) {
interruptBuffer = new Int32Array(buffer);
}
// webR/emscripten.ts
var Module = {};
function dictEmFree(dict) {
Object.keys(dict).forEach((key) => Module._free(dict[key]));
}
// webR/chan/channel-shared.ts
if (IN_NODE) {
globalThis.Worker = require("worker_threads").Worker;
}
var _interruptBuffer, _handleEventsFromWorker, handleEventsFromWorker_fn, _onMessageFromWorker;
var SharedBufferChannelMain = class extends ChannelMain {
constructor(config) {
super();
__privateAdd(this, _handleEventsFromWorker);
__privateAdd(this, _interruptBuffer, void 0);
this.close = () => {
};
__privateAdd(this, _onMessageFromWorker, async (worker, message) => {
if (!message || !message.type) {
return;
}
switch (message.type) {
case "resolve":
__privateSet(this, _interruptBuffer, new Int32Array(message.data));
this.resolve();
return;
case "response":
this.resolveResponse(message);
return;
default:
this.outputQueue.put(message);
return;
case "sync-request": {
const msg = message;
const payload = msg.data.msg;
const reqData = msg.data.reqData;
switch (payload.type) {
case "read": {
const response = await this.inputQueue.get();
await syncResponse(worker, reqData, response);
break;
}
default:
throw new TypeError(`Unsupported request type '${payload.type}'.`);
}