@julclang/julc-vm-wasm 0.0.0-oidc-bootstrap.0 → 0.1.0-pre21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3306 @@
1
+ 'use strict';
2
+
3
+
4
+ /**
5
+ * @suppress {checkVars,checkTypes,duplicate}
6
+ * @nocollapse
7
+ */
8
+ var GraalVM = {};
9
+ (function() {(function() {(function() {
10
+
11
+ /*
12
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
13
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
14
+ *
15
+ * This code is free software; you can redistribute it and/or modify it
16
+ * under the terms of the GNU General Public License version 2 only, as
17
+ * published by the Free Software Foundation. Oracle designates this
18
+ * particular file as subject to the "Classpath" exception as provided
19
+ * by Oracle in the LICENSE file that accompanied this code.
20
+ *
21
+ * This code is distributed in the hope that it will be useful, but WITHOUT
22
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
23
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
24
+ * version 2 for more details (a copy is included in the LICENSE file that
25
+ * accompanied this code).
26
+ *
27
+ * You should have received a copy of the GNU General Public License version
28
+ * 2 along with this work; if not, write to the Free Software Foundation,
29
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
30
+ *
31
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
32
+ * or visit www.oracle.com if you need additional information or have any
33
+ * questions.
34
+ */
35
+
36
+ /**
37
+ * Represents a potential feature of the JS runtime.
38
+ *
39
+ * During construction, the detection callback is called to detect whether the runtime supports the feature.
40
+ * The callback returns whether the feature was detected and may store some data
41
+ * into the 'data' member for future use.
42
+ */
43
+ class Feature {
44
+ constructor(descr, detection_callback) {
45
+ this.description = descr;
46
+ this.data = {};
47
+ this.detected = detection_callback(this.data);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Specialized feature to detect global variables.
53
+ */
54
+ class GlobalVariableFeature extends Feature {
55
+ constructor(descr, var_name) {
56
+ super(descr, GlobalVariableFeature.detection_callback.bind(null, var_name));
57
+ }
58
+
59
+ /**
60
+ * Function to detect a global variable.
61
+ *
62
+ * Uses the 'globalThis' object which should represent the global scope in
63
+ * modern runtimes.
64
+ */
65
+ static detection_callback(var_name, data) {
66
+ if (var_name in globalThis) {
67
+ data.global = globalThis[var_name];
68
+ return true;
69
+ }
70
+
71
+ return false;
72
+ }
73
+
74
+ /**
75
+ * Returns the global detected by this feature.
76
+ */
77
+ get() {
78
+ return this.data.global;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Specialized feature to detect the presence of Node.js modules.
84
+ */
85
+ class RequireFeature extends Feature {
86
+ constructor(descr, module_name) {
87
+ super(descr, RequireFeature.detection_callback.bind(null, module_name));
88
+ }
89
+
90
+ /**
91
+ * Function to detect a Node.js module.
92
+ */
93
+ static detection_callback(module_name, data) {
94
+ if (typeof require != "function") {
95
+ return false;
96
+ }
97
+
98
+ try {
99
+ data.module = require(module_name);
100
+ return true;
101
+ } catch (e) {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Returns the module detected by this feature.
108
+ */
109
+ get() {
110
+ return this.data.module;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Collection of features needed for runtime functions.
116
+ */
117
+ let features = {
118
+ // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
119
+ fetch: new GlobalVariableFeature("Presence of the Fetch API", "fetch"),
120
+
121
+ // https://nodejs.org/api/fs.html#promises-api
122
+ node_fs: new RequireFeature("Presence of Node.js fs promises module", "fs/promises"),
123
+
124
+ // https://nodejs.org/api/https.html
125
+ node_https: new RequireFeature("Presence of Node.js https module", "https"),
126
+
127
+ // https://nodejs.org/api/process.html
128
+ node_process: new RequireFeature("Presence of Node.js process module", "process"),
129
+
130
+ /**
131
+ * Technically, '__filename' is not a global variable, it is a variable in the module scope.
132
+ * https://nodejs.org/api/globals.html#__filename
133
+ */
134
+ filename: new Feature("Presence of __filename global", (d) => {
135
+ if (typeof __filename != "undefined") {
136
+ d.filename = __filename;
137
+ return true;
138
+ }
139
+
140
+ return false;
141
+ }),
142
+
143
+ // https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript
144
+ currentScript: new Feature("Presence of document.currentScript global", (d) => {
145
+ if (
146
+ typeof document != "undefined" &&
147
+ "currentScript" in document &&
148
+ document.currentScript != null &&
149
+ "src" in document.currentScript
150
+ ) {
151
+ d.currentScript = document.currentScript;
152
+ return true;
153
+ }
154
+
155
+ return false;
156
+ }),
157
+
158
+ // https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/location
159
+ location: new Feature("Presence of Web worker location", (d) => {
160
+ if (typeof self != "undefined") {
161
+ d.location = self.location;
162
+ return true;
163
+ }
164
+ return false;
165
+ }),
166
+ };
167
+
168
+
169
+ /*
170
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
171
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
172
+ *
173
+ * This code is free software; you can redistribute it and/or modify it
174
+ * under the terms of the GNU General Public License version 2 only, as
175
+ * published by the Free Software Foundation. Oracle designates this
176
+ * particular file as subject to the "Classpath" exception as provided
177
+ * by Oracle in the LICENSE file that accompanied this code.
178
+ *
179
+ * This code is distributed in the hope that it will be useful, but WITHOUT
180
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
181
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
182
+ * version 2 for more details (a copy is included in the LICENSE file that
183
+ * accompanied this code).
184
+ *
185
+ * You should have received a copy of the GNU General Public License version
186
+ * 2 along with this work; if not, write to the Free Software Foundation,
187
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
188
+ *
189
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
190
+ * or visit www.oracle.com if you need additional information or have any
191
+ * questions.
192
+ */
193
+ function charArrayToString(arr) {
194
+ let res = [];
195
+
196
+ const len = 512;
197
+
198
+ for (let i = 0; i < arr.length; i += len) {
199
+ res.push(String.fromCharCode(...arr.slice(i, i + len)));
200
+ }
201
+ return res.join("");
202
+ }
203
+
204
+
205
+ /*
206
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
207
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
208
+ *
209
+ * This code is free software; you can redistribute it and/or modify it
210
+ * under the terms of the GNU General Public License version 2 only, as
211
+ * published by the Free Software Foundation. Oracle designates this
212
+ * particular file as subject to the "Classpath" exception as provided
213
+ * by Oracle in the LICENSE file that accompanied this code.
214
+ *
215
+ * This code is distributed in the hope that it will be useful, but WITHOUT
216
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
217
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
218
+ * version 2 for more details (a copy is included in the LICENSE file that
219
+ * accompanied this code).
220
+ *
221
+ * You should have received a copy of the GNU General Public License version
222
+ * 2 along with this work; if not, write to the Free Software Foundation,
223
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
224
+ *
225
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
226
+ * or visit www.oracle.com if you need additional information or have any
227
+ * questions.
228
+ */
229
+ function llog(p) {
230
+ if (p instanceof Error) {
231
+ console.log(p);
232
+ } else if (p instanceof Object) {
233
+ console.log(p.toString());
234
+ } else {
235
+ console.log(p);
236
+ }
237
+ }
238
+
239
+ /**
240
+ * A writer emulating stdout and stderr using console.log and console.error
241
+ *
242
+ * Since those functions cannot print without newline, lines are buffered but
243
+ * without a max buffer size.
244
+ */
245
+ class ConsoleWriter {
246
+ constructor(logger) {
247
+ this.line = "";
248
+ this.newline = "\n".charCodeAt(0);
249
+ this.closed = false;
250
+ this.logger = logger;
251
+ }
252
+
253
+ printChars(chars) {
254
+ let index = chars.lastIndexOf(this.newline);
255
+
256
+ if (index >= 0) {
257
+ this.line += charArrayToString(chars.slice(0, index));
258
+ this.writeLine();
259
+ chars = chars.slice(index + 1);
260
+ }
261
+
262
+ this.line += charArrayToString(chars);
263
+ }
264
+
265
+ writeLine() {
266
+ this.logger(this.line);
267
+ this.line = "";
268
+ }
269
+
270
+ flush() {
271
+ if (this.line.length > 0) {
272
+ // In JS we cannot print without newline, so flushing will always produce one
273
+ this.writeLine();
274
+ }
275
+ }
276
+
277
+ close() {
278
+ if (this.closed) {
279
+ return;
280
+ }
281
+ this.closed = true;
282
+
283
+ this.flush();
284
+ }
285
+ }
286
+
287
+ var stdoutWriter = new ConsoleWriter(console.log);
288
+ var stderrWriter = new ConsoleWriter(console.error);
289
+
290
+
291
+ /*
292
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
293
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
294
+ *
295
+ * This code is free software; you can redistribute it and/or modify it
296
+ * under the terms of the GNU General Public License version 2 only, as
297
+ * published by the Free Software Foundation. Oracle designates this
298
+ * particular file as subject to the "Classpath" exception as provided
299
+ * by Oracle in the LICENSE file that accompanied this code.
300
+ *
301
+ * This code is distributed in the hope that it will be useful, but WITHOUT
302
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
303
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
304
+ * version 2 for more details (a copy is included in the LICENSE file that
305
+ * accompanied this code).
306
+ *
307
+ * You should have received a copy of the GNU General Public License version
308
+ * 2 along with this work; if not, write to the Free Software Foundation,
309
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
310
+ *
311
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
312
+ * or visit www.oracle.com if you need additional information or have any
313
+ * questions.
314
+ */
315
+
316
+ /**
317
+ * Class that holds the configuration of the VM.
318
+ */
319
+ class Config {
320
+ constructor() {
321
+ this.libraries = {};
322
+ this.currentWorkingDirectory = "/root";
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Class that holds the data required to start the VM.
328
+ */
329
+ class Data {
330
+ constructor(config) {
331
+ /**
332
+ * User-specified configuration object.
333
+ *
334
+ * @type Config
335
+ */
336
+ this.config = config;
337
+
338
+ /**
339
+ * Optionally holds a binary support file.
340
+ */
341
+ this.binaryImageHeap = null;
342
+
343
+ /**
344
+ * Maps the library names to prefetched content during VM bootup.
345
+ * After the VM is initialized, the keys are retained, but values are set to null.
346
+ */
347
+ this.libraries = {};
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Dummy object that exists only to avoid warnings in IDEs for the `$t[name]` expressions (used in JavaScript support files).
353
+ */
354
+ const $t = {};
355
+
356
+ /**
357
+ * For a given JavaScript class, returns an object that can lookup its properties.
358
+ */
359
+ function cprops(cls) {
360
+ return cls.prototype;
361
+ }
362
+
363
+ /**
364
+ * Placeholder for lazy-value initializers.
365
+ */
366
+ class LazyValueThunk {
367
+ constructor(initializer) {
368
+ this.initializer = initializer;
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Creates a lazy property on the specified object.
374
+ */
375
+ function lazy(obj, name, initializer) {
376
+ let state = new LazyValueThunk(initializer);
377
+ Object.defineProperty(obj, name, {
378
+ configurable: false,
379
+ enumerable: true,
380
+ get: () => {
381
+ if (state instanceof LazyValueThunk) {
382
+ state = state.initializer();
383
+ }
384
+ return state;
385
+ },
386
+ set: () => {
387
+ throw new Error("Property is not writable.");
388
+ },
389
+ });
390
+ }
391
+
392
+ /**
393
+ * Placeholder for a method and its signature.
394
+ */
395
+ class MethodMetadata {
396
+ constructor(method, isStatic, returnHub, ...paramHubs) {
397
+ this.method = method;
398
+ this.isStatic = isStatic;
399
+ this.returnHub = returnHub;
400
+ this.paramHubs = paramHubs;
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Create MethodMetadata object for an instance method.
406
+ */
407
+ function mmeta(method, returnHub, ...paramHubs) {
408
+ return new MethodMetadata(method, false, returnHub, ...paramHubs);
409
+ }
410
+
411
+ /**
412
+ * Create MethodMetadata object for a static method.
413
+ */
414
+ function smmeta(method, returnHub, ...paramHubs) {
415
+ return new MethodMetadata(method, true, returnHub, ...paramHubs);
416
+ }
417
+
418
+ /**
419
+ * Describes extra class metadata used by the runtime.
420
+ */
421
+ class ClassMetadata {
422
+ /**
423
+ * Constructs the class metadata.
424
+ *
425
+ * @param ft Field table
426
+ * @param singleAbstractMethod Method metadata for the single abstract method, when the class implements exactly one functional interface
427
+ * @param methodTable Dictionary mapping each method name to the list of overloaded signatures
428
+ */
429
+ constructor(ft, singleAbstractMethod = undefined, methodTable = undefined) {
430
+ this.ft = ft;
431
+ this.singleAbstractMethod = singleAbstractMethod;
432
+ this.methodTable = methodTable;
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Class for the various runtime utilities.
438
+ */
439
+ class Runtime {
440
+ constructor() {
441
+ this.isLittleEndian = false;
442
+ /**
443
+ * Dictionary of all initializer functions.
444
+ */
445
+ this.jsResourceInits = {};
446
+ /**
447
+ * The data object of the current VM, which contains the configuration settings,
448
+ * optionally a binary-encoded image heap, and other resources.
449
+ *
450
+ * The initial data value is present in the enclosing scope.
451
+ *
452
+ * @type Data
453
+ */
454
+ this.data = null;
455
+ /**
456
+ * Map from full Java class names to corresponding Java hubs, for classes that are accessible outside of the image.
457
+ */
458
+ this.hubs = {};
459
+ /**
460
+ * The table of native functions that can be invoked via indirect calls.
461
+ *
462
+ * The index in this table represents the address of the function.
463
+ * The zero-th entry is always set to null.
464
+ */
465
+ this.funtab = [null];
466
+ /**
467
+ * Map of internal symbols that are used during execution.
468
+ */
469
+ Object.defineProperty(this, "symbol", {
470
+ writable: false,
471
+ configurable: false,
472
+ value: {
473
+ /**
474
+ * Symbol used to symbolically get the to-JavaScript-native coercion object on the Java proxy.
475
+ *
476
+ * This symbol is available as a property on Java proxies, and will return a special object
477
+ * that can coerce the Java proxy to various native JavaScript values.
478
+ *
479
+ * See the ProxyHandler class for more details.
480
+ */
481
+ javaScriptCoerceAs: Symbol("__javascript_coerce_as__"),
482
+
483
+ /**
484
+ * Key used by Web Image to store the corresponding JS native value as a property of JSValue objects.
485
+ *
486
+ * Used by the JS annotation.
487
+ *
488
+ * Use conversion.setJavaScriptNative and conversion.extractJavaScriptNative to access that property
489
+ * instead of using this symbol directly.
490
+ */
491
+ javaScriptNative: Symbol("__javascript_native__"),
492
+
493
+ /**
494
+ * Key used by proxies around Java objects to extract the underlying Java object for internal processing.
495
+ */
496
+ javaNative: Symbol("__java_native__"),
497
+
498
+ /**
499
+ * Property key that returns `true` when accessed on a proxy object, which proxies a native Java object.
500
+ *
501
+ * This property is advertised as an own property on the proxy (unlike `javaNative`) and can be looked
502
+ * up using `Object.getOwnPropertyDescriptor`. Instead of directly trying to access `javaNative`, this
503
+ * property should be looked up using `Object.getOwnPropertyDescriptor` first.
504
+ * Frameworks like Vue may complain when accessing the `javaNative` property on arbitrary objects, using
505
+ * `getOwnPropertyDescriptor` is a bit less intrusive and doesn't produce warnings in Vue.
506
+ */
507
+ isProxy: Symbol("__is_java_proxy__"),
508
+
509
+ /**
510
+ * Key used to store the runtime-generated proxy handler inside the Java class.
511
+ *
512
+ * The handler is created lazily the first time that the corresponding class is added
513
+ *
514
+ * Use getOrCreateProxyHandler to retrieve the proxy handler instead of using this symbol directly.
515
+ */
516
+ javaProxyHandler: Symbol("__java_proxy_handler__"),
517
+
518
+ /**
519
+ * Key used to store the extra class metadata when emitting Java classes.
520
+ */
521
+ classMeta: Symbol("__class_metadata__"),
522
+
523
+ /**
524
+ * Key for the hub-object property that points to the corresponding generated JavaScript class.
525
+ */
526
+ jsClass: Symbol("__js_class__"),
527
+
528
+ /**
529
+ * Key for the property on primitive hubs, which points to the corresponding boxed hub.
530
+ */
531
+ boxedHub: Symbol("__boxed_hub__"),
532
+
533
+ /**
534
+ * Key for the property on primitive hubs, which holds the boxing function.
535
+ */
536
+ box: Symbol("__box__"),
537
+
538
+ /**
539
+ * Key for the property on primitive hubs, which holds the unboxing function.
540
+ */
541
+ unbox: Symbol("__unbox__"),
542
+
543
+ /**
544
+ * Key for the constructor-overload list that is stored in the class metadata.
545
+ */
546
+ ctor: Symbol("__ctor__"),
547
+
548
+ /**
549
+ * Internal value passed to JavaScript mirror-class constructors
550
+ * to denote that the mirrored class was instantiated from Java.
551
+ *
552
+ * This is used when a JSObject subclass gets constructed from Java.
553
+ */
554
+ skipJavaCtor: Symbol("__skip_java_ctor__"),
555
+
556
+ /**
557
+ * Symbol for the Java toString method.
558
+ */
559
+ toString: Symbol("__toString__"),
560
+ },
561
+ });
562
+
563
+ /**
564
+ * The holder of JavaScript mirror class for JSObject subclasses.
565
+ */
566
+ this.mirrors = {};
567
+ }
568
+
569
+ /**
570
+ * Use the build-time endianness at run-time.
571
+ *
572
+ * Unsafe operations that write values to byte arrays at build-time assumes the
573
+ * endianness of the build machine. Therefore, unsafe read and write operations
574
+ * at run-time need to assume the same endianness.
575
+ */
576
+ setEndianness(isLittleEndian) {
577
+ runtime.isLittleEndian = isLittleEndian;
578
+ }
579
+
580
+ _ensurePackage(container, name) {
581
+ const elements = name === "" ? [] : name.split(".");
582
+ let current = container;
583
+ for (let i = 0; i < elements.length; i++) {
584
+ const element = elements[i];
585
+ current = element in current ? current[element] : (current[element] = {});
586
+ }
587
+ return current;
588
+ }
589
+
590
+ /**
591
+ * Get or create the specified exported JavaScript mirror-class export package on the VM object.
592
+ *
593
+ * @param name Full Java name of the package
594
+ */
595
+ ensureExportPackage(name) {
596
+ return this._ensurePackage(vm.exports, name);
597
+ }
598
+
599
+ /**
600
+ * Get or create the specified exported JavaScript mirror-class package on the Runtime object.
601
+ *
602
+ * @param name Full Java name of the package
603
+ */
604
+ ensureVmPackage(name) {
605
+ return this._ensurePackage(runtime.mirrors, name);
606
+ }
607
+
608
+ /**
609
+ * Get an existing exported JavaScript mirror class on the Runtime object.
610
+ *
611
+ * @param className Full Java name of the class
612
+ */
613
+ vmClass(className) {
614
+ const elements = className.split(".");
615
+ let current = runtime.mirrors;
616
+ for (let i = 0; i < elements.length; i++) {
617
+ const element = elements[i];
618
+ if (element in current) {
619
+ current = current[element];
620
+ } else {
621
+ return null;
622
+ }
623
+ }
624
+ return current;
625
+ }
626
+
627
+ /**
628
+ * Returns the array with all the prefetched library names.
629
+ */
630
+ prefetchedLibraryNames() {
631
+ const names = [];
632
+ for (const name in this.data.libraries) {
633
+ names.push(name);
634
+ }
635
+ return names;
636
+ }
637
+
638
+ /**
639
+ * Adds a function to the function table.
640
+ *
641
+ * @param f The function to add
642
+ * @returns {number} The address of the newly added function
643
+ */
644
+ addToFuntab(f) {
645
+ this.funtab.push(f);
646
+ return runtime.funtab.length - 1;
647
+ }
648
+
649
+ /**
650
+ * Fetches binary data from the given url.
651
+ *
652
+ * @param url
653
+ * @returns {!Promise<!ArrayBuffer>}
654
+ */
655
+ fetchData(url) {
656
+ return Promise.reject(new Error("fetchData is not supported"));
657
+ }
658
+
659
+ /**
660
+ * Fetches UTF8 text from the given url.
661
+ *
662
+ * @param url
663
+ * @returns {!Promise<!String>}
664
+ */
665
+ fetchText(url) {
666
+ return Promise.reject(new Error("fetchText is not supported"));
667
+ }
668
+
669
+ /**
670
+ * Sets the exit code for the VM.
671
+ */
672
+ setExitCode(c) {
673
+ vm.exitCode = c;
674
+ }
675
+
676
+ /**
677
+ * Returns the absolute path of the JS file WebImage is running in.
678
+ *
679
+ * Depending on the runtime, this may be a URL or an absolute filesystem path.
680
+ * @returns {!String}
681
+ */
682
+ getCurrentFile() {
683
+ throw new Error("getCurrentFile is not supported");
684
+ }
685
+ }
686
+
687
+ /**
688
+ * Instance of the internal runtime state of the VM.
689
+ */
690
+ const runtime = new Runtime();
691
+
692
+ /**
693
+ * VM state that is exposed, and which represents the VM API accessible to external users.
694
+ */
695
+ class VM {
696
+ constructor() {
697
+ this.exitCode = 0;
698
+ this.exports = {};
699
+ this.symbol = {};
700
+ /**
701
+ * The to-JavaScript-native coercion symbol in the external API.
702
+ */
703
+ Object.defineProperty(this.symbol, "as", {
704
+ configurable: false,
705
+ enumerable: true,
706
+ writable: false,
707
+ value: runtime.symbol.javaScriptCoerceAs,
708
+ });
709
+ /**
710
+ * The symbol for the Java toString method in the external API.
711
+ */
712
+ Object.defineProperty(this.symbol, "toString", {
713
+ configurable: false,
714
+ enumerable: true,
715
+ writable: false,
716
+ value: runtime.symbol.toString,
717
+ });
718
+ }
719
+
720
+ /**
721
+ * Coerce the specified JavaScript value to the specified Java type.
722
+ *
723
+ * For precise summary of the coercion rules, please see the JS annotation JavaDoc.
724
+ *
725
+ * The implementation for this function is injected later.
726
+ *
727
+ * @param javaScriptValue The JavaScript value to coerce
728
+ * @param type The name of the Java class to coerce to, or a Java Proxy representing the target class.
729
+ * @returns {*} The closest corresponding Java Proxy value
730
+ */
731
+ as(javaScriptValue, type) {
732
+ throw new Error("VM.as is not supported in this backend or it was called too early");
733
+ }
734
+ }
735
+
736
+ /**
737
+ * Instance of the class that represents the public VM API.
738
+ */
739
+ const vm = new VM();
740
+
741
+ if (features.node_fs.detected && features.node_https.detected) {
742
+ runtime.fetchText = (url) => {
743
+ if (url.startsWith("http://") || url.startsWith("https://")) {
744
+ return new Promise((fulfill, reject) => {
745
+ let content = [];
746
+ features.node_https
747
+ .get()
748
+ .get(url, (r) => {
749
+ r.on("data", (data) => {
750
+ content.push(data);
751
+ });
752
+ r.on("end", () => {
753
+ fulfill(content.join(""));
754
+ });
755
+ })
756
+ .on("error", (e) => {
757
+ reject(e);
758
+ });
759
+ });
760
+ } else {
761
+ return features.node_fs.get().readFile(url, "utf8");
762
+ }
763
+ };
764
+ runtime.fetchData = (url) => {
765
+ return features.node_fs
766
+ .get()
767
+ .readFile(url)
768
+ .then((d) => d.buffer);
769
+ };
770
+ } else if (features.fetch.detected) {
771
+ runtime.fetchText = (url) =>
772
+ features.fetch
773
+ .get()(url)
774
+ .then((r) => r.text());
775
+ runtime.fetchData = (url) =>
776
+ features.fetch
777
+ .get()(url)
778
+ .then((response) => {
779
+ if (!response.ok) {
780
+ throw new Error(`Failed to load data at '${url}': ${response.status} ${response.statusText}`);
781
+ }
782
+ return response.arrayBuffer();
783
+ });
784
+ }
785
+
786
+ if (features.node_process.detected) {
787
+ // Extend the setExitCode function to also set the exit code of the runtime.
788
+ let oldFun = runtime.setExitCode;
789
+ runtime.setExitCode = (exitCode) => {
790
+ oldFun(exitCode);
791
+ features.node_process.get().exitCode = exitCode;
792
+ };
793
+ }
794
+
795
+ if (features.filename.detected) {
796
+ runtime.getCurrentFile = () => features.filename.data.filename;
797
+ } else if (features.currentScript.detected) {
798
+ runtime.getCurrentFile = () => features.currentScript.data.currentScript.src;
799
+ } else if (features.location.detected) {
800
+ runtime.getCurrentFile = () => features.location.data.location.href;
801
+ }
802
+
803
+
804
+ /*
805
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
806
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
807
+ *
808
+ * This code is free software; you can redistribute it and/or modify it
809
+ * under the terms of the GNU General Public License version 2 only, as
810
+ * published by the Free Software Foundation. Oracle designates this
811
+ * particular file as subject to the "Classpath" exception as provided
812
+ * by Oracle in the LICENSE file that accompanied this code.
813
+ *
814
+ * This code is distributed in the hope that it will be useful, but WITHOUT
815
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
816
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
817
+ * version 2 for more details (a copy is included in the LICENSE file that
818
+ * accompanied this code).
819
+ *
820
+ * You should have received a copy of the GNU General Public License version
821
+ * 2 along with this work; if not, write to the Free Software Foundation,
822
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
823
+ *
824
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
825
+ * or visit www.oracle.com if you need additional information or have any
826
+ * questions.
827
+ */
828
+
829
+ /**
830
+ * Imports object passed to the WASM module during instantiation.
831
+ *
832
+ * @see WasmImports
833
+ */
834
+ const wasmImports = {};
835
+
836
+ /**
837
+ * Imports for operations that cannot be performed (or be easily emulated) in WASM.
838
+ */
839
+ wasmImports.compat = {
840
+ f64rem: (x, y) => x % y,
841
+ f64log: Math.log,
842
+ f64log10: Math.log10,
843
+ f64sin: Math.sin,
844
+ f64cos: Math.cos,
845
+ f64tan: Math.tan,
846
+ f64tanh: Math.tanh,
847
+ f64exp: Math.exp,
848
+ f64pow: Math.pow,
849
+ f64cbrt: Math.cbrt,
850
+ f32rem: (x, y) => x % y,
851
+ };
852
+
853
+ /**
854
+ * Imports relating to I/O.
855
+ */
856
+ wasmImports.io = {};
857
+
858
+ /**
859
+ * Loads and instantiates the appropriate WebAssembly module.
860
+ *
861
+ * The module path is given by config.wasm_path, if specified, otherwise it is loaded relative to the current script file.
862
+ */
863
+ async function wasmInstantiate(config, args) {
864
+ const wasmPath = config.wasm_path || runtime.getCurrentFile() + ".wasm";
865
+ const file = await runtime.fetchData(wasmPath);
866
+ const result = await WebAssembly.instantiate(file, wasmImports);
867
+ return {
868
+ instance: result.instance,
869
+ memory: result.instance.exports.memory,
870
+ };
871
+ }
872
+
873
+ /**
874
+ * Runs the main entry point of the given WebAssembly module.
875
+ */
876
+ function wasmRun(args) {
877
+ try {
878
+ doRun(args);
879
+ } catch (e) {
880
+ console.log("Uncaught internal error:");
881
+ console.log(e);
882
+ runtime.setExitCode(1);
883
+ }
884
+ }
885
+
886
+ function getExports() {
887
+ return runtime.data.wasm.instance.exports;
888
+ }
889
+
890
+ function getExport(name) {
891
+ return getExports()[name];
892
+ }
893
+
894
+
895
+ /*
896
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
897
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
898
+ *
899
+ * This code is free software; you can redistribute it and/or modify it
900
+ * under the terms of the GNU General Public License version 2 only, as
901
+ * published by the Free Software Foundation. Oracle designates this
902
+ * particular file as subject to the "Classpath" exception as provided
903
+ * by Oracle in the LICENSE file that accompanied this code.
904
+ *
905
+ * This code is distributed in the hope that it will be useful, but WITHOUT
906
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
907
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
908
+ * version 2 for more details (a copy is included in the LICENSE file that
909
+ * accompanied this code).
910
+ *
911
+ * You should have received a copy of the GNU General Public License version
912
+ * 2 along with this work; if not, write to the Free Software Foundation,
913
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
914
+ *
915
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
916
+ * or visit www.oracle.com if you need additional information or have any
917
+ * questions.
918
+ */
919
+
920
+ /**
921
+ * Constructs Java string from JavaScript string.
922
+ */
923
+ function toJavaString(jsStr) {
924
+ const length = jsStr.length;
925
+ const charArray = getExport("array.char.create")(length);
926
+
927
+ for (let i = 0; i < length; i++) {
928
+ getExport("array.char.write")(charArray, i, jsStr.charCodeAt(i));
929
+ }
930
+
931
+ return getExport("string.fromchars")(charArray);
932
+ }
933
+
934
+ /**
935
+ * Constructs a Java string array (String[]) from a JavaScript array of
936
+ * JavaScript strings.
937
+ */
938
+ function toJavaStringArray(jsStrings) {
939
+ const length = jsStrings.length;
940
+ const stringArray = getExport("array.string.create")(length);
941
+
942
+ for (let i = 0; i < length; i++) {
943
+ getExport("array.object.write")(stringArray, i, toJavaString(jsStrings[i]));
944
+ }
945
+
946
+ return stringArray;
947
+ }
948
+
949
+
950
+ /*
951
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
952
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
953
+ *
954
+ * This code is free software; you can redistribute it and/or modify it
955
+ * under the terms of the GNU General Public License version 2 only, as
956
+ * published by the Free Software Foundation. Oracle designates this
957
+ * particular file as subject to the "Classpath" exception as provided
958
+ * by Oracle in the LICENSE file that accompanied this code.
959
+ *
960
+ * This code is distributed in the hope that it will be useful, but WITHOUT
961
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
962
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
963
+ * version 2 for more details (a copy is included in the LICENSE file that
964
+ * accompanied this code).
965
+ *
966
+ * You should have received a copy of the GNU General Public License version
967
+ * 2 along with this work; if not, write to the Free Software Foundation,
968
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
969
+ *
970
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
971
+ * or visit www.oracle.com if you need additional information or have any
972
+ * questions.
973
+ */
974
+
975
+ /**
976
+ * Checks if the given string is an array index.
977
+ *
978
+ * Proxied accesses always get a string property (even for indexed accesses) so
979
+ * we need to check if the property access is an indexed access.
980
+ *
981
+ * A property is an index if the numeric index it is refering to has the same
982
+ * string representation as the original property.
983
+ * E.g the string '010' is a property while '10' is an index.
984
+ */
985
+ function isArrayIndex(property) {
986
+ try {
987
+ return Number(property).toString() === property;
988
+ } catch (e) {
989
+ // Catch clause because not all property keys (e.g. symbols) can be
990
+ // converted to a number.
991
+ return false;
992
+ }
993
+ }
994
+
995
+ /**
996
+ * Proxy handler that proxies all array element and length accesses to a Wasm
997
+ * array and everything else to the underlying array.
998
+ *
999
+ * See `proxyArray` function for more information.
1000
+ */
1001
+ class ArrayProxyHandler {
1002
+ /**
1003
+ * Reference to the Wasm-world object.
1004
+ *
1005
+ * In this case, this will be a Wasm struct containing a Wasm array.
1006
+ */
1007
+ #wasmObject;
1008
+
1009
+ /**
1010
+ * Immutable length of the array, determined during construction.
1011
+ */
1012
+ #length;
1013
+
1014
+ /**
1015
+ * A callable (usually an exported function) that accepts the Wasm object
1016
+ * and an index and returns the element at that location.
1017
+ */
1018
+ #reader;
1019
+
1020
+ constructor(wasmObject, reader) {
1021
+ this.#wasmObject = wasmObject;
1022
+ this.#length = getExport("array.length")(wasmObject);
1023
+ this.#reader = reader;
1024
+ }
1025
+
1026
+ #isInBounds(idx) {
1027
+ return idx >= 0 && idx < this.#length;
1028
+ }
1029
+
1030
+ #getElement(idx) {
1031
+ /*
1032
+ * We need an additional bounds check here because Wasm will trap,
1033
+ * while JS expects an undefined value.
1034
+ */
1035
+ if (this.#isInBounds(idx)) {
1036
+ return this.#reader(this.#wasmObject, idx);
1037
+ } else {
1038
+ return undefined;
1039
+ }
1040
+ }
1041
+
1042
+ defineProperty() {
1043
+ throw new TypeError("This array is immutable. Attempted to call defineProperty");
1044
+ }
1045
+
1046
+ deleteProperty() {
1047
+ throw new TypeError("This array is immutable. Attempted to call deleteProperty");
1048
+ }
1049
+
1050
+ /**
1051
+ * Indexed accesses and the `length` property are serviced from the Wasm
1052
+ * object, everything else goes to the underlying object.
1053
+ */
1054
+ get(target, property, receiver) {
1055
+ if (isArrayIndex(property)) {
1056
+ return this.#getElement(property);
1057
+ } else if (property == "length") {
1058
+ return this.#length;
1059
+ } else {
1060
+ return Reflect.get(target, property, receiver);
1061
+ }
1062
+ }
1063
+
1064
+ getOwnPropertyDescriptor(target, property) {
1065
+ if (isArrayIndex(property)) {
1066
+ return {
1067
+ value: this.#getElement(property),
1068
+ writable: false,
1069
+ enumerable: true,
1070
+ configurable: false,
1071
+ };
1072
+ } else {
1073
+ return Reflect.getOwnPropertyDescriptor(target, property);
1074
+ }
1075
+ }
1076
+
1077
+ has(target, property) {
1078
+ if (isArrayIndex(property)) {
1079
+ return this.#isInBounds(Number(property));
1080
+ } else {
1081
+ return Reflect.has(target, property);
1082
+ }
1083
+ }
1084
+
1085
+ isExtensible() {
1086
+ return false;
1087
+ }
1088
+
1089
+ /**
1090
+ * Returns the array's own enumerable string-keyed property names.
1091
+ *
1092
+ * For arrays this is simply an array of all indices in string form.
1093
+ */
1094
+ ownKeys() {
1095
+ return Object.keys(Array.from({ length: this.#length }, (x, i) => i));
1096
+ }
1097
+
1098
+ preventExtensions() {
1099
+ // Do nothing this object is already not extensible
1100
+ }
1101
+
1102
+ set() {
1103
+ throw new TypeError("This array is immutable. Attempted to call set");
1104
+ }
1105
+
1106
+ setPrototypeOf() {
1107
+ throw new TypeError("This array is immutable. Attempted to call setPrototypeOf");
1108
+ }
1109
+ }
1110
+
1111
+ /**
1112
+ * Creates a read-only view on a Wasm array that looks like a JavaScript Array.
1113
+ *
1114
+ * The proxy is backed by an Array instance (albeit an empty one) and any
1115
+ * accesses except for `length` and indexed accesses (see `isArrayIndex`) are
1116
+ * proxied to the original object.
1117
+ * Because the `Array.prototype` methods are all generic and only access
1118
+ * `length` and the indices, this works. For example if `indexOf` is called on
1119
+ * the proxy, `Array.prototype.indexOf` is called with the proxy bound to
1120
+ * `this`, thus the `indexOf` implementation goes through the proxy when
1121
+ * accessing elements or determining the array length.
1122
+ */
1123
+ function proxyArray(a, reader) {
1124
+ return new Proxy(new Array(), new ArrayProxyHandler(a, reader));
1125
+ }
1126
+
1127
+ function proxyCharArray(a) {
1128
+ return proxyArray(a, getExport("array.char.read"));
1129
+ }
1130
+
1131
+ wasmImports.convert = {};
1132
+ wasmImports.convert.proxyCharArray = proxyCharArray;
1133
+
1134
+
1135
+ /*
1136
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
1137
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1138
+ *
1139
+ * This code is free software; you can redistribute it and/or modify it
1140
+ * under the terms of the GNU General Public License version 2 only, as
1141
+ * published by the Free Software Foundation. Oracle designates this
1142
+ * particular file as subject to the "Classpath" exception as provided
1143
+ * by Oracle in the LICENSE file that accompanied this code.
1144
+ *
1145
+ * This code is distributed in the hope that it will be useful, but WITHOUT
1146
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1147
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1148
+ * version 2 for more details (a copy is included in the LICENSE file that
1149
+ * accompanied this code).
1150
+ *
1151
+ * You should have received a copy of the GNU General Public License version
1152
+ * 2 along with this work; if not, write to the Free Software Foundation,
1153
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1154
+ *
1155
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1156
+ * or visit www.oracle.com if you need additional information or have any
1157
+ * questions.
1158
+ */
1159
+
1160
+ function doRun(args) {
1161
+ getExport("main")(toJavaStringArray(args));
1162
+ }
1163
+
1164
+
1165
+ /*
1166
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
1167
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1168
+ *
1169
+ * This code is free software; you can redistribute it and/or modify it
1170
+ * under the terms of the GNU General Public License version 2 only, as
1171
+ * published by the Free Software Foundation. Oracle designates this
1172
+ * particular file as subject to the "Classpath" exception as provided
1173
+ * by Oracle in the LICENSE file that accompanied this code.
1174
+ *
1175
+ * This code is distributed in the hope that it will be useful, but WITHOUT
1176
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1177
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1178
+ * version 2 for more details (a copy is included in the LICENSE file that
1179
+ * accompanied this code).
1180
+ *
1181
+ * You should have received a copy of the GNU General Public License version
1182
+ * 2 along with this work; if not, write to the Free Software Foundation,
1183
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1184
+ *
1185
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1186
+ * or visit www.oracle.com if you need additional information or have any
1187
+ * questions.
1188
+ */
1189
+ const STACK_TRACE_MARKER = "NATIVE-IMAGE-MARKER";
1190
+
1191
+ /**
1192
+ * Create JavaScript Error object, which is used to fill in the Throwable.backtrace object.
1193
+ */
1194
+ function genBacktrace() {
1195
+ return new Error(STACK_TRACE_MARKER);
1196
+ }
1197
+
1198
+ /**
1199
+ * Extract a Java string from the given backtrace object, which is supposed to be a JavaScript Error object.
1200
+ */
1201
+ function formatStackTrace(backtrace) {
1202
+ let trace;
1203
+
1204
+ if (backtrace.stack) {
1205
+ let lines = backtrace.stack.split("\n");
1206
+
1207
+ /*
1208
+ * Since Error.prototype.stack is non-standard, different runtimes set
1209
+ * it differently.
1210
+ * We try to remove the preamble that contains the error name and
1211
+ * message to just get the stack trace.
1212
+ */
1213
+ if (lines.length > 0 && lines[0].includes(STACK_TRACE_MARKER)) {
1214
+ lines = lines.splice(1);
1215
+ }
1216
+
1217
+ trace = lines.join("\n");
1218
+ } else {
1219
+ trace = "This JavaScript runtime does not expose stack trace information.";
1220
+ }
1221
+
1222
+ return toJavaString(trace);
1223
+ }
1224
+
1225
+ function gen_call_stack() {
1226
+ return formatStackTrace(genBacktrace());
1227
+ }
1228
+
1229
+
1230
+ /*
1231
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
1232
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1233
+ *
1234
+ * This code is free software; you can redistribute it and/or modify it
1235
+ * under the terms of the GNU General Public License version 2 only, as
1236
+ * published by the Free Software Foundation. Oracle designates this
1237
+ * particular file as subject to the "Classpath" exception as provided
1238
+ * by Oracle in the LICENSE file that accompanied this code.
1239
+ *
1240
+ * This code is distributed in the hope that it will be useful, but WITHOUT
1241
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1242
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1243
+ * version 2 for more details (a copy is included in the LICENSE file that
1244
+ * accompanied this code).
1245
+ *
1246
+ * You should have received a copy of the GNU General Public License version
1247
+ * 2 along with this work; if not, write to the Free Software Foundation,
1248
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1249
+ *
1250
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1251
+ * or visit www.oracle.com if you need additional information or have any
1252
+ * questions.
1253
+ */
1254
+
1255
+ /**
1256
+ * Provides the current working directory from the Config instance to Java code.
1257
+ */
1258
+ function getCurrentWorkingDirectory() {
1259
+ return toJavaString(runtime.data.config.currentWorkingDirectory);
1260
+ }
1261
+ runtime.setEndianness(1);
1262
+ wasmImports.interop = {
1263
+ 'Date.now' : (...args) => Date.now(...args),
1264
+ 'formatStackTrace' : (...args) => formatStackTrace(...args),
1265
+ 'genBacktrace' : (...args) => genBacktrace(...args),
1266
+ 'getCurrentWorkingDirectory' : (...args) => getCurrentWorkingDirectory(...args),
1267
+ 'llog' : (...args) => llog(...args),
1268
+ 'performance.now' : (...args) => performance.now(...args),
1269
+ 'runtime.setExitCode' : (...args) => runtime.setExitCode(...args),
1270
+ 'stderrWriter.close' : (...args) => stderrWriter.close(...args),
1271
+ 'stderrWriter.flush' : (...args) => stderrWriter.flush(...args),
1272
+ 'stderrWriter.printChars' : (...args) => stderrWriter.printChars(...args),
1273
+ 'stdoutWriter.close' : (...args) => stdoutWriter.close(...args),
1274
+ 'stdoutWriter.flush' : (...args) => stdoutWriter.flush(...args),
1275
+ 'stdoutWriter.printChars' : (...args) => stdoutWriter.printChars(...args),
1276
+ }
1277
+ ;
1278
+ wasmImports.jsbody = {
1279
+ '_FileSystemInitializer.clearPrefetchedLibraryContent___String_V' : (...args) => (function(name){
1280
+ try{
1281
+ runtime.data.libraries[name] = null;
1282
+ }catch( e ) {
1283
+ conversion.handleJSError(e);}}).call(...args),
1284
+ '_FileSystemInitializer.prefetchedLibraryContent___String_String' : (...args) => (function(name){
1285
+ try{
1286
+ return runtime.data.libraries[name];
1287
+ }catch( e ) {
1288
+ conversion.handleJSError(e);}}).call(...args),
1289
+ '_FileSystemInitializer.prefetchedLibraryNames___JSObject' : (...args) => (function(){
1290
+ try{
1291
+ return runtime.prefetchedLibraryNames();
1292
+ }catch( e ) {
1293
+ conversion.handleJSError(e);}}).call(...args),
1294
+ '_JSBoolean.javaBoolean___Boolean' : (...args) => (function(){
1295
+ try{
1296
+ return conversion.toProxy(conversion.createJavaBoolean(this));
1297
+ }catch( e ) {
1298
+ conversion.handleJSError(e);}}).call(...args),
1299
+ '_JSConversion.asJavaObjectOrString___Object_Object' : (...args) => (function(obj){
1300
+ try{
1301
+ return conversion.isInternalJavaObject(obj) ? obj : toJavaString(obj.toString());
1302
+ }catch( e ) {
1303
+ conversion.handleJSError(e);}}).call(...args),
1304
+ '_JSConversion.extractJavaScriptProxy___Object_Object' : (...args) => (function(self){
1305
+ try{
1306
+ return conversion.toProxy(self);
1307
+ }catch( e ) {
1308
+ conversion.handleJSError(e);}}).call(...args),
1309
+ '_JSConversion.extractJavaScriptString___String_Object' : (...args) => (function(s){
1310
+ try{
1311
+ return conversion.extractJavaScriptString(s);
1312
+ }catch( e ) {
1313
+ conversion.handleJSError(e);}}).call(...args),
1314
+ '_JSConversion.javaScriptToJava___Object_Object' : (...args) => (function(x){
1315
+ try{
1316
+ return conversion.javaScriptToJava(x);
1317
+ }catch( e ) {
1318
+ conversion.handleJSError(e);}}).call(...args),
1319
+ '_JSConversion.javaScriptUndefined___Object' : (...args) => (function(){
1320
+ try{
1321
+ return undefined;
1322
+ }catch( e ) {
1323
+ conversion.handleJSError(e);}}).call(...args),
1324
+ '_JSConversion.unproxy___Object_Object' : (...args) => (function(proxy){
1325
+ try{
1326
+ return conversion.unproxy(proxy);
1327
+ }catch( e ) {
1328
+ conversion.handleJSError(e);}}).call(...args),
1329
+ '_JSFunctionIntrinsics.isUndefined___Object_Z' : (...args) => (function(o){
1330
+ try{
1331
+ return o === undefined;
1332
+ }catch( e ) {
1333
+ conversion.handleJSError(e);}}).call(...args),
1334
+ '_JSNumber.javaDouble___Double' : (...args) => (function(){
1335
+ try{
1336
+ return conversion.toProxy(conversion.createJavaDouble(this));
1337
+ }catch( e ) {
1338
+ conversion.handleJSError(e);}}).call(...args),
1339
+ '_JSObject.get___Object_Object' : (...args) => (function(key){
1340
+ try{
1341
+ return this[key];
1342
+ }catch( e ) {
1343
+ conversion.handleJSError(e);}}).call(...args),
1344
+ '_JSObject.typeofString___JSString' : (...args) => (function(){
1345
+ try{
1346
+ return typeof this;
1347
+ }catch( e ) {
1348
+ conversion.handleJSError(e);}}).call(...args),
1349
+ '_JSString.asString___String' : (...args) => (function(){
1350
+ try{
1351
+ return conversion.toProxy(toJavaString(this));
1352
+ }catch( e ) {
1353
+ conversion.handleJSError(e);}}).call(...args),
1354
+ '_JSString.of___String_JSString' : (...args) => (function(s){
1355
+ try{
1356
+ return conversion.extractJavaScriptString(conversion.unproxy(s));
1357
+ }catch( e ) {
1358
+ conversion.handleJSError(e);}}).call(...args),
1359
+ '_JSSymbol.referenceEquals___JSSymbol_JSSymbol_JSBoolean' : (...args) => (function(sym0,sym1){
1360
+ try{
1361
+ return sym0 === sym1;
1362
+ }catch( e ) {
1363
+ conversion.handleJSError(e);}}).call(...args),
1364
+ '_JSValue.stringValue___String' : (...args) => (function(){
1365
+ try{
1366
+ return this?.toString()?? 'undefined';
1367
+ }catch( e ) {
1368
+ conversion.handleJSError(e);}}).call(...args),
1369
+ '_JsApi.install___Function_JSString_JSString_JSString_JSString_JSString_JSString_JSString_V' : (...args) => (function(fn,schema,name,variant,version,groups,julcVersion,source){
1370
+ try{
1371
+ const own = String(julcVersion);
1372
+ // The worker hears the cause before main fails; detail names the runtime's build when it is the cause.
1373
+ const startupError = (message, detail) => {
1374
+ globalThis.onJulcStartupError?.(message, detail);
1375
+ return new Error(message);
1376
+ };
1377
+ const found = globalThis.JulcRuntime;
1378
+ const stamp = found !== null && typeof found === 'object' && typeof found.install === 'function'
1379
+ ? found.julcVersion : undefined;
1380
+ const preload = globalThis.JULC_RUNTIME_PRELOAD;
1381
+ let runtime = found, origin = 'preloaded';
1382
+ if (preload !== undefined) {
1383
+ if (preload !== 'loaded' || stamp !== own) {
1384
+ throw startupError('JuLC engine ' + own + ' cannot start: the runtime file julc-runtime.js loaded '
1385
+ + 'before it is ' + (preload !== 'loaded' ? 'missing'
1386
+ : typeof stamp === 'string' ? 'JuLC ' + stamp : 'not a stamped JuLC runtime')
1387
+ + '; serve the julc-runtime.js of JuLC ' + own + ' with this engine',
1388
+ {engineJulcVersion: own, runtimeJulcVersion: typeof stamp === 'string' ? stamp : null});
1389
+ }
1390
+ } else if (stamp !== own) {
1391
+ try {
1392
+ (0, eval)(String(source));
1393
+ } catch (error) {
1394
+ throw startupError('JuLC engine ' + own + ' cannot start: the runtime file julc-runtime.js was not '
1395
+ + "loaded, and evaluating the engine's own copy failed (for example under a Content Security "
1396
+ + "Policy without 'unsafe-eval'): " + error);
1397
+ }
1398
+ runtime = globalThis.JulcRuntime;
1399
+ if (found !== undefined) globalThis.JulcRuntime = found;
1400
+ origin = 'evaluated';
1401
+ } else {
1402
+ origin = 'shared';
1403
+ }
1404
+ if (String(name) in globalThis) throw startupError('Global ' + String(name) + ' is already defined');
1405
+ const api = runtime.install(
1406
+ (method, body) => String(fn([method, body])), JSON.parse(String(schema)),
1407
+ String(variant), String(version), JSON.parse(String(groups)), own);
1408
+ Object.defineProperty(api, Symbol.for('julc.runtime'), {value: origin});
1409
+ globalThis[String(name)] = api;
1410
+ if (typeof globalThis.onJulcReady === 'function') {
1411
+ setTimeout(() => globalThis.onJulcReady(api), 0);
1412
+ }
1413
+ }catch( e ) {
1414
+ conversion.handleJSError(e);}}).call(...args),
1415
+ '_WebImageNativeLibrarySupport.loadPrefetchedJSLibrary___JSString_JSObject' : (...args) => (function(content){
1416
+ try{
1417
+ return loadPrefetchedJSLibrary(content);
1418
+ }catch( e ) {
1419
+ conversion.handleJSError(e);}}).call(...args),
1420
+ '_WebImageUtil.random___D' : (...args) => (function(){
1421
+ try{
1422
+ return Math.random();
1423
+ }catch( e ) {
1424
+ conversion.handleJSError(e);}}).call(...args),
1425
+ }
1426
+ ;
1427
+
1428
+
1429
+ /*
1430
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
1431
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1432
+ *
1433
+ * This code is free software; you can redistribute it and/or modify it
1434
+ * under the terms of the GNU General Public License version 2 only, as
1435
+ * published by the Free Software Foundation. Oracle designates this
1436
+ * particular file as subject to the "Classpath" exception as provided
1437
+ * by Oracle in the LICENSE file that accompanied this code.
1438
+ *
1439
+ * This code is distributed in the hope that it will be useful, but WITHOUT
1440
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1441
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1442
+ * version 2 for more details (a copy is included in the LICENSE file that
1443
+ * accompanied this code).
1444
+ *
1445
+ * You should have received a copy of the GNU General Public License version
1446
+ * 2 along with this work; if not, write to the Free Software Foundation,
1447
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1448
+ *
1449
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1450
+ * or visit www.oracle.com if you need additional information or have any
1451
+ * questions.
1452
+ */
1453
+
1454
+ /**
1455
+ * Code dealing with moving values between the Java and JavaScript world.
1456
+ *
1457
+ * This code handles Java values:
1458
+ * - All Java values except for objects and longs are represented as JS Number values.
1459
+ * - Object and long representation depends on the backend used.
1460
+ * Variables and arguments representing Java values are usually marked explicitly
1461
+ * (e.g. by being named something like javaObject or jlstring, which stands for
1462
+ * java.lang.String).
1463
+ *
1464
+ * Java values can be used to call Java methods directly without additional
1465
+ * conversions, which is the basis of the functionality this class provides.
1466
+ * It facilitates calling Java methods from JavaScript by first performing the
1467
+ * necessary conversions or coercions before the Java call is executed. In the
1468
+ * reverse direction, it helps Java code execute JS code (e.g. through the @JS
1469
+ * annotation) by converting or coercing Java values into appropriate JS values.
1470
+ */
1471
+ class Conversion {
1472
+ constructor() {
1473
+ /*
1474
+ * Stores the unique proxy instance for each proxied Java object.
1475
+ *
1476
+ * Maps Java objects to their proxies to ensure every Java object has
1477
+ * at most one proxy associated with it.
1478
+ *
1479
+ * The keys (Java objects) of this map are weak references and don't
1480
+ * prevent the Java object from being garbage collected. The values
1481
+ * (proxies) aren't. The proxies themselves hold a strong reference to
1482
+ * the Java object, creating a dependency cycle. However, this does not
1483
+ * cause a memory leak because the standard prevents it.
1484
+ * From the 6th edition of ECMA-262 section 23.3:
1485
+ *
1486
+ * If an object that is being used as the key of a WeakMap key/value
1487
+ * pair is only reachable by following a chain of references that
1488
+ * start within that WeakMap, then that key/value pair is
1489
+ * inaccessible and is automatically removed from the WeakMap
1490
+ *
1491
+ * See https://262.ecma-international.org/6.0/#sec-weakmap-objects
1492
+ */
1493
+ this.proxies = new WeakMap();
1494
+ }
1495
+
1496
+ /**
1497
+ * Extracts the underlying Java object from the given proxy.
1498
+ *
1499
+ * Only call this method if the object is a proxy created by `toProxy`.
1500
+ */
1501
+ unproxy(jsJavaProxy) {
1502
+ const optionalUnproxied = this.tryUnproxy(jsJavaProxy);
1503
+ if (optionalUnproxied === undefined) {
1504
+ throw new TypeError(`Tried to unproxy a non-Java-object proxy: ${String(jsJavaProxy)}`);
1505
+ }
1506
+
1507
+ return optionalUnproxied;
1508
+ }
1509
+
1510
+ /**
1511
+ * Tests whether the given JS object is a proxy over a Java object as
1512
+ * created by `toProxy` and returns the underlying Java object.
1513
+ * Returns `undefined` if the object is not one of our proxies.
1514
+ *
1515
+ * Can detect if our proxy is wrapped in a 3rd party proxy and in those
1516
+ * cases also returns `undefined`.
1517
+ */
1518
+ tryUnproxy(jsProxyCandidate) {
1519
+ let looksLikeProxy = Object.getOwnPropertyDescriptor(jsProxyCandidate, runtime.symbol.isProxy)?.value === true;
1520
+ if (looksLikeProxy) {
1521
+ // Our proxy could be wrapped in one or more 3rd party proxies, which just forward the lookup of the isProxy
1522
+ // property. We additionally have to look up the actual unique proxy object for the underlying Java object
1523
+ // to check if the given object is one of our proxies.
1524
+ let javaObject = jsProxyCandidate[runtime.symbol.javaNative];
1525
+ if (!javaObject) {
1526
+ // Unlikely, but this could be a non-proxy object with the isProxy property.
1527
+ return undefined;
1528
+ }
1529
+ if (this.toProxy(javaObject) === jsProxyCandidate) {
1530
+ return javaObject;
1531
+ }
1532
+ }
1533
+
1534
+ return undefined;
1535
+ }
1536
+
1537
+ /**
1538
+ * Associates the given Java object with the given JS value.
1539
+ */
1540
+ setJavaScriptNative(javaObject, jsNative) {
1541
+ throw new Error("Unimplemented: Conversion.javaScriptNative");
1542
+ }
1543
+
1544
+ /**
1545
+ * Returns the JS value associated with the given Java object or null if there is no associated value.
1546
+ */
1547
+ extractJavaScriptNative(javaObject) {
1548
+ throw new Error("Unimplemented: Conversion.extractJavaScriptNative");
1549
+ }
1550
+
1551
+ // Java-to-JavaScript conversions
1552
+
1553
+ /**
1554
+ * Given a Java boxed Double, creates the corresponding JavaScript number value.
1555
+ *
1556
+ * @param jldouble The java.lang.Double object
1557
+ * @return {*} A JavaScript Number value
1558
+ */
1559
+ extractJavaScriptNumber(jldouble) {
1560
+ throw new Error("Unimplemented: Conversion.extractJavaScriptNumber");
1561
+ }
1562
+
1563
+ /**
1564
+ * Given a Java String, creates the corresponding JavaScript string value.
1565
+ *
1566
+ * Note: the Java method called in this implementation will return (in the generated code)
1567
+ * an actual primitive Java string.
1568
+ *
1569
+ * @param jlstring The java.lang.String object
1570
+ * @return {*} A JavaScript String value
1571
+ */
1572
+ extractJavaScriptString(jlstring) {
1573
+ throw new Error("Unimplemented: Conversion.extractJavaScriptString");
1574
+ }
1575
+
1576
+ // JavaScript-to-Java conversions (standard Java classes)
1577
+
1578
+ /**
1579
+ * Creates a java.lang.Boolean object from a JavaScript boolean value.
1580
+ */
1581
+ createJavaBoolean(b) {
1582
+ throw new Error("Unimplemented: Conversion.createJavaBoolean");
1583
+ }
1584
+
1585
+ /**
1586
+ * Creates a java.lang.Byte object from a JavaScript number value.
1587
+ */
1588
+ createJavaByte(x) {
1589
+ throw new Error("Unimplemented: Conversion.createJavaByte");
1590
+ }
1591
+
1592
+ /**
1593
+ * Creates a java.lang.Short object from a JavaScript number value.
1594
+ */
1595
+ createJavaShort(x) {
1596
+ throw new Error("Unimplemented: Conversion.createJavaShort");
1597
+ }
1598
+
1599
+ /**
1600
+ * Creates a java.lang.Character object from a JavaScript number value.
1601
+ */
1602
+ createJavaCharacter(x) {
1603
+ throw new Error("Unimplemented: Conversion.createJavaCharacter");
1604
+ }
1605
+
1606
+ /**
1607
+ * Creates a java.lang.Integer object from a JavaScript number value.
1608
+ */
1609
+ createJavaInteger(x) {
1610
+ throw new Error("Unimplemented: Conversion.createJavaInteger");
1611
+ }
1612
+
1613
+ /**
1614
+ * Creates a java.lang.Float object from a JavaScript number value.
1615
+ */
1616
+ createJavaFloat(x) {
1617
+ throw new Error("Unimplemented: Conversion.createJavaFloat");
1618
+ }
1619
+
1620
+ /**
1621
+ * Creates a java.lang.Long object from a JavaScript number value.
1622
+ */
1623
+ createJavaLong(x) {
1624
+ throw new Error("Unimplemented: Conversion.createJavaLong");
1625
+ }
1626
+
1627
+ /**
1628
+ * Creates a java.lang.Double object from a JavaScript number value.
1629
+ */
1630
+ createJavaDouble(x) {
1631
+ throw new Error("Unimplemented: Conversion.createJavaDouble");
1632
+ }
1633
+
1634
+ /**
1635
+ * Gets the JavaKind ordinal for the given hub, as expected by `boxIfNeeded`.
1636
+ */
1637
+ getHubKindOrdinal(hub) {
1638
+ throw new Error("Unimplemented: Conversion.getHubKindOrdinal");
1639
+ }
1640
+
1641
+ /**
1642
+ * Box the given value if the specified type is primitive.
1643
+ *
1644
+ * The parameter type is the enum index as defined in jdk.vm.ci.meta.JavaKind.
1645
+ * The following is a summary:
1646
+ *
1647
+ * 0 - Boolean
1648
+ * 1 - Byte
1649
+ * 2 - Short
1650
+ * 3 - Char
1651
+ * 4 - Int
1652
+ * 5 - Float
1653
+ * 6 - Long
1654
+ * 7 - Double
1655
+ * 8 - Object
1656
+ *
1657
+ * @param {number=} type
1658
+ */
1659
+ boxIfNeeded(javaValue, type) {
1660
+ switch (type) {
1661
+ case 0:
1662
+ return this.createJavaBoolean(javaValue);
1663
+ case 1:
1664
+ return this.createJavaByte(javaValue);
1665
+ case 2:
1666
+ return this.createJavaShort(javaValue);
1667
+ case 3:
1668
+ return this.createJavaCharacter(javaValue);
1669
+ case 4:
1670
+ return this.createJavaInteger(javaValue);
1671
+ case 5:
1672
+ return this.createJavaFloat(javaValue);
1673
+ case 6:
1674
+ return this.createJavaLong(javaValue);
1675
+ case 7:
1676
+ return this.createJavaDouble(javaValue);
1677
+ default:
1678
+ return javaValue;
1679
+ }
1680
+ }
1681
+
1682
+ /**
1683
+ * Unbox the given value if the specified type is primitive.
1684
+ *
1685
+ * See documentation for `boxIfNeeded`.
1686
+ */
1687
+ unboxIfNeeded(javaObject, type) {
1688
+ switch (type) {
1689
+ case 0:
1690
+ return this.unboxBoolean(javaObject);
1691
+ case 1:
1692
+ return this.unboxByte(javaObject);
1693
+ case 2:
1694
+ return this.unboxShort(javaObject);
1695
+ case 3:
1696
+ return this.unboxChar(javaObject);
1697
+ case 4:
1698
+ return this.unboxInt(javaObject);
1699
+ case 5:
1700
+ return this.unboxFloat(javaObject);
1701
+ case 6:
1702
+ return this.unboxLong(javaObject);
1703
+ case 7:
1704
+ return this.unboxDouble(javaObject);
1705
+ default:
1706
+ return javaObject;
1707
+ }
1708
+ }
1709
+
1710
+ unboxBoolean(jlBoolean) {
1711
+ throw new Error("Unimplemented: Conversion.unboxBoolean");
1712
+ }
1713
+
1714
+ unboxByte(jlByte) {
1715
+ throw new Error("Unimplemented: Conversion.unboxByte");
1716
+ }
1717
+
1718
+ unboxShort(jlShort) {
1719
+ throw new Error("Unimplemented: Conversion.unboxShort");
1720
+ }
1721
+
1722
+ unboxChar(jlChar) {
1723
+ throw new Error("Unimplemented: Conversion.unboxChar");
1724
+ }
1725
+
1726
+ unboxInt(jlInt) {
1727
+ throw new Error("Unimplemented: Conversion.unboxInt");
1728
+ }
1729
+
1730
+ unboxFloat(jlFloat) {
1731
+ throw new Error("Unimplemented: Conversion.unboxFloat");
1732
+ }
1733
+
1734
+ unboxLong(jlLong) {
1735
+ throw new Error("Unimplemented: Conversion.unboxLong");
1736
+ }
1737
+
1738
+ unboxDouble(jlDouble) {
1739
+ throw new Error("Unimplemented: Conversion.unboxDouble");
1740
+ }
1741
+
1742
+ /**
1743
+ * Gets the boxed counterpart of the given primitive hub.
1744
+ */
1745
+ getBoxedHub(jlClass) {
1746
+ throw new Error("Unimplemented: Conversion.getBoxedHub");
1747
+ }
1748
+
1749
+ // JavaScript-to-Java conversions (JSValue classes)
1750
+
1751
+ /**
1752
+ * Gets the Java singleton object that represents the JavaScript undefined value.
1753
+ */
1754
+ createJSUndefined() {
1755
+ throw new Error("Unimplemented: Conversion.createJSUndefined");
1756
+ }
1757
+
1758
+ /**
1759
+ * Wraps a JavaScript Boolean into a Java JSBoolean object.
1760
+ *
1761
+ * @param boolean The JavaScript boolean to wrap
1762
+ * @return {*} The Java JSBoolean object
1763
+ */
1764
+ createJSBoolean(boolean) {
1765
+ throw new Error("Unimplemented: Conversion.createJSBoolean");
1766
+ }
1767
+
1768
+ /**
1769
+ * Wraps a JavaScript Number into a Java JSNumber object.
1770
+ *
1771
+ * @param number The JavaScript number to wrap
1772
+ * @return {*} The Java JSNumber object
1773
+ */
1774
+ createJSNumber(number) {
1775
+ throw new Error("Unimplemented: Conversion.createJSNumber");
1776
+ }
1777
+
1778
+ /**
1779
+ * Wraps a JavaScript BigInt into a Java JSBigInt object.
1780
+ *
1781
+ * @param bigint The JavaScript BigInt value to wrap
1782
+ * @return {*} The Java JSBigInt object
1783
+ */
1784
+ createJSBigInt(bigint) {
1785
+ throw new Error("Unimplemented: Conversion.createJSBigInt");
1786
+ }
1787
+
1788
+ /**
1789
+ * Wraps a JavaScript String into a Java JSString object.
1790
+ *
1791
+ * @param string The JavaScript String value to wrap
1792
+ * @return {*} The Java JSString object
1793
+ */
1794
+ createJSString(string) {
1795
+ throw new Error("Unimplemented: Conversion.createJSString");
1796
+ }
1797
+
1798
+ /**
1799
+ * Wraps a JavaScript Symbol into a Java JSSymbol object.
1800
+ *
1801
+ * @param symbol The JavaScript Symbol value to wrap
1802
+ * @return {*} The Java JSSymbol object
1803
+ */
1804
+ createJSSymbol(symbol) {
1805
+ throw new Error("Unimplemented: Conversion.createJSSymbol");
1806
+ }
1807
+
1808
+ /**
1809
+ * Wraps a JavaScript object into a Java JSObject object.
1810
+ *
1811
+ * @param obj The JavaScript Object value to wrap
1812
+ * @returns {*} The Java JSObject object
1813
+ */
1814
+ createJSObject(obj) {
1815
+ throw new Error("Unimplemented: Conversion.createJSObject");
1816
+ }
1817
+
1818
+ // Helper methods
1819
+
1820
+ /**
1821
+ * Checks if the specified object (which may be a JavaScript value or a Java value) is an internal Java object.
1822
+ */
1823
+ isInternalJavaObject(obj) {
1824
+ throw new Error("Unimplemented: Conversion.isInternalJavaObject");
1825
+ }
1826
+
1827
+ isPrimitiveHub(hub) {
1828
+ throw new Error("Unimplemented: Conversion.isPrimitiveHub");
1829
+ }
1830
+
1831
+ isJavaLangString(obj) {
1832
+ throw new Error("Unimplemented: Conversion.isJavaLangString");
1833
+ }
1834
+
1835
+ isJavaLangClass(obj) {
1836
+ throw new Error("Unimplemented: Conversion.isJavaLangClass");
1837
+ }
1838
+
1839
+ /**
1840
+ * Checks if the given object is an instance of the given class. null values also return true.
1841
+ */
1842
+ isInstance(obj, hub) {
1843
+ throw new Error("Unimplemented: Conversion.isInstance");
1844
+ }
1845
+
1846
+ /**
1847
+ * @return {*} The result of obj.getClass()
1848
+ */
1849
+ getHub(obj) {
1850
+ throw new Error("Unimplemented: Conversion.getHub");
1851
+ }
1852
+
1853
+ /**
1854
+ * Returns the supertype of the type represented by the given hub or null
1855
+ * if and only if the hub represents java.lang.Object.
1856
+ *
1857
+ * This function must only be called with instance or array classes (no
1858
+ * primitive or interface classes).
1859
+ */
1860
+ getSupertype(hub) {
1861
+ throw new Error("Unimplemented: Conversion.getSupertype");
1862
+ }
1863
+
1864
+ /**
1865
+ * @return {*|null} The component type of the given hub, or null if the hub does not represent an array type.
1866
+ */
1867
+ getComponentHub(hub) {
1868
+ throw new Error("Unimplemented: Conversion.getComponentHub");
1869
+ }
1870
+
1871
+ /**
1872
+ * Returns hub.getTypeName().
1873
+ */
1874
+ getTypeNameAsJavaString(hub) {
1875
+ throw new Error("Unimplemented: Conversion.getTypeNameAsJavaString");
1876
+ }
1877
+
1878
+ /**
1879
+ * Returns hub.getTypeName() as a JS string.
1880
+ */
1881
+ getTypeName(hub) {
1882
+ return conversion.extractJavaScriptString(this.getTypeNameAsJavaString(hub));
1883
+ }
1884
+
1885
+ /**
1886
+ * Copies own fields from source to destination.
1887
+ *
1888
+ * Existing fields in the destination are overwritten.
1889
+ */
1890
+ copyOwnFields(src, dst) {
1891
+ for (let name of Object.getOwnPropertyNames(src)) {
1892
+ dst[name] = src[name];
1893
+ }
1894
+ }
1895
+
1896
+ /**
1897
+ * Obtains or creates the proxy handler for the given Java class
1898
+ */
1899
+ getOrCreateProxyHandler(hub) {
1900
+ throw new Error("Unimplemented: Conversion.getOrCreateProxyHandler");
1901
+ }
1902
+
1903
+ /**
1904
+ * Creates a proxy that intercepts messages that correspond to Java method calls and Java field accesses.
1905
+ *
1906
+ * @param obj The Java object to create a proxy for
1907
+ * @return {*} The proxy around the Java object
1908
+ */
1909
+ toProxy(obj) {
1910
+ let proxy = this.proxies.get(obj);
1911
+
1912
+ if (proxy === undefined) {
1913
+ let proxyHandler = this.getOrCreateProxyHandler(this.getHub(obj));
1914
+ // The wrapper is a temporary object that allows having the non-identifier name of the target function.
1915
+ // We declare the property as a function, to ensure that it is constructable, so that the Proxy handler's construct method is callable.
1916
+ let targetWrapper = {
1917
+ ["Java Proxy"]: function (key) {
1918
+ if (key === runtime.symbol.javaNative) {
1919
+ return obj;
1920
+ }
1921
+ return undefined;
1922
+ },
1923
+ };
1924
+
1925
+ const proxyFun = targetWrapper["Java Proxy"];
1926
+
1927
+ Object.defineProperty(proxyFun, runtime.symbol.isProxy, {
1928
+ value: true,
1929
+ writable: false,
1930
+ enumerable: false,
1931
+ configurable: false,
1932
+ });
1933
+
1934
+ proxy = new Proxy(proxyFun, proxyHandler);
1935
+ this.proxies.set(obj, proxy);
1936
+ }
1937
+
1938
+ return proxy;
1939
+ }
1940
+
1941
+ /**
1942
+ * Converts a JavaScript value to the corresponding Java representation.
1943
+ *
1944
+ * The exact rules of the mapping are documented in the Java JS annotation class.
1945
+ *
1946
+ * This method is only meant to be called from the conversion code generated for JS-annotated methods.
1947
+ *
1948
+ * @param x The JavaScript value to convert
1949
+ * @return {*} The Java representation of the JavaScript value
1950
+ */
1951
+ javaScriptToJava(x) {
1952
+ // Step 1: check null, which is mapped 1:1 to null in Java.
1953
+ if (x === null) {
1954
+ return null;
1955
+ }
1956
+
1957
+ // Step 2: check undefined, which is a singleton in Java.
1958
+ if (x === undefined) {
1959
+ return this.createJSUndefined();
1960
+ }
1961
+
1962
+ // Step 3: Unproxy Java proxies to get the underlying Java object
1963
+ const optionalUnproxied = this.tryUnproxy(x);
1964
+ if (optionalUnproxied !== undefined) {
1965
+ return optionalUnproxied;
1966
+ }
1967
+
1968
+ // Step 4: use the JavaScript type to select the appropriate Java representation.
1969
+ const tpe = typeof x;
1970
+ switch (tpe) {
1971
+ case "boolean":
1972
+ return this.createJSBoolean(x);
1973
+ case "number":
1974
+ return this.createJSNumber(x);
1975
+ case "bigint":
1976
+ return this.createJSBigInt(x);
1977
+ case "string":
1978
+ return this.createJSString(x);
1979
+ case "symbol":
1980
+ return this.createJSSymbol(x);
1981
+ case "object":
1982
+ case "function":
1983
+ // We know this is not a proxy of a Java object because the
1984
+ // conversion would have returned in Step 3.
1985
+ return this.createJSObject(x);
1986
+ default:
1987
+ throw new Error("unexpected type: " + tpe);
1988
+ }
1989
+ }
1990
+
1991
+ /**
1992
+ * Maps each JavaScript value in the input array to a Java value.
1993
+ * See {@code javaScriptToJava}.
1994
+ */
1995
+ eachJavaScriptToJava(javaScriptValues) {
1996
+ const javaValues = new Array(javaScriptValues.length);
1997
+ for (let i = 0; i < javaScriptValues.length; i++) {
1998
+ javaValues[i] = this.javaScriptToJava(javaScriptValues[i]);
1999
+ }
2000
+ return javaValues;
2001
+ }
2002
+
2003
+ /**
2004
+ * Converts a Java value to JavaScript.
2005
+ */
2006
+ javaToJavaScript(x) {
2007
+ throw new Error("Unimplemented: Conversion.javaToJavaScript");
2008
+ }
2009
+
2010
+ throwClassCastExceptionImpl(javaObject, tpeNameJavaString) {
2011
+ throw new Error("Unimplemented: Conversion.throwClassCastExceptionImpl");
2012
+ }
2013
+
2014
+ throwClassCastException(javaObject, tpe) {
2015
+ let tpeName;
2016
+ if (typeof tpe === "string") {
2017
+ tpeName = tpe;
2018
+ } else if (typeof tpe === "function") {
2019
+ tpeName = tpe.name;
2020
+ } else {
2021
+ tpeName = tpe.toString();
2022
+ }
2023
+ this.throwClassCastExceptionImpl(javaObject, toJavaString(tpeName));
2024
+ }
2025
+
2026
+ /**
2027
+ * Converts the specified Java Proxy to the target JavaScript type, if possible.
2028
+ *
2029
+ * This method is meant to be called from Java Proxy object, either when implicit coercion is enabled,
2030
+ * or when the user explicitly invokes coercion on the Proxy object.
2031
+ *
2032
+ * @param proxyHandler handler for the proxy that must be converted
2033
+ * @param proxy the Java Proxy object that should be coerced
2034
+ * @param tpe target JavaScript type name (result of the typeof operator) or constructor function
2035
+ * @return {*} the resulting JavaScript value
2036
+ */
2037
+ coerceJavaProxyToJavaScriptType(proxyHandler, proxy, tpe) {
2038
+ throw new Error("Unimplemented: Conversion.coerceJavaProxyToJavaScriptType");
2039
+ }
2040
+
2041
+ /**
2042
+ * Wraps the JavaScript object in a Java facade class.
2043
+ *
2044
+ * @param obj JavaScript object which is wrapped in the Java facade
2045
+ * @param jsObjectClazz target Java class for a proper subtype of JSObject in the form of its JavaScript counterpart
2046
+ * @return {*} the mirror instance wrapped into a JavaScript Java Proxy
2047
+ */
2048
+ coerceToFacadeClass(obj, jsObjectClazz) {
2049
+ const rawJavaHub = this.unproxy(jsObjectClazz);
2050
+ const internalJavaClass = rawJavaHub[runtime.symbol.jsClass];
2051
+ const rawJavaMirror = new internalJavaClass();
2052
+ // Note: only one-way handshake, since the JavaScript object could be recast to a different Java facade class.
2053
+ this.setJavaScriptNative(rawJavaMirror, obj);
2054
+ return this.toProxy(rawJavaMirror);
2055
+ }
2056
+
2057
+ loadArrayElement(javaArray, componentKindOrdinal, idx) {
2058
+ switch (componentKindOrdinal) {
2059
+ case 0:
2060
+ return this.loadBooleanArrayElement(javaArray, idx);
2061
+ case 1:
2062
+ return this.loadByteArrayElement(javaArray, idx);
2063
+ case 2:
2064
+ return this.loadShortArrayElement(javaArray, idx);
2065
+ case 3:
2066
+ return this.loadCharArrayElement(javaArray, idx);
2067
+ case 4:
2068
+ return this.loadIntArrayElement(javaArray, idx);
2069
+ case 5:
2070
+ return this.loadFloatArrayElement(javaArray, idx);
2071
+ case 6:
2072
+ return this.loadLongArrayElement(javaArray, idx);
2073
+ case 7:
2074
+ return this.loadDoubleArrayElement(javaArray, idx);
2075
+ case 8:
2076
+ return this.javaToJavaScript(this.loadObjectArrayElement(javaArray, idx));
2077
+ }
2078
+ }
2079
+
2080
+ checkNumericType(arrayType, jsValue) {
2081
+ const tpe = typeof jsValue;
2082
+ if (tpe !== "number" && tpe !== "bigint") {
2083
+ throw new TypeError(`Invalid type ${tpe} for insertion into ${arrayType} array`);
2084
+ }
2085
+ }
2086
+
2087
+ checkIntegerValueRange(arrayType, jsValue, lowValue, highValue) {
2088
+ const tpe = typeof jsValue;
2089
+ this.checkNumericType(arrayType, jsValue);
2090
+
2091
+ if (tpe === "number" && !Number.isInteger(jsValue)) {
2092
+ throw new RangeError(`Non-integer number ${jsValue} for insertion into ${arrayType} array`);
2093
+ }
2094
+
2095
+ if (jsValue > highValue || jsValue < lowValue) {
2096
+ throw new RangeError(`Out of range value ${jsValue} for insertion into ${arrayType} array`);
2097
+ }
2098
+ }
2099
+
2100
+ storeArrayElement(javaArray, componentKindOrdinal, idx, jsValue) {
2101
+ if (idx < 0 || idx >= conversion.getArrayLength(javaArray)) {
2102
+ // Silently ignore out of bounds array stores. This matches the
2103
+ // behavior of TypedArray
2104
+ return;
2105
+ }
2106
+ const tpe = typeof jsValue;
2107
+ switch (componentKindOrdinal) {
2108
+ case 0:
2109
+ if (tpe !== "boolean") {
2110
+ throw new TypeError(`Invalid type ${tpe} for insertion into boolean array`);
2111
+ }
2112
+ this.storeBooleanArrayElement(javaArray, idx, jsValue);
2113
+ break;
2114
+ case 1:
2115
+ this.checkIntegerValueRange("byte", jsValue, -128, 127);
2116
+ this.storeByteArrayElement(javaArray, idx, Number(jsValue));
2117
+ break;
2118
+ case 2:
2119
+ this.checkIntegerValueRange("short", jsValue, -32768, 32767);
2120
+ this.storeShortArrayElement(javaArray, idx, Number(jsValue));
2121
+ break;
2122
+ case 3:
2123
+ this.checkIntegerValueRange("char", jsValue, 0, 65535);
2124
+ this.storeCharArrayElement(javaArray, idx, Number(jsValue));
2125
+ break;
2126
+ case 4:
2127
+ this.checkIntegerValueRange("int", jsValue, -2147483648, 2147483647);
2128
+ this.storeIntArrayElement(javaArray, idx, Number(jsValue));
2129
+ break;
2130
+ case 5:
2131
+ this.checkNumericType("float", jsValue);
2132
+ this.storeFloatArrayElement(javaArray, idx, Number(jsValue));
2133
+ break;
2134
+ case 6:
2135
+ this.checkIntegerValueRange("long", jsValue, -9223372036854775808n, 9223372036854775807n);
2136
+ this.storeLongArrayElement(javaArray, idx, BigInt(jsValue));
2137
+ break;
2138
+ case 7:
2139
+ this.checkNumericType("double", jsValue);
2140
+ this.storeDoubleArrayElement(javaArray, idx, Number(jsValue));
2141
+ break;
2142
+ case 8:
2143
+ this.storeObjectArrayElement(javaArray, idx, conversion.javaScriptToJava(jsValue));
2144
+ break;
2145
+ }
2146
+ }
2147
+
2148
+ /**
2149
+ * Coerce the specified JavaScript value to the specified Java type.
2150
+ *
2151
+ * See VM.as for the specification of this function.
2152
+ */
2153
+ coerceJavaScriptToJavaType(javaScriptValue, type) {
2154
+ throw new Error("Unimplemented: Conversion.coerceJavaScriptToJavaType");
2155
+ }
2156
+
2157
+ /**
2158
+ * Reads the length of a Java array and returns it as a JS number.
2159
+ */
2160
+ getArrayLength(_javaArray) {
2161
+ throw new Error("Unimplemented: Conversion.getArrayLength");
2162
+ }
2163
+
2164
+ /**
2165
+ * @param {number} _idx In bounds index
2166
+ * @return {boolean} Boolean value at index idx as a JS boolean
2167
+ */
2168
+ loadBooleanArrayElement(_javaArray, _idx) {
2169
+ throw new Error("Unimplemented: loadBooleanArrayElement");
2170
+ }
2171
+
2172
+ /**
2173
+ * @param {number} _idx In bounds index
2174
+ * @return {number} Byte value at index idx as a JS number
2175
+ */
2176
+ loadByteArrayElement(_javaArray, _idx) {
2177
+ throw new Error("Unimplemented: loadByteArrayElement");
2178
+ }
2179
+
2180
+ /**
2181
+ * @param {number} _idx In bounds index
2182
+ * @return {number} Short value at index idx as a JS number
2183
+ */
2184
+ loadShortArrayElement(_javaArray, _idx) {
2185
+ throw new Error("Unimplemented: loadShortArrayElement");
2186
+ }
2187
+
2188
+ /**
2189
+ * @param {number} _idx In bounds index
2190
+ * @return {number} Char value at index idx as a JS number
2191
+ */
2192
+ loadCharArrayElement(_javaArray, _idx) {
2193
+ throw new Error("Unimplemented: loadCharArrayElement");
2194
+ }
2195
+
2196
+ /**
2197
+ * @param {number} _idx In bounds index
2198
+ * @return {number} Int value at index idx as a JS number
2199
+ */
2200
+ loadIntArrayElement(_javaArray, _idx) {
2201
+ throw new Error("Unimplemented: loadIntArrayElement");
2202
+ }
2203
+
2204
+ /**
2205
+ * @param {number} _idx In bounds index
2206
+ * @return {number} Float value at index idx as a JS number
2207
+ */
2208
+ loadFloatArrayElement(_javaArray, _idx) {
2209
+ throw new Error("Unimplemented: loadFloatArrayElement");
2210
+ }
2211
+
2212
+ /**
2213
+ * @param {number} _idx In bounds index
2214
+ * @return {bigint} Long value at index idx as a JS bigint
2215
+ */
2216
+ loadLongArrayElement(_javaArray, _idx) {
2217
+ throw new Error("Unimplemented: loadLongArrayElement");
2218
+ }
2219
+
2220
+ /**
2221
+ * @param {number} _idx In bounds index
2222
+ * @return {number} Double value at index idx as a JS number
2223
+ */
2224
+ loadDoubleArrayElement(_javaArray, _idx) {
2225
+ throw new Error("Unimplemented: loadDoubleArrayElement");
2226
+ }
2227
+
2228
+ /**
2229
+ * @param {number} _idx In bounds index
2230
+ * @return {*} Java object at index idx (caller is responsible for conversion to JS value).
2231
+ */
2232
+ loadObjectArrayElement(_javaArray, _idx) {
2233
+ throw new Error("Unimplemented: loadObjectArrayElement");
2234
+ }
2235
+
2236
+ /**
2237
+ * @param {number} _idx In bounds index
2238
+ * @param {boolean} _jsBoolean JS Boolean value to store at index idx.
2239
+ */
2240
+ storeBooleanArrayElement(_javaArray, _idx, _jsBoolean) {
2241
+ throw new Error("Unimplemented: storeByteArrayElement");
2242
+ }
2243
+
2244
+ /**
2245
+ * @param {number} _idx In bounds index
2246
+ * @param {number} _jsNumber JS number value to store at index idx.
2247
+ */
2248
+ storeByteArrayElement(_javaArray, _idx, _jsNumber) {
2249
+ throw new Error("Unimplemented: storeByteArrayElement");
2250
+ }
2251
+
2252
+ /**
2253
+ * @param {number} _idx In bounds index
2254
+ * @param {number} _jsNumber JS number value to store at index idx.
2255
+ */
2256
+ storeShortArrayElement(_javaArray, _idx, _jsNumber) {
2257
+ throw new Error("Unimplemented: storeShortArrayElement");
2258
+ }
2259
+
2260
+ /**
2261
+ * @param {number} _idx In bounds index
2262
+ * @param {number} _jsNumber JS number value to store at index idx.
2263
+ */
2264
+ storeCharArrayElement(_javaArray, _idx, _jsNumber) {
2265
+ throw new Error("Unimplemented: storeCharArrayElement");
2266
+ }
2267
+
2268
+ /**
2269
+ * @param {number} _idx In bounds index
2270
+ * @param {number} _jsNumber JS number value to store at index idx.
2271
+ */
2272
+ storeIntArrayElement(_javaArray, _idx, _jsNumber) {
2273
+ throw new Error("Unimplemented: storeIntArrayElement");
2274
+ }
2275
+
2276
+ /**
2277
+ * @param {number} _idx In bounds index
2278
+ * @param {number} _jsNumber JS number value to store at index idx.
2279
+ */
2280
+ storeFloatArrayElement(_javaArray, _idx, _jsNumber) {
2281
+ throw new Error("Unimplemented: storeFloatArrayElement");
2282
+ }
2283
+
2284
+ /**
2285
+ * @param {number} _idx In bounds index
2286
+ * @param {bigint} _jsBigInt JS bigint value to store at index idx.
2287
+ */
2288
+ storeLongArrayElement(_javaArray, _idx, _jsBigInt) {
2289
+ throw new Error("Unimplemented: storeLongArrayElement");
2290
+ }
2291
+
2292
+ /**
2293
+ * @param {number} _idx In bounds index
2294
+ * @param {number} _jsNumber JS number value to store at index idx.
2295
+ */
2296
+ storeDoubleArrayElement(_javaArray, _idx, _jsNumber) {
2297
+ throw new Error("Unimplemented: storeDoubleArrayElement");
2298
+ }
2299
+
2300
+ /**
2301
+ * @param {number} _idx In bounds index
2302
+ * @param {*} _javaObjectValue Java object instance to store at index idx (caller is responsible for conversion to Java object).
2303
+ */
2304
+ storeObjectArrayElement(_javaArray, _idx, _javaObjectValue) {
2305
+ throw new Error("Unimplemented: storeObjectArrayElement");
2306
+ }
2307
+ }
2308
+
2309
+ /**
2310
+ * Checks if the given string is an array index and returns the numeric index
2311
+ * (otherwise undefined).
2312
+ *
2313
+ * Proxied accesses always get a string property (even for indexed accesses) so
2314
+ * we need to check if the property access is an indexed access.
2315
+ *
2316
+ * A property is an index if the numeric index it is refering to has the same
2317
+ * string representation as the original property.
2318
+ * E.g the string '010' is a property while '10' is an index.
2319
+ */
2320
+ function getArrayIndex(propertyName) {
2321
+ try {
2322
+ const idx = Number(propertyName);
2323
+ if (idx.toString() === propertyName) {
2324
+ return idx;
2325
+ }
2326
+ } catch (e) {
2327
+ // Catch clause because not all property keys (e.g. symbols) can be
2328
+ // converted to a number.
2329
+ }
2330
+ return undefined;
2331
+ }
2332
+
2333
+ /**
2334
+ * Handle for proxying Java objects.
2335
+ *
2336
+ * Client JS code never directly sees Java object, instead they see proxies
2337
+ * using this handler. The handler is generally specialized per type.
2338
+ * It provides access to the underlying Java methods.
2339
+ *
2340
+ * It also supports invoking the proxy, which calls the single abstract method
2341
+ * in the Java object if available, and for Class objects the new operator
2342
+ * works, creating a Java object and invoking a matching constructor.
2343
+ *
2344
+ * The backends provide method metadata describing the Java methods available
2345
+ * to the proxy. At runtime, when a method call is triggered (a method is
2346
+ * accessed and called, the proxy itself is invoked, or a constructor is called),
2347
+ * the proxy will find a matching implementation based on the types of the
2348
+ * passed arguments.
2349
+ * Arguments and return values are automatically converted to and from Java
2350
+ * objects respectively, but no coercion is done.
2351
+ */
2352
+ class ProxyHandler {
2353
+ constructor(javaHub) {
2354
+ if (javaHub === null || javaHub === undefined) {
2355
+ throw new Error("Got undefined or null javaHub");
2356
+ }
2357
+ this._initialized = false;
2358
+ this._methods = null;
2359
+ this._staticMethods = {};
2360
+ this._javaConstructorMethod = null;
2361
+ this.javaHub = javaHub;
2362
+ this.componentHub = conversion.getComponentHub(javaHub);
2363
+ this.isArray = this.componentHub !== null;
2364
+ this.componentKindOrdinal = this.isArray ? conversion.getHubKindOrdinal(this.componentHub) : -1;
2365
+ }
2366
+
2367
+ _ensureInitialized() {
2368
+ if (!this._initialized) {
2369
+ this._initialized = true;
2370
+ this._methods = this._createLinkedMethodsObject();
2371
+ // Function properties derived from accessible Java methods.
2372
+ this._createProxyMethods();
2373
+ // Default function properties.
2374
+ this._createDefaultMethods();
2375
+ }
2376
+ }
2377
+
2378
+ _getMethods() {
2379
+ this._ensureInitialized();
2380
+ return this._methods;
2381
+ }
2382
+
2383
+ _getStaticMethods() {
2384
+ this._ensureInitialized();
2385
+ return this._staticMethods;
2386
+ }
2387
+
2388
+ _getJavaConstructorMethod() {
2389
+ this._ensureInitialized();
2390
+ return this._javaConstructorMethod;
2391
+ }
2392
+
2393
+ /**
2394
+ * Returns a ClassMetadata instance for the class this proxy handler represents.
2395
+ */
2396
+ _getClassMetadata() {
2397
+ throw new Error("Unimplemented: ProxyHandler._getClassMetadata");
2398
+ }
2399
+
2400
+ _getMethodTable() {
2401
+ const classMeta = this._getClassMetadata();
2402
+ if (classMeta === undefined) {
2403
+ return undefined;
2404
+ }
2405
+ return classMeta.methodTable;
2406
+ }
2407
+
2408
+ /**
2409
+ * String that can be printed as part of the toString and valueOf functions.
2410
+ */
2411
+ _getClassName() {
2412
+ return conversion.getTypeName(this.javaHub);
2413
+ }
2414
+
2415
+ /**
2416
+ * Creates an empty object for the _methods field with the prototype being
2417
+ * the _methods object from the superclass' proxy handler.
2418
+ */
2419
+ _createLinkedMethodsObject() {
2420
+ // Link the prototype chain of the superclass' proxy handler, to include super methods.
2421
+ const parentClass = conversion.getSupertype(this.javaHub);
2422
+ if (parentClass === null) {
2423
+ // This is the handler for java.lang.Object, no linking to supertype necessary.
2424
+ return {};
2425
+ } else {
2426
+ const parentProxyHandler = conversion.getOrCreateProxyHandler(parentClass);
2427
+ // Link the prototype chain of the superclass' proxy handler, to include super methods.
2428
+ return Object.create(parentProxyHandler._getMethods());
2429
+ }
2430
+ }
2431
+
2432
+ _createProxyMethods() {
2433
+ // Create proxy methods for the current class.
2434
+ const methodTable = this._getMethodTable();
2435
+ if (methodTable === undefined) {
2436
+ return;
2437
+ }
2438
+
2439
+ const proxyHandlerThis = this;
2440
+ for (const name in methodTable) {
2441
+ const overloads = methodTable[name];
2442
+ const instanceOverloads = [];
2443
+ const staticOverloads = [];
2444
+ for (const m of overloads) {
2445
+ if (m.isStatic) {
2446
+ staticOverloads.push(m);
2447
+ } else {
2448
+ instanceOverloads.push(m);
2449
+ }
2450
+ }
2451
+ if (instanceOverloads.length > 0) {
2452
+ this._methods[name] = function (...javaScriptArgs) {
2453
+ // Note: the 'this' value is bound to the Proxy object.
2454
+ return proxyHandlerThis._invokeProxyMethod(name, instanceOverloads, this, ...javaScriptArgs);
2455
+ };
2456
+ }
2457
+ if (staticOverloads.length > 0) {
2458
+ this._staticMethods[name] = function (...javaScriptArgs) {
2459
+ // Note: the 'this' value is bound to the Proxy object.
2460
+ return proxyHandlerThis._invokeProxyMethod(name, staticOverloads, null, ...javaScriptArgs);
2461
+ };
2462
+ }
2463
+ }
2464
+ if (methodTable[runtime.symbol.ctor] !== undefined) {
2465
+ const overloads = methodTable[runtime.symbol.ctor];
2466
+ this._javaConstructorMethod = function (javaScriptJavaProxy, ...javaScriptArgs) {
2467
+ // Note: the 'this' value is bound to the Proxy object.
2468
+ return proxyHandlerThis._invokeProxyMethod("<init>", overloads, javaScriptJavaProxy, ...javaScriptArgs);
2469
+ };
2470
+ } else {
2471
+ this._javaConstructorMethod = function (javaScriptJavaProxy, ...javaScriptArgs) {
2472
+ throw new Error(
2473
+ "Cannot invoke the constructor. Make sure that the constructors are explicitly added to the image."
2474
+ );
2475
+ };
2476
+ }
2477
+ }
2478
+
2479
+ /**
2480
+ * Checks whether the given argument values can be used to call the method identified by the given metdata class.
2481
+ */
2482
+ _conforms(args, metadata) {
2483
+ if (metadata.paramHubs.length !== args.length) {
2484
+ return false;
2485
+ }
2486
+ for (let i = 0; i < args.length; i++) {
2487
+ const arg = args[i];
2488
+ let paramHub = metadata.paramHubs[i];
2489
+ if (paramHub === null) {
2490
+ // A null parameter hub means that the type-check always passes.
2491
+ continue;
2492
+ }
2493
+ if (conversion.isPrimitiveHub(paramHub)) {
2494
+ // A primitive hub must be replaced with the hub of the corresponding boxed type.
2495
+ paramHub = conversion.getBoxedHub(paramHub);
2496
+ }
2497
+ if (!conversion.isInstance(arg, paramHub)) {
2498
+ return false;
2499
+ }
2500
+ }
2501
+ return true;
2502
+ }
2503
+
2504
+ _unboxJavaArguments(args, metadata) {
2505
+ // Precondition -- method metadata refers to a method with a correct arity.
2506
+ for (let i = 0; i < args.length; i++) {
2507
+ const paramHub = metadata.paramHubs[i];
2508
+ args[i] = conversion.unboxIfNeeded(args[i], conversion.getHubKindOrdinal(paramHub));
2509
+ }
2510
+ }
2511
+
2512
+ _createDefaultMethods() {
2513
+ if (!this._methods.hasOwnProperty("toString")) {
2514
+ // The check must use hasOwnProperty, because toString always exists in the prototype.
2515
+ this._methods["toString"] = () => "[Java Proxy: " + this._getClassName() + "]";
2516
+ } else {
2517
+ const javaToString = this._methods["toString"];
2518
+ this._methods[runtime.symbol.toString] = javaToString;
2519
+ this._methods["toString"] = function () {
2520
+ // The `this` value must be bound to the proxy instance.
2521
+ //
2522
+ // The `toString` method is used often in JavaScript, and treated specially.
2523
+ // If its return type is a Java String, then that string is converted to a JavaScript string.
2524
+ // In other words, if the result of the call is a JavaScript proxy (see _invokeProxyMethod return value),
2525
+ // then proxies that represent java.lang.String are converted to JavaScript strings.
2526
+ const javaScriptResult = javaToString.call(this);
2527
+ if (typeof javaScriptResult === "function" || typeof javaScriptResult === "object") {
2528
+ const javaResult = conversion.tryUnproxy(javaScriptResult);
2529
+ if (javaResult !== undefined && conversion.isJavaLangString(javaResult)) {
2530
+ return conversion.extractJavaScriptString(javaResult);
2531
+ }
2532
+ }
2533
+ return javaScriptResult;
2534
+ };
2535
+ }
2536
+
2537
+ // Override Java methods that return valueOf.
2538
+ // JavaScript requires that valueOf returns a JavaScript primitive (in this case, string).
2539
+ this._methods["valueOf"] = () => "[Java Proxy: " + this._getClassName() + "]";
2540
+
2541
+ const proxyHandlerThis = this;
2542
+ const asProperty = function (tpe) {
2543
+ // Note: 'this' will usually be bound to the Proxy object.
2544
+ return conversion.coerceJavaProxyToJavaScriptType(proxyHandlerThis, this, tpe);
2545
+ };
2546
+ this._methods["$as"] = asProperty;
2547
+ this._methods[runtime.symbol.javaScriptCoerceAs] = asProperty;
2548
+
2549
+ const vmProperty = vm;
2550
+ if (!("$vm" in this._methods)) {
2551
+ this._methods["$vm"] = vmProperty;
2552
+ }
2553
+ }
2554
+
2555
+ _loadMethod(target, key) {
2556
+ const member = this._getMethods()[key];
2557
+ if (member !== undefined) {
2558
+ return member;
2559
+ }
2560
+ }
2561
+
2562
+ _methodNames() {
2563
+ return Object.keys(this._getMethods());
2564
+ }
2565
+
2566
+ _invokeProxyMethod(name, overloads, javaScriptJavaProxy, ...javaScriptArgs) {
2567
+ // For static methods, javaScriptThis is set to null.
2568
+ const isStatic = javaScriptJavaProxy === null;
2569
+ const javaThis = isStatic ? null : conversion.unproxy(javaScriptJavaProxy);
2570
+ const javaArgs = conversion.eachJavaScriptToJava(javaScriptArgs);
2571
+ for (let i = 0; i < overloads.length; i++) {
2572
+ const metadata = overloads[i];
2573
+ if (this._conforms(javaArgs, metadata)) {
2574
+ // Where necessary, perform unboxing of Java arguments.
2575
+ this._unboxJavaArguments(javaArgs, metadata);
2576
+ let javaResult;
2577
+ try {
2578
+ if (isStatic) {
2579
+ javaResult = metadata.method.call(null, ...javaArgs);
2580
+ } else {
2581
+ javaResult = metadata.method.call(null, javaThis, ...javaArgs);
2582
+ }
2583
+ } catch (error) {
2584
+ throw conversion.javaToJavaScript(error);
2585
+ }
2586
+ if (javaResult === undefined) {
2587
+ // This only happens when the return type is void.
2588
+ return undefined;
2589
+ }
2590
+ // If necessary, box the Java return value.
2591
+ const retHub = metadata.returnHub;
2592
+ javaResult = conversion.boxIfNeeded(javaResult, conversion.getHubKindOrdinal(retHub));
2593
+ const javaScriptResult = conversion.javaToJavaScript(javaResult);
2594
+ return javaScriptResult;
2595
+ }
2596
+ }
2597
+ const methodName = name !== null ? "method '" + name + "'" : "single abstract method";
2598
+ throw new Error("No matching signature for " + methodName + " and argument list '" + javaScriptArgs + "'");
2599
+ }
2600
+
2601
+ _extractJavaObject(target) {
2602
+ return target(runtime.symbol.javaNative);
2603
+ }
2604
+
2605
+ /**
2606
+ * The Java type hierarchy is not modelled in the proxy and the proxied
2607
+ * object has no prototype.
2608
+ */
2609
+ getPrototypeOf(target) {
2610
+ return null;
2611
+ }
2612
+
2613
+ /**
2614
+ * Modifying the prototype of the proxied object is not allowed.
2615
+ */
2616
+ setPrototypeOf(target, prototype) {
2617
+ return false;
2618
+ }
2619
+
2620
+ /**
2621
+ * Proxied objects are not extensible in any way.
2622
+ */
2623
+ isExtensible(target) {
2624
+ return false;
2625
+ }
2626
+
2627
+ /**
2628
+ * We allow calling Object.preventExtensions on the proxy.
2629
+ * However, it won't do anything, the proxy handler already prevents extensions.
2630
+ */
2631
+ preventExtensions(target) {
2632
+ return true;
2633
+ }
2634
+
2635
+ getOwnPropertyDescriptor(target, key) {
2636
+ if (key === runtime.symbol.isProxy) {
2637
+ return {
2638
+ value: true,
2639
+ writable: false,
2640
+ enumerable: false,
2641
+ configurable: false,
2642
+ };
2643
+ }
2644
+
2645
+ const value = this._loadMethod(target, key);
2646
+ if (value === undefined) {
2647
+ return undefined;
2648
+ }
2649
+ return {
2650
+ value: value,
2651
+ writable: false,
2652
+ enumerable: false,
2653
+ configurable: false,
2654
+ };
2655
+ }
2656
+
2657
+ /**
2658
+ * Defining properties on the Java object is not allowed.
2659
+ */
2660
+ defineProperty(target, key, descriptor) {
2661
+ return false;
2662
+ }
2663
+
2664
+ has(target, key) {
2665
+ if (key === runtime.symbol.isProxy) {
2666
+ return true;
2667
+ }
2668
+ return this._loadMethod(target, key) !== undefined;
2669
+ }
2670
+
2671
+ get(target, key) {
2672
+ const javaObject = this._extractJavaObject(target);
2673
+ if (key === runtime.symbol.javaNative) {
2674
+ return javaObject;
2675
+ } else if (key === runtime.symbol.isProxy) {
2676
+ return true;
2677
+ } else if (this.isArray) {
2678
+ const componentKindOrdinal = this.componentKindOrdinal;
2679
+ const length = conversion.getArrayLength(javaObject);
2680
+ if (key === "length") {
2681
+ return length;
2682
+ } else if (key === Symbol.iterator) {
2683
+ return function () {
2684
+ return (function* () {
2685
+ for (let i = 0; i < length; i++) {
2686
+ yield conversion.loadArrayElement(javaObject, componentKindOrdinal, i);
2687
+ }
2688
+ })();
2689
+ };
2690
+ }
2691
+
2692
+ const potentialIdx = getArrayIndex(key);
2693
+
2694
+ if (potentialIdx !== undefined) {
2695
+ if (potentialIdx < 0 || potentialIdx >= length) {
2696
+ return undefined;
2697
+ }
2698
+ return conversion.loadArrayElement(javaObject, componentKindOrdinal, potentialIdx);
2699
+ }
2700
+ }
2701
+ return this._loadMethod(target, key);
2702
+ }
2703
+
2704
+ set(target, key, value) {
2705
+ if (this.isArray) {
2706
+ const potentialIdx = getArrayIndex(key);
2707
+
2708
+ if (potentialIdx !== undefined) {
2709
+ const javaObject = this._extractJavaObject(target);
2710
+ conversion.storeArrayElement(javaObject, this.componentKindOrdinal, potentialIdx, value);
2711
+ return true;
2712
+ }
2713
+ }
2714
+
2715
+ return false;
2716
+ }
2717
+
2718
+ /**
2719
+ * Deleting properties on the Java object is not allowed.
2720
+ */
2721
+ deleteProperty(target, key) {
2722
+ return false;
2723
+ }
2724
+
2725
+ ownKeys(target) {
2726
+ return this._methodNames();
2727
+ }
2728
+
2729
+ apply(target, javaScriptThisArg, javaScriptArgs) {
2730
+ // We need to convert the Proxy's target function to the Java Proxy.
2731
+ const javaScriptJavaProxy = conversion.toProxy(this._extractJavaObject(target));
2732
+ // Note: the JavaScript this argument for the apply method is never exposed to Java, so we just ignore it.
2733
+ return this._applyWithObject(javaScriptJavaProxy, javaScriptArgs);
2734
+ }
2735
+
2736
+ _getSingleAbstractMethod(javaScriptJavaProxy) {
2737
+ return this._getClassMetadata().singleAbstractMethod;
2738
+ }
2739
+
2740
+ _applyWithObject(javaScriptJavaProxy, javaScriptArgs) {
2741
+ const sam = this._getSingleAbstractMethod(javaScriptJavaProxy);
2742
+ if (sam === undefined) {
2743
+ throw new Error("Java Proxy is not a functional interface, so 'apply' cannot be called from JavaScript.");
2744
+ }
2745
+ return this._invokeProxyMethod(null, [sam], javaScriptJavaProxy, ...javaScriptArgs);
2746
+ }
2747
+
2748
+ /**
2749
+ * Create uninitialized instance of given Java type.
2750
+ */
2751
+ _createInstance(hub) {
2752
+ throw new Error("Unimplemented: ProxyHandler._createInstance");
2753
+ }
2754
+
2755
+ construct(target, argumentsList) {
2756
+ const javaThis = this._extractJavaObject(target);
2757
+ // This is supposed to be a proxy handler for java.lang.Class objects
2758
+ // and javaThis is supposed to be some Class instance.
2759
+ if (!conversion.isJavaLangClass(javaThis)) {
2760
+ throw new Error(
2761
+ "Cannot invoke the 'new' operator. The 'new' operator can only be used on Java Proxies that represent the 'java.lang.Class' type."
2762
+ );
2763
+ }
2764
+
2765
+ if (conversion.getComponentHub(javaThis) !== null) {
2766
+ throw new TypeError(
2767
+ "Cannot invoke the 'new' operator on a Java proxy that represents the 'java.lang.Class' instance for an array."
2768
+ );
2769
+ }
2770
+
2771
+ // Allocate the Java object from Class instance
2772
+ const javaInstance = this._createInstance(javaThis);
2773
+ // Lookup constructor method of the target class.
2774
+ // This proxy handler is for java.lang.Class while javaThis is a
2775
+ // java.lang.Class instance for some object type for which we want to
2776
+ // lookup the constructor.
2777
+ const instanceProxyHandler = conversion.getOrCreateProxyHandler(conversion.getHub(javaInstance));
2778
+ const javaConstructorMethod = instanceProxyHandler._getJavaConstructorMethod();
2779
+ // Get JS proxy for the Java object
2780
+ const jsProxy = conversion.toProxy(javaInstance);
2781
+ // Call the Java constructor method.
2782
+ javaConstructorMethod(jsProxy, ...argumentsList);
2783
+ return jsProxy;
2784
+ }
2785
+ }
2786
+
2787
+
2788
+ /*
2789
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
2790
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
2791
+ *
2792
+ * This code is free software; you can redistribute it and/or modify it
2793
+ * under the terms of the GNU General Public License version 2 only, as
2794
+ * published by the Free Software Foundation. Oracle designates this
2795
+ * particular file as subject to the "Classpath" exception as provided
2796
+ * by Oracle in the LICENSE file that accompanied this code.
2797
+ *
2798
+ * This code is distributed in the hope that it will be useful, but WITHOUT
2799
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
2800
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
2801
+ * version 2 for more details (a copy is included in the LICENSE file that
2802
+ * accompanied this code).
2803
+ *
2804
+ * You should have received a copy of the GNU General Public License version
2805
+ * 2 along with this work; if not, write to the Free Software Foundation,
2806
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
2807
+ *
2808
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2809
+ * or visit www.oracle.com if you need additional information or have any
2810
+ * questions.
2811
+ */
2812
+
2813
+ /**
2814
+ * WasmGC-backend specific implementation of conversion code.
2815
+ *
2816
+ * In the WasmGC backend, all Java values are originally Wasm values, with
2817
+ * objects being references to Wasm structs. How those values are represented
2818
+ * in Java is governed by the "WebAssembly JavaScript Interface".
2819
+ * Java Objects are represented as opaque JS objects, these objects do not have
2820
+ * any properties of their own nor are they extensible (though identity with
2821
+ * regards to the === operator is preserved), only when passing them back to
2822
+ * Wasm code can they be manipulated.
2823
+ * Java long values are represented as JS BigInt values.
2824
+ *
2825
+ * Unlike the JS backend, Java code compiled to WasmGC cannot directly be passed
2826
+ * JS objects as arguments due to Wasm's type safety. Instead, JS values are
2827
+ * first wrapped in WasmExtern, a custom Java class with some special handling
2828
+ * to have it store and externref value in one of its fields.
2829
+ *
2830
+ * To support JSValue instances, there are Java factory methods for each
2831
+ * subclass exported under convert.create.*, which create a new instance of the
2832
+ * type and associate it with the given JavaScript value.
2833
+ * Instead of having the JS code store the JS native value directly in the
2834
+ * WasmGC object (which won't work because they are immutable on the JS side),
2835
+ * the JS value is first wrapped in a WasmExtern, and then passed to Java, where
2836
+ * that WasmExtern value is stored in a hidden field of the JSValue instance.
2837
+ */
2838
+ class WasmGCConversion extends Conversion {
2839
+ constructor() {
2840
+ super();
2841
+ this.proxyHandlers = new WeakMap();
2842
+ }
2843
+
2844
+ #wrapExtern(jsObj) {
2845
+ return getExport("extern.wrap")(jsObj);
2846
+ }
2847
+
2848
+ #unwrapExtern(javaObj) {
2849
+ return getExport("extern.unwrap")(javaObj);
2850
+ }
2851
+
2852
+ handleJSError(jsError) {
2853
+ if (jsError instanceof WebAssembly.Exception) {
2854
+ // Wasm exceptions can be rethrown as-is. They will be caught in Wasm code
2855
+ throw jsError;
2856
+ } else {
2857
+ // Have Java code wrap the JS error in a Java JSError instance and throw it.
2858
+ getExport("convert.throwjserror")(this.javaScriptToJava(jsError));
2859
+ }
2860
+ }
2861
+
2862
+ extractJavaScriptNumber(jldouble) {
2863
+ return getExport("unbox.double")(jldouble);
2864
+ }
2865
+
2866
+ extractJavaScriptString(jlstring) {
2867
+ return charArrayToString(proxyCharArray(getExport("string.tochars")(jlstring)));
2868
+ }
2869
+
2870
+ createJavaBoolean(x) {
2871
+ return getExport("box.boolean")(x);
2872
+ }
2873
+
2874
+ createJavaByte(x) {
2875
+ return getExport("box.byte")(x);
2876
+ }
2877
+
2878
+ createJavaShort(x) {
2879
+ return getExport("box.short")(x);
2880
+ }
2881
+
2882
+ createJavaCharacter(x) {
2883
+ return getExport("box.char")(x);
2884
+ }
2885
+
2886
+ createJavaInteger(x) {
2887
+ return getExport("box.int")(x);
2888
+ }
2889
+
2890
+ createJavaFloat(x) {
2891
+ return getExport("box.float")(x);
2892
+ }
2893
+
2894
+ createJavaLong(x) {
2895
+ return getExport("box.long")(x);
2896
+ }
2897
+
2898
+ createJavaDouble(x) {
2899
+ return getExport("box.double")(x);
2900
+ }
2901
+
2902
+ getHubKindOrdinal(hub) {
2903
+ return getExport("class.getkindordinal")(hub);
2904
+ }
2905
+
2906
+ getBoxedHub(jlClass) {
2907
+ return getExport("class.getboxedhub")(jlClass);
2908
+ }
2909
+
2910
+ unboxBoolean(jlBoolean) {
2911
+ return getExport("unbox.boolean")(jlBoolean);
2912
+ }
2913
+
2914
+ unboxByte(jlByte) {
2915
+ return getExport("unbox.byte")(jlByte);
2916
+ }
2917
+
2918
+ unboxShort(jlShort) {
2919
+ return getExport("unbox.short")(jlShort);
2920
+ }
2921
+
2922
+ unboxChar(jlChar) {
2923
+ return getExport("unbox.char")(jlChar);
2924
+ }
2925
+
2926
+ unboxInt(jlInt) {
2927
+ return getExport("unbox.int")(jlInt);
2928
+ }
2929
+
2930
+ unboxFloat(jlFloat) {
2931
+ return getExport("unbox.float")(jlFloat);
2932
+ }
2933
+
2934
+ unboxLong(jlLong) {
2935
+ return getExport("unbox.long")(jlLong);
2936
+ }
2937
+
2938
+ unboxDouble(jlDouble) {
2939
+ return getExport("unbox.double")(jlDouble);
2940
+ }
2941
+
2942
+ createJSUndefined() {
2943
+ return getExport("convert.create.jsundefined")();
2944
+ }
2945
+
2946
+ createJSBoolean(boolean) {
2947
+ return getExport("convert.create.jsboolean")(this.#wrapExtern(boolean));
2948
+ }
2949
+
2950
+ createJSNumber(number) {
2951
+ return getExport("convert.create.jsnumber")(this.#wrapExtern(number));
2952
+ }
2953
+
2954
+ createJSBigInt(bigint) {
2955
+ return getExport("convert.create.jsbigint")(this.#wrapExtern(bigint));
2956
+ }
2957
+
2958
+ createJSString(string) {
2959
+ return getExport("convert.create.jsstring")(this.#wrapExtern(string));
2960
+ }
2961
+
2962
+ createJSSymbol(symbol) {
2963
+ return getExport("convert.create.jssymbol")(this.#wrapExtern(symbol));
2964
+ }
2965
+
2966
+ createJSObject(obj) {
2967
+ return getExport("convert.create.jsobject")(this.#wrapExtern(obj));
2968
+ }
2969
+
2970
+ isInternalJavaObject(obj) {
2971
+ return getExport("extern.isjavaobject")(obj);
2972
+ }
2973
+
2974
+ isPrimitiveHub(hub) {
2975
+ return getExport("class.isprimitive")(hub);
2976
+ }
2977
+
2978
+ isJavaLangString(obj) {
2979
+ return getExport("convert.isjavalangstring")(obj);
2980
+ }
2981
+
2982
+ isJavaLangClass(obj) {
2983
+ return getExport("convert.isjavalangclass")(obj);
2984
+ }
2985
+
2986
+ isInstance(obj, hub) {
2987
+ return getExport("object.isinstance")(obj, hub);
2988
+ }
2989
+
2990
+ getHub(obj) {
2991
+ return getExport("object.getclass")(obj);
2992
+ }
2993
+
2994
+ getSupertype(hub) {
2995
+ return getExport("class.superclass")(hub);
2996
+ }
2997
+
2998
+ getComponentHub(hub) {
2999
+ return getExport("class.componenttype")(hub);
3000
+ }
3001
+
3002
+ getTypeNameAsJavaString(hub) {
3003
+ return getExport("class.getname")(hub);
3004
+ }
3005
+
3006
+ getOrCreateProxyHandler(hub) {
3007
+ if (!this.proxyHandlers.has(hub)) {
3008
+ this.proxyHandlers.set(hub, new WasmGCProxyHandler(hub));
3009
+ }
3010
+ return this.proxyHandlers.get(hub);
3011
+ }
3012
+
3013
+ javaToJavaScript(x) {
3014
+ let effectiveJavaObject = x;
3015
+
3016
+ /*
3017
+ * When catching exceptions in JavaScript, exceptions thrown from Java
3018
+ * aren't caught as Java objects, but as WebAssembly.Exception objects.
3019
+ * Instead of having to do special handling whenever we catch an
3020
+ * exception in JS, converting to JavaScript first unwraps the original
3021
+ * Java Throwable before converting.
3022
+ */
3023
+ if (x instanceof WebAssembly.Exception && x.is(getExport("tag.throwable"))) {
3024
+ effectiveJavaObject = x.getArg(getExport("tag.throwable"), 0);
3025
+ }
3026
+
3027
+ return this.#unwrapExtern(getExport("convert.javatojavascript")(effectiveJavaObject));
3028
+ }
3029
+
3030
+ throwClassCastExceptionImpl(javaObject, tpeNameJavaString) {
3031
+ getExport("convert.throwClassCastException")(javaObject, tpeNameJavaString);
3032
+ }
3033
+
3034
+ coerceJavaProxyToJavaScriptType(proxyHandler, proxy, tpe) {
3035
+ const o = this.unproxy(proxy);
3036
+ switch (tpe) {
3037
+ case "boolean":
3038
+ // Due to Java booleans being numbers, the double-negation is necessary.
3039
+ return !!getExport("convert.coerce.boolean")(o);
3040
+ case "number":
3041
+ return getExport("convert.coerce.number")(o);
3042
+ case "bigint":
3043
+ const bs = this.#unwrapExtern(getExport("convert.coerce.bigint")(o));
3044
+ return BigInt(bs);
3045
+ case "string":
3046
+ return this.#unwrapExtern(getExport("convert.coerce.string")(o));
3047
+ case "function":
3048
+ const sam = proxyHandler._getSingleAbstractMethod(proxy);
3049
+ if (sam !== undefined) {
3050
+ return (...args) => proxyHandler._applyWithObject(proxy, args);
3051
+ }
3052
+ this.throwClassCastException(o, tpe);
3053
+ default:
3054
+ this.throwClassCastException(o, tpe);
3055
+ }
3056
+ }
3057
+
3058
+ getArrayLength(javaArray) {
3059
+ return getExport("array.length")(javaArray);
3060
+ }
3061
+
3062
+ loadBooleanArrayElement(javaArray, idx) {
3063
+ return !!getExport("array.boolean.read")(javaArray, idx);
3064
+ }
3065
+
3066
+ loadByteArrayElement(javaArray, idx) {
3067
+ return getExport("array.byte.read")(javaArray, idx);
3068
+ }
3069
+
3070
+ loadShortArrayElement(javaArray, idx) {
3071
+ return getExport("array.short.read")(javaArray, idx);
3072
+ }
3073
+
3074
+ loadCharArrayElement(javaArray, idx) {
3075
+ return getExport("array.char.read")(javaArray, idx);
3076
+ }
3077
+
3078
+ loadIntArrayElement(javaArray, idx) {
3079
+ return getExport("array.int.read")(javaArray, idx);
3080
+ }
3081
+
3082
+ loadFloatArrayElement(javaArray, idx) {
3083
+ return getExport("array.float.read")(javaArray, idx);
3084
+ }
3085
+
3086
+ loadLongArrayElement(javaArray, idx) {
3087
+ return getExport("array.long.read")(javaArray, idx);
3088
+ }
3089
+
3090
+ loadDoubleArrayElement(javaArray, idx) {
3091
+ return getExport("array.double.read")(javaArray, idx);
3092
+ }
3093
+
3094
+ loadObjectArrayElement(javaArray, idx) {
3095
+ return getExport("array.object.read")(javaArray, idx);
3096
+ }
3097
+
3098
+ storeBooleanArrayElement(javaArray, idx, jsBoolean) {
3099
+ getExport("array.boolean.write")(javaArray, idx, jsBoolean ? 1 : 0);
3100
+ }
3101
+
3102
+ storeByteArrayElement(javaArray, idx, jsNumber) {
3103
+ getExport("array.byte.write")(javaArray, idx, jsNumber);
3104
+ }
3105
+
3106
+ storeShortArrayElement(javaArray, idx, jsNumber) {
3107
+ getExport("array.short.write")(javaArray, idx, jsNumber);
3108
+ }
3109
+
3110
+ storeCharArrayElement(javaArray, idx, jsNumber) {
3111
+ getExport("array.char.write")(javaArray, idx, jsNumber);
3112
+ }
3113
+
3114
+ storeIntArrayElement(javaArray, idx, jsNumber) {
3115
+ getExport("array.int.write")(javaArray, idx, jsNumber);
3116
+ }
3117
+
3118
+ storeFloatArrayElement(javaArray, idx, jsNumber) {
3119
+ getExport("array.float.write")(javaArray, idx, jsNumber);
3120
+ }
3121
+
3122
+ storeLongArrayElement(javaArray, idx, jsBigInt) {
3123
+ getExport("array.long.write")(javaArray, idx, jsBigInt);
3124
+ }
3125
+
3126
+ storeDoubleArrayElement(javaArray, idx, jsNumber) {
3127
+ getExport("array.double.write")(javaArray, idx, jsNumber);
3128
+ }
3129
+
3130
+ storeObjectArrayElement(javaArray, idx, javaObjectValue) {
3131
+ getExport("array.object.write")(javaArray, idx, javaObjectValue);
3132
+ }
3133
+ }
3134
+
3135
+ const METADATA_PREFIX = "META.";
3136
+ const SAM_PREFIX = "SAM.";
3137
+ const METADATA_SEPARATOR = " ";
3138
+
3139
+ class WasmGCProxyHandler extends ProxyHandler {
3140
+ #classMetadata = null;
3141
+
3142
+ #lookupClass(name) {
3143
+ const clazz = getExport("conversion.classfromencoding")(toJavaString(name));
3144
+ if (!clazz) {
3145
+ throw new Error("Failed to lookup class " + name);
3146
+ }
3147
+
3148
+ return clazz;
3149
+ }
3150
+
3151
+ _getClassMetadata() {
3152
+ if (!this.#classMetadata) {
3153
+ this.#classMetadata = new ClassMetadata({}, this.#extractSingleAbstractMethod(), this.#createMethodTable());
3154
+ }
3155
+ return this.#classMetadata;
3156
+ }
3157
+
3158
+ #decodeMetadata(exports, name, prefix) {
3159
+ if (name.startsWith(prefix)) {
3160
+ const parts = name.slice(prefix.length).split(METADATA_SEPARATOR);
3161
+ if (parts.length < 3) {
3162
+ throw new Error("Malformed metadata: " + name);
3163
+ }
3164
+ const classId = parts[0];
3165
+
3166
+ if (this.#lookupClass(classId) == this.javaHub) {
3167
+ const methodName = parts[1];
3168
+ const returnTypeId = parts[2];
3169
+ const argTypeIds = parts.slice(3);
3170
+
3171
+ return [
3172
+ methodName,
3173
+ mmeta(
3174
+ exports[name],
3175
+ this.#lookupClass(returnTypeId),
3176
+ ...argTypeIds.map((i) => this.#lookupClass(i))
3177
+ ),
3178
+ ];
3179
+ }
3180
+ }
3181
+
3182
+ return undefined;
3183
+ }
3184
+
3185
+ #extractSingleAbstractMethod() {
3186
+ const exports = getExports();
3187
+
3188
+ for (const name in exports) {
3189
+ const meta = this.#decodeMetadata(exports, name, SAM_PREFIX);
3190
+ if (meta !== undefined) {
3191
+ return meta[1];
3192
+ }
3193
+ }
3194
+
3195
+ return undefined;
3196
+ }
3197
+
3198
+ #createMethodTable() {
3199
+ const exports = getExports();
3200
+ const methodTable = {};
3201
+
3202
+ for (const name in exports) {
3203
+ const meta = this.#decodeMetadata(exports, name, METADATA_PREFIX);
3204
+ if (meta !== undefined) {
3205
+ let methodName = meta[0];
3206
+
3207
+ if (methodName === "<init>") {
3208
+ methodName = runtime.symbol.ctor;
3209
+ }
3210
+
3211
+ if (!methodTable.hasOwnProperty(methodName)) {
3212
+ methodTable[methodName] = [];
3213
+ }
3214
+
3215
+ methodTable[methodName].push(meta[1]);
3216
+ }
3217
+ }
3218
+
3219
+ return methodTable;
3220
+ }
3221
+
3222
+ _createInstance(hub) {
3223
+ return getExport("unsafe.create")(hub);
3224
+ }
3225
+ }
3226
+
3227
+ const conversion = new WasmGCConversion();
3228
+ const createVM = function(vmArgs, data) {
3229
+ runtime.data = data;
3230
+ wasmRun(vmArgs);
3231
+
3232
+ return vm;
3233
+
3234
+ };
3235
+ GraalVM.Config = Config;
3236
+ /** @suppress {checkVars,duplicate} */ GraalVM.run = async function (vmArgs, config = new GraalVM.Config()) {
3237
+ let data = new Data(config);
3238
+ for (let libname in config.libraries) {
3239
+ const content = await runtime.fetchText(config.libraries[libname]);
3240
+ data.libraries[libname] = content;
3241
+ }
3242
+ data.wasm = await wasmInstantiate(config, vmArgs);
3243
+ let vm = createVM(vmArgs, data);
3244
+ return vm;
3245
+ }
3246
+ })();
3247
+
3248
+ })();
3249
+
3250
+ })();
3251
+
3252
+ (function() {
3253
+ /*
3254
+ * Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
3255
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3256
+ *
3257
+ * This code is free software; you can redistribute it and/or modify it
3258
+ * under the terms of the GNU General Public License version 2 only, as
3259
+ * published by the Free Software Foundation. Oracle designates this
3260
+ * particular file as subject to the "Classpath" exception as provided
3261
+ * by Oracle in the LICENSE file that accompanied this code.
3262
+ *
3263
+ * This code is distributed in the hope that it will be useful, but WITHOUT
3264
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
3265
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
3266
+ * version 2 for more details (a copy is included in the LICENSE file that
3267
+ * accompanied this code).
3268
+ *
3269
+ * You should have received a copy of the GNU General Public License version
3270
+ * 2 along with this work; if not, write to the Free Software Foundation,
3271
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
3272
+ *
3273
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
3274
+ * or visit www.oracle.com if you need additional information or have any
3275
+ * questions.
3276
+ */
3277
+
3278
+ /**
3279
+ * Try to load commandline arguments for various JS runtimes.
3280
+ */
3281
+ function load_cmd_args() {
3282
+ if (typeof process === "object" && "argv" in process) {
3283
+ // nodejs
3284
+ return process.argv.slice(2);
3285
+ } else if (typeof scriptArgs == "object") {
3286
+ // spidermonkey
3287
+ return scriptArgs;
3288
+ }
3289
+
3290
+ return [];
3291
+ }
3292
+
3293
+ const config = new GraalVM.Config();
3294
+ // Inserted into a Web Image launcher after `const config = new GraalVM.Config();` (julc-wasm README, step 2). The
3295
+ // worker says where the module is, and hears when main stops with an error before the engine is ready.
3296
+ if (globalThis.JULC_WASM_PATH) config.wasm_path = globalThis.JULC_WASM_PATH;
3297
+ {
3298
+ const run = GraalVM.run;
3299
+ GraalVM.run = (...args) => run(...args).then(vm => {
3300
+ if (vm.exitCode !== 0) globalThis.onJulcExit?.(vm.exitCode);
3301
+ return vm;
3302
+ });
3303
+ }
3304
+
3305
+ GraalVM.run(load_cmd_args(),config).catch(e => { console.error(e); throw e; });
3306
+ })();