diff --git a/.gitmodules b/.gitmodules index 7913129bb..82c79cfdf 100644 --- a/.gitmodules +++ b/.gitmodules @@ -8,3 +8,6 @@ path = test-app/build-tools/android-dts-generator url = https://github.com/NativeScript/android-dts-generator.git branch = main +[submodule "test-app/runtime/src/main/cpp/runtime-common"] + path = test-app/runtime/src/main/cpp/runtime-common + url = https://github.com/NativeScript/runtime-common.git diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 1372040c6..5213b32a3 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -776,7 +776,7 @@ unmodified where a shim exists: |---|---|---| | `node:util` | `inspect`, `format`, `TextEncoder`, `TextDecoder` | Re-exports `ns:util`'s members unchanged (`nodeUtil.inspect === nsUtil.inspect`) from a **distinct, separately frozen module object**. `TextEncoder`/`TextDecoder` are the globals of those names, as they are in Node. Documented as partial. | | `node:url` | `URL`, `URLSearchParams`, `fileURLToPath`, `pathToFileURL` | Re-exports `ns:url`'s members unchanged (`nodeUrl.fileURLToPath === nsUrl.fileURLToPath`) from a **distinct, separately frozen module object**; the converters are Node-strict and throw Node's messages. Documented as partial — no legacy `url.parse`/`format`/`resolve`, and no `URLPattern` (Node's `node:url` has none). | -| `node:module` | `createRequire` | Re-exports `ns:module`'s `createRequire` unchanged from a **distinct, separately frozen module object**. `createPumpingRequire` is deliberately absent: it has no Node counterpart, so code written against this shim keeps running on Node. `require.resolve`/`.cache`/`.main` are not implemented, and neither is any other `node:module` member (`Module`, `builtinModules`, `isBuiltin`, `register`, `syncBuiltinESMExports`). Documented as partial. | +| `node:module` | `createRequire` | Re-exports `ns:module`'s `createRequire` unchanged from a **distinct, separately frozen module object**. `createPumpingRequire` is deliberately absent: it has no Node counterpart, so code written against this shim keeps running on Node. `require.cache` is not implemented (`require.resolve` and `require.main` are), and neither is any other `node:module` member (`Module`, `builtinModules`, `isBuiltin`, `register`, `syncBuiltinESMExports`). Documented as partial. | | `node:worker_threads` | the messaging and thread surface — see [worker-threads.md](worker-threads.md) | The channel half (`MessagePort`, `MessageChannel`, `BroadcastChannel`, `receiveMessageOnPort`) is the real implementation, the same objects the globals of those names hold; the thread half is a bridge over the `Worker` that `ns:worker_threads` exports. The channel half has no `ns:` counterpart — its surface tracks Node's, so there is nothing for a standard module to own. The one place it breaks the absent-not-throwing rule below is deliberate: `postMessageToThread` and `moveMessagePortToContext` are present and throw an `Error` naming themselves, because silently missing thread-addressed messaging reads as a delivery bug rather than as an unsupported call. Documented as partial. | ## Loading ES modules @@ -1379,7 +1379,7 @@ internal require is a fixed parameter of the builtin function wrapper (`exports`, `require`, `module`, `binding`, `primordials`). The files under `js/` that are *not* in the public registry — `primordials.js`, -`require-factory.js`, `inspect.js`, `json-helper.js`, `events.js`, +`inspect.js`, `json-helper.js`, `events.js`, `error-events.js`, `structured-clone.js`, `blob-url.js`, `performance.js`, `weak-ref.js`, `interop-globals.js` — are the internal builtins: each is run from its own native call site and none is named in the public registry. diff --git a/test-app/app/src/main/assets/app/esm/createrequire/cycle-requirer.mjs b/test-app/app/src/main/assets/app/esm/createrequire/cycle-requirer.mjs new file mode 100644 index 000000000..b86aad830 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/createrequire/cycle-requirer.mjs @@ -0,0 +1,11 @@ +import { createRequire } from "node:module"; + +let attempt; +try { + createRequire(import.meta.url)("./cycle-root.mjs"); + attempt = ""; +} catch (e) { + attempt = String(e && e.code) + ": " + String((e && e.message) || e); +} + +export { attempt }; diff --git a/test-app/app/src/main/assets/app/esm/createrequire/cycle-root.mjs b/test-app/app/src/main/assets/app/esm/createrequire/cycle-root.mjs new file mode 100644 index 000000000..67360f4ca --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/createrequire/cycle-root.mjs @@ -0,0 +1,5 @@ +// Statically imports a module that require()s this one while it is still +// evaluating. +import { attempt } from "./cycle-requirer.mjs"; + +export const outcome = attempt; diff --git a/test-app/app/src/main/assets/app/esm/createrequire/identity-import-first.mjs b/test-app/app/src/main/assets/app/esm/createrequire/identity-import-first.mjs new file mode 100644 index 000000000..2bc2e6299 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/createrequire/identity-import-first.mjs @@ -0,0 +1,6 @@ +// Reached by import() first, then by require(): both must see this one +// evaluation. +const counts = globalThis.__nsIdentityEvaluations || (globalThis.__nsIdentityEvaluations = {}); +counts.importFirst = (counts.importFirst || 0) + 1; + +export const token = {}; diff --git a/test-app/app/src/main/assets/app/esm/createrequire/identity-require-first.mjs b/test-app/app/src/main/assets/app/esm/createrequire/identity-require-first.mjs new file mode 100644 index 000000000..d60113bf0 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/createrequire/identity-require-first.mjs @@ -0,0 +1,6 @@ +// Reached by require() first, then by import(): both must see this one +// evaluation. +const counts = globalThis.__nsIdentityEvaluations || (globalThis.__nsIdentityEvaluations = {}); +counts.requireFirst = (counts.requireFirst || 0) + 1; + +export const token = {}; diff --git a/test-app/app/src/main/assets/app/esm/createrequire/tla-still-running.mjs b/test-app/app/src/main/assets/app/esm/createrequire/tla-still-running.mjs new file mode 100644 index 000000000..8bf569762 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/createrequire/tla-still-running.mjs @@ -0,0 +1,10 @@ +// Started by import() and still parked in its top-level await when a pumping +// require() asks for it. Its export is declared after the await, so a +// namespace read before the evaluation settled would throw. +globalThis.__nsTlaStillRunningStarted = true; + +await new Promise(function (resolve) { + __ns__setTimeout(resolve, 300); +}); + +export const value = "settled"; diff --git a/test-app/app/src/main/assets/app/esm/json-strict/comment.json b/test-app/app/src/main/assets/app/esm/json-strict/comment.json new file mode 100644 index 000000000..b61336889 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/comment.json @@ -0,0 +1,2 @@ +// a comment +{"a": 1} diff --git a/test-app/app/src/main/assets/app/esm/json-strict/empty.json b/test-app/app/src/main/assets/app/esm/json-strict/empty.json new file mode 100644 index 000000000..8d1c8b69c --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/empty.json @@ -0,0 +1 @@ + diff --git a/test-app/app/src/main/assets/app/esm/json-strict/importer.mjs b/test-app/app/src/main/assets/app/esm/json-strict/importer.mjs new file mode 100644 index 000000000..a5553265a --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/importer.mjs @@ -0,0 +1,3 @@ +export function load(spec) { + return import(spec, { with: { type: "json" } }); +} diff --git a/test-app/app/src/main/assets/app/esm/json-strict/injection.json b/test-app/app/src/main/assets/app/esm/json-strict/injection.json new file mode 100644 index 000000000..6377d3045 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/injection.json @@ -0,0 +1 @@ +{"a": 1};globalThis.__jsonStrictInjected = true \ No newline at end of file diff --git a/test-app/app/src/main/assets/app/esm/json-strict/ok.json b/test-app/app/src/main/assets/app/esm/json-strict/ok.json new file mode 100644 index 000000000..b0529fac2 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/ok.json @@ -0,0 +1 @@ +{"name": "strict"} diff --git a/test-app/app/src/main/assets/app/esm/json-strict/proto.json b/test-app/app/src/main/assets/app/esm/json-strict/proto.json new file mode 100644 index 000000000..eb8557a3d --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/proto.json @@ -0,0 +1 @@ +{"__proto__": {"polluted": true}, "own": 1} \ No newline at end of file diff --git a/test-app/app/src/main/assets/app/esm/json-strict/static-trailing-comma.mjs b/test-app/app/src/main/assets/app/esm/json-strict/static-trailing-comma.mjs new file mode 100644 index 000000000..086614a14 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/static-trailing-comma.mjs @@ -0,0 +1,2 @@ +import data from "./trailing-comma.json" with { type: "json" }; +export default data; diff --git a/test-app/app/src/main/assets/app/esm/json-strict/trailing-comma.json b/test-app/app/src/main/assets/app/esm/json-strict/trailing-comma.json new file mode 100644 index 000000000..90000f7bb --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/json-strict/trailing-comma.json @@ -0,0 +1 @@ +{"a": 1,} \ No newline at end of file diff --git a/test-app/app/src/main/assets/app/mainpage.js b/test-app/app/src/main/assets/app/mainpage.js index d5d7a0933..bfc162718 100644 --- a/test-app/app/src/main/assets/app/mainpage.js +++ b/test-app/app/src/main/assets/app/mainpage.js @@ -15,6 +15,7 @@ TNSGetOutput = function () { __approot = __dirname.substr(0, __dirname.length - 4); var shared = require("./shared"); shared.runRequireTests(); +shared.runImportTests(); shared.runWeakRefTests(); shared.runRuntimeTests(); shared.runWorkerTests(); @@ -36,6 +37,7 @@ require("./tests/testWorkerTerminateDuringRequireMint"); require("./tests/testWorkerTerminateCaughtRequire"); require("./tests/testWorkerTerminateAfterClose"); require("./tests/testWorkerOptions"); +require("./tests/testWorkerEntryNames"); require("./tests/testWorkerResourceLimits"); require("./tests/testWorkerNestedConsole"); require("./tests/testWorkerConcurrentStartup"); @@ -151,6 +153,10 @@ require('./tests/testConcurrentProxyGeneration'); require('./tests/testEsmHttpLoader'); // What import() settles with, per importer kind and specifier shape require('./tests/testDynamicImport'); +// JSON modules: strict JSON.parse, and the SyntaxError they reject with +require('./tests/testJsonModules'); +// import() of CommonJS files and of .js files with either syntax +require('./tests/testImportCommonJs'); // File modules large enough to load off the JS thread require('./tests/testFileModuleLoad'); // Node-API addon surface diff --git a/test-app/app/src/main/assets/app/shared b/test-app/app/src/main/assets/app/shared index 2cb9c23ce..589478f42 160000 --- a/test-app/app/src/main/assets/app/shared +++ b/test-app/app/src/main/assets/app/shared @@ -1 +1 @@ -Subproject commit 2cb9c23ceae51f05e37b170cbbe0bafa4788c9ce +Subproject commit 589478f427ac0e418db1fb542732dff03de7bbda diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js b/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js index cd1d50a10..773bdc1cf 100644 --- a/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js +++ b/test-app/app/src/main/assets/app/tests/benchmarks/jniBenchmarks.js @@ -578,7 +578,10 @@ exports.run = function () { // Yield to the looper between benchmarks so GC and queued work run outside timed rounds. function next() { if (index >= benchmarks.length) { - runContention(); + require("./moduleBenchmarks").run(report, skipped, ROUNDS, SCALE, function (r) { + results.push.apply(results, r); + runContention(); + }); return; } gc(); diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/hub.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/hub.mjs new file mode 100644 index 000000000..fccd019ed --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/hub.mjs @@ -0,0 +1,21 @@ +import { v0 } from "./m0.mjs"; +import { v1 } from "./m1.mjs"; +import { v2 } from "./m2.mjs"; +import { v3 } from "./m3.mjs"; +import { v4 } from "./m4.mjs"; +import { v5 } from "./m5.mjs"; +import { v6 } from "./m6.mjs"; +import { v7 } from "./m7.mjs"; +import { v8 } from "./m8.mjs"; +import { v9 } from "./m9.mjs"; +import { v10 } from "./m10.mjs"; +import { v11 } from "./m11.mjs"; +import { v12 } from "./m12.mjs"; +import { v13 } from "./m13.mjs"; +import { v14 } from "./m14.mjs"; +import { v15 } from "./m15.mjs"; +import { v16 } from "./m16.mjs"; +import { v17 } from "./m17.mjs"; +import { v18 } from "./m18.mjs"; +import { v19 } from "./m19.mjs"; +export const sum = v0 + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10 + v11 + v12 + v13 + v14 + v15 + v16 + v17 + v18 + v19; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/leaf.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/leaf.mjs new file mode 100644 index 000000000..78c8271f3 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/leaf.mjs @@ -0,0 +1 @@ +export const name = "leaf"; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m0.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m0.mjs new file mode 100644 index 000000000..91863e2c3 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m0.mjs @@ -0,0 +1 @@ +export const v0 = 0; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m1.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m1.mjs new file mode 100644 index 000000000..5ba70d27a --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m1.mjs @@ -0,0 +1 @@ +export const v1 = 1; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m10.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m10.mjs new file mode 100644 index 000000000..e2a2da10a --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m10.mjs @@ -0,0 +1 @@ +export const v10 = 10; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m11.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m11.mjs new file mode 100644 index 000000000..a24d73fbc --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m11.mjs @@ -0,0 +1 @@ +export const v11 = 11; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m12.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m12.mjs new file mode 100644 index 000000000..9ce3fc84f --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m12.mjs @@ -0,0 +1 @@ +export const v12 = 12; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m13.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m13.mjs new file mode 100644 index 000000000..5cc3d0780 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m13.mjs @@ -0,0 +1 @@ +export const v13 = 13; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m14.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m14.mjs new file mode 100644 index 000000000..a13d6e455 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m14.mjs @@ -0,0 +1 @@ +export const v14 = 14; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m15.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m15.mjs new file mode 100644 index 000000000..dbf6a7e89 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m15.mjs @@ -0,0 +1 @@ +export const v15 = 15; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m16.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m16.mjs new file mode 100644 index 000000000..246473af7 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m16.mjs @@ -0,0 +1 @@ +export const v16 = 16; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m17.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m17.mjs new file mode 100644 index 000000000..6b80abfdc --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m17.mjs @@ -0,0 +1 @@ +export const v17 = 17; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m18.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m18.mjs new file mode 100644 index 000000000..a5915fa7c --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m18.mjs @@ -0,0 +1 @@ +export const v18 = 18; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m19.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m19.mjs new file mode 100644 index 000000000..466e9905b --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m19.mjs @@ -0,0 +1 @@ +export const v19 = 19; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m2.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m2.mjs new file mode 100644 index 000000000..2a0b24c9e --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m2.mjs @@ -0,0 +1 @@ +export const v2 = 2; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m3.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m3.mjs new file mode 100644 index 000000000..e0490a2ad --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m3.mjs @@ -0,0 +1 @@ +export const v3 = 3; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m4.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m4.mjs new file mode 100644 index 000000000..8d4dfb709 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m4.mjs @@ -0,0 +1 @@ +export const v4 = 4; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m5.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m5.mjs new file mode 100644 index 000000000..9a1e9a198 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m5.mjs @@ -0,0 +1 @@ +export const v5 = 5; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m6.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m6.mjs new file mode 100644 index 000000000..acbc302cb --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m6.mjs @@ -0,0 +1 @@ +export const v6 = 6; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m7.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m7.mjs new file mode 100644 index 000000000..4df18c54a --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m7.mjs @@ -0,0 +1 @@ +export const v7 = 7; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m8.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m8.mjs new file mode 100644 index 000000000..ffb61b521 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m8.mjs @@ -0,0 +1 @@ +export const v8 = 8; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m9.mjs b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m9.mjs new file mode 100644 index 000000000..a5a1adca4 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/modbench/m9.mjs @@ -0,0 +1 @@ +export const v9 = 9; diff --git a/test-app/app/src/main/assets/app/tests/benchmarks/moduleBenchmarks.js b/test-app/app/src/main/assets/app/tests/benchmarks/moduleBenchmarks.js new file mode 100644 index 000000000..68572a8d3 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/benchmarks/moduleBenchmarks.js @@ -0,0 +1,62 @@ +// Module loader rows for the JniBench harness: import() of cached modules +// through each specifier form, and links of a fresh module whose 20 static +// imports are cached. Async, so each row awaits every import. + +function rows(appRoot) { + var leafPath = appRoot + "/tests/benchmarks/modbench/leaf.mjs"; + var hubSeq = 0; + return [ + ["module.import() cached relative", 2000, function () { return import("./modbench/leaf.mjs"); }], + ["module.import() cached bare mapped", 2000, function () { return import("ns-modbench-leaf"); }], + ["module.import() cached app-relative", 2000, function () { return import("~/tests/benchmarks/modbench/leaf.mjs"); }], + ["module.import() cached absolute path", 2000, function () { return import(leafPath); }], + ["module.import() cached file URL", 2000, function () { return import("file://" + leafPath); }], + ["module.import() fresh hub, 20 cached static imports", 200, function () { + return import("./modbench/hub.mjs?i=" + (hubSeq++)); + }] + ]; +} + +exports.run = function (report, skipped, rounds, scale, done) { + // The runtime's own spelling of the app root; getFilesDir() may spell it + // through another mount (/data/user/0 for /data/data). + var appRoot = __dirname.slice(0, __dirname.length - "/tests/benchmarks".length); + require("ns:module").configureLoader({ importMap: { imports: { "ns-modbench-leaf": "~/tests/benchmarks/modbench/leaf.mjs" } } }); + var list = rows(appRoot).filter(function (row) { return !skipped(row[0]); }); + var results = []; + function loop(body, n) { + var i = 0; + return new Promise(function (resolve, reject) { + function step() { + if (i >= n) { resolve(); return; } + i++; + body().then(step, reject); + } + step(); + }); + } + function runRow(index) { + if (index >= list.length) { done(results); return; } + var row = list[index]; + var n = row[1] * scale; + var samples = []; + var r = 0; + loop(row[2], Math.max(200, n >> 2)).then(function round() { + if (r >= rounds) { + results.push(report(row[0], samples, null, n * rounds)); + setTimeout(function () { runRow(index + 1); }, 50); + return; + } + r++; + var start = performance.now(); + return loop(row[2], n).then(function () { + samples.push(((performance.now() - start) * 1e6) / n); + return round(); + }); + }).catch(function (e) { + console.log("JNIBENCH_ERROR " + row[0] + ": " + e); + runRow(index + 1); + }); + } + runRow(0); +}; diff --git a/test-app/app/src/main/assets/app/tests/codeCacheFiles.js b/test-app/app/src/main/assets/app/tests/codeCacheFiles.js new file mode 100644 index 000000000..7f6466b4f --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/codeCacheFiles.js @@ -0,0 +1,144 @@ +// The runtime's on-disk code caches, as the shared core lays them out: +// /v8/<16 hex digits of the FNV-1a 64 hash of the key>, then +// ".mcache" for an ES module or ".cache" for a classic script. The key is the +// source's path relative to the app root, or its absolute path outside it. +// A file is a header (magic "NSCC", version, kind, key length, source size, +// freshness token length, payload length, module format, key, token), then +// V8's payload. The module format is 0 for a classic script, 1 for a CommonJS +// file reached through import (a marker with no payload), 2 for an ES module. +var context = com.tns.NativeScriptApplication.getInstance(); +var dir = String(new java.io.File(context.getCodeCacheDir(), "v8").getAbsolutePath()); +var appRoot = String(context.getFilesDir().getCanonicalPath()) + "/app"; + +var FNV_OFFSET = BigInt("0xcbf29ce484222325"); +var FNV_PRIME = BigInt("0x100000001b3"); +var MASK_64 = (BigInt(1) << BigInt(64)) - BigInt(1); + +function fnv1a64(text) { + var bytes = unescape(encodeURIComponent(text)); + var hash = FNV_OFFSET; + for (var i = 0; i < bytes.length; i++) { + hash = ((hash ^ BigInt(bytes.charCodeAt(i))) * FNV_PRIME) & MASK_64; + } + var hex = hash.toString(16); + while (hex.length < 16) { + hex = "0" + hex; + } + return hex; +} + +function keyFor(path) { + return path.indexOf(appRoot + "/") === 0 ? path.substring(appRoot.length + 1) : path; +} + +// `kind` is "module" or "script". +function fileFor(path, kind) { + return dir + "/" + fnv1a64(keyFor(path)) + (kind === "script" ? ".cache" : ".mcache"); +} + +// What platform::Stat reports as the source's freshness token: its mtime with +// nanoseconds. +function sourceToken(path) { + var mtime = android.system.Os.stat(path).st_mtim; + var nanos = String(mtime.tv_nsec); + while (nanos.length < 9) { + nanos = "0" + nanos; + } + return String(mtime.tv_sec) + "." + nanos; +} + +function readBytes(file) { + var f = new java.io.File(file); + return f.exists() ? java.nio.file.Files.readAllBytes(f.toPath()) : null; +} + +// The cache file's header, or null when there is no file or it is not a cache. +function readHeader(file) { + var bytes = readBytes(file); + if (bytes === null || bytes.length < 36) { + return null; + } + var u8 = function (i) { + return bytes[i] & 0xff; + }; + var u32 = function (i) { + return (u8(i) | (u8(i + 1) << 8) | (u8(i + 2) << 16) | (u8(i + 3) << 24)) >>> 0; + }; + var text = function (start, length) { + var out = ""; + for (var i = start; i < start + length; i++) { + out += String.fromCharCode(u8(i)); + } + return decodeURIComponent(escape(out)); + }; + if (text(0, 4) !== "NSCC") { + return null; + } + var keyLength = u32(12); + var tokenLength = u32(24); + var payloadStart = 36 + keyLength + tokenLength; + var zeroPayload = true; + for (var i = payloadStart; i < bytes.length && zeroPayload; i++) { + zeroPayload = bytes[i] === 0; + } + return { + version: u32(4), + format: u32(32), + key: text(36, keyLength), + sourceSize: u32(16) + u32(20) * 4294967296, + token: text(36 + keyLength, tokenLength), + payloadStart: payloadStart, + payloadLength: u32(28), + fileLength: bytes.length, + zeroPayload: zeroPayload + }; +} + +// Whether `file` is a cache for the source at `path` as it is now. +function isFresh(file, path) { + var header = readHeader(file); + return header !== null && header.key === keyFor(path) && + header.sourceSize === new java.io.File(path).length() && + header.token === sourceToken(path) && + header.fileLength === header.payloadStart + header.payloadLength; +} + +// Overwrites the payload with zeros and keeps the header, so the cache still +// reads as fresh and V8 rejects it. +function zeroPayload(file) { + var header = readHeader(file); + var bytes = readBytes(file); + for (var i = header.payloadStart; i < bytes.length; i++) { + bytes[i] = 0; + } + var out = new java.io.FileOutputStream(file); + try { + out.write(bytes); + } finally { + out.close(); + } +} + +// Names in the cache directory that start with `file`'s name and a dot: the +// writer's temporaries. +function temporariesOf(file) { + var name = file.substring(file.lastIndexOf("/") + 1) + "."; + var names = new java.io.File(dir).list(); + var found = []; + for (var i = 0; names && i < names.length; i++) { + if (String(names[i]).indexOf(name) === 0) { + found.push(String(names[i])); + } + } + return found; +} + +module.exports = { + dir: dir, + fileFor: fileFor, + sourceToken: sourceToken, + readHeader: readHeader, + isFresh: isFresh, + zeroPayload: zeroPayload, + temporariesOf: temporariesOf +}; diff --git a/test-app/app/src/main/assets/app/tests/esmEntryNeverSettlesWorker.mjs b/test-app/app/src/main/assets/app/tests/esmEntryNeverSettlesWorker.mjs index 4ad5744ff..2658d7579 100644 --- a/test-app/app/src/main/assets/app/tests/esmEntryNeverSettlesWorker.mjs +++ b/test-app/app/src/main/assets/app/tests/esmEntryNeverSettlesWorker.mjs @@ -1,6 +1,6 @@ // An ES module worker entry that never finishes evaluating. The parent is told -// the entry body started before the park, so its terminate() lands inside the -// entry's bounded evaluation pump rather than after it. +// the entry body started before the park, so its terminate() lands while the +// entry's evaluation is still pending. postMessage("never-settles:started"); await new Promise(function () {}); diff --git a/test-app/app/src/main/assets/app/tests/esmEntryResolvedWorker.mjs b/test-app/app/src/main/assets/app/tests/esmEntryResolvedWorker.mjs index 7e1450cc2..10cf4a563 100644 --- a/test-app/app/src/main/assets/app/tests/esmEntryResolvedWorker.mjs +++ b/test-app/app/src/main/assets/app/tests/esmEntryResolvedWorker.mjs @@ -1,7 +1,7 @@ // Reached through an extension-less worker specifier: no `.js` sibling exists, // so only this file can answer. The top-level await parks on a NON-nestable -// foreground task, which the in-place yield window cannot settle, so a message -// posted at construction has to wait on the settle-gated queue. +// foreground task, so a message posted at construction has to wait on the +// settle-gated queue. const i32 = new Int32Array(new SharedArrayBuffer(4)); const wait = Atomics.waitAsync(i32, 0, 0); Atomics.notify(i32, 0); diff --git a/test-app/app/src/main/assets/app/tests/esmEntryTimerWorker.mjs b/test-app/app/src/main/assets/app/tests/esmEntryTimerWorker.mjs index 3a220c043..5e3de812a 100644 --- a/test-app/app/src/main/assets/app/tests/esmEntryTimerWorker.mjs +++ b/test-app/app/src/main/assets/app/tests/esmEntryTimerWorker.mjs @@ -1,10 +1,7 @@ -// An ES module worker entry whose top-level await parks on a JS timer: the -// resolution rides the worker looper's ordered lane, which the entry pump -// drains directly, so the entry settles inside the yield window. The runtime -// primitive is used directly: the test app wires global setTimeout on the -// main thread only, and as a Java-Handler polyfill the pump could not -// dispatch it anyway — this fixture pins the runtime's own ordered-lane -// timers. +// An ES module worker entry whose top-level await parks on a JS timer, which +// fires from the worker's own event loop after the entry came back pending. +// The runtime primitive is used directly: this fixture pins the runtime's own +// ordered-lane timers. const settled = await new Promise(function (resolve) { __ns__setTimeout(function () { resolve("ok"); }, 10); }); diff --git a/test-app/app/src/main/assets/app/tests/esmEntryTlaWorker.mjs b/test-app/app/src/main/assets/app/tests/esmEntryTlaWorker.mjs index 2205f505f..74bab6cb6 100644 --- a/test-app/app/src/main/assets/app/tests/esmEntryTlaWorker.mjs +++ b/test-app/app/src/main/assets/app/tests/esmEntryTlaWorker.mjs @@ -1,6 +1,6 @@ // An ES module worker entry with top-level await, parked on a NON-nestable -// foreground task: the in-place yield window cannot settle it, so the entry -// finishes from the real event loop and the message queue enables on settle. +// foreground task: the entry finishes from the worker's event loop and the +// message queue enables on settle. const i32 = new Int32Array(new SharedArrayBuffer(4)); const wait = Atomics.waitAsync(i32, 0, 0); Atomics.notify(i32, 0); diff --git a/test-app/app/src/main/assets/app/tests/exceptionHandlingTests.js b/test-app/app/src/main/assets/app/tests/exceptionHandlingTests.js index 0c5f8cd9c..12452b8ba 100644 --- a/test-app/app/src/main/assets/app/tests/exceptionHandlingTests.js +++ b/test-app/app/src/main/assets/app/tests/exceptionHandlingTests.js @@ -306,17 +306,13 @@ describe("Tests exception handling ", function () { }); it("should successfully catch syntax errors", function () { - var exceptionCaught = false; - var errMsg; + var error; try { require("./syntaxErrors.js"); } catch (e) { - exceptionCaught = true; - errMsg = e.fullMessage; + error = e; } - expect(exceptionCaught).toBe(true); - expect(errMsg).toContain("Cannot compile /data/data/com.tns.testapplication/files/app/tests/syntaxErrors.js"); - expect(errMsg).toContain("SyntaxError: Unexpected token 'class'"); - expect(errMsg).toContain("File: (file:///data/data/com.tns.testapplication/files/app/tests/syntaxErrors.js:3:4)"); + expect(error instanceof SyntaxError).toBe(true); + expect(error.message).toBe("Unexpected token 'class'"); }); }); \ No newline at end of file diff --git a/test-app/app/src/main/assets/app/tests/importOnCloseWorker.js b/test-app/app/src/main/assets/app/tests/importOnCloseWorker.js new file mode 100644 index 000000000..7a2060302 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/importOnCloseWorker.js @@ -0,0 +1,16 @@ +// Issues an import() of every specifier it is sent, reports "issued", and, +// when told to, closes itself in the same task, so its runtime tears down with +// those imports still loading. +onmessage = function (msg) { + var specs = msg.data.specs; + for (var i = 0; i < specs.length; i++) { + import(specs[i]).catch(function () {}); + } + postMessage("issued"); + if (msg.data.close) { + close(); + for (var j = 0; j < specs.length; j++) { + import(specs[j]).catch(function () {}); + } + } +}; diff --git a/test-app/app/src/main/assets/app/tests/prebuiltExtendLineOneMinified.js b/test-app/app/src/main/assets/app/tests/prebuiltExtendLineOneMinified.js new file mode 100644 index 000000000..47fa24a2a --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/prebuiltExtendLineOneMinified.js @@ -0,0 +1 @@ +var first = java.lang.Object.extend({ toString: function () { return "first"; } }); exports.First = first; exports.Second = java.lang.Object.extend({ toString: function () { return "second"; } }); diff --git a/test-app/app/src/main/assets/app/tests/requireExceptionTests.js b/test-app/app/src/main/assets/app/tests/requireExceptionTests.js index 5b28cbd8e..a2e8457bf 100644 --- a/test-app/app/src/main/assets/app/tests/requireExceptionTests.js +++ b/test-app/app/src/main/assets/app/tests/requireExceptionTests.js @@ -52,99 +52,44 @@ describe("Tests require exceptions ", function () { //expect(partialMessage).toBe(thrownException); }); - it("when requiring a relative (../) non existing module and error should be thrown", function () { - - var exceptionCaught = false; - var partialMessage = "Error: com.tns.NativeScriptException: Failed to find module: \"../aaa.js\", relative to: app/tests/"; - var thrownException; - try - { - require("../aaa.js"); - } - catch(e) - { - thrownException = e.toString().substr(0, partialMessage.length); - exceptionCaught = true; + var appRoot = __dirname.replace(/\/tests$/, ""); + + // The core's text: "Cannot find module '' (tried )". + function expectModuleNotFound(specifier, triedPrefix) { + var error; + try { + require(specifier); + } catch (e) { + error = e; } - expect(exceptionCaught).toBe(true); - expect(partialMessage).toBe(thrownException); + expect(error instanceof Error).toBe(true); + expect(error.code).toBe("MODULE_NOT_FOUND"); + expect(Array.isArray(error.requireStack) && error.requireStack.length).toBe(0); + var prefix = "Cannot find module '" + specifier + "' (tried " + triedPrefix; + expect(error.message.substr(0, prefix.length)).toBe(prefix); + } + + it("when requiring a relative (../) non existing module and error should be thrown", function () { + expectModuleNotFound("../aaa.js", appRoot + "/aaa.js"); }); - - it("when requiring a relative (~/) non existing module and error should be thrown", function () { - - var exceptionCaught = false; - try - { - require("~/a.js"); - } - catch(e) - { - exceptionCaught = true; - // Just verify the exception contains the expected error type - expect(e.toString()).toContain("Failed to find module"); - } - expect(exceptionCaught).toBe(true); + it("when requiring a relative (~/) non existing module and error should be thrown", function () { + expectModuleNotFound("~/a.js", appRoot + "/a.js"); }); - - it("when requiring a relative (./) non existing module and error should be thrown", function () { - - var exceptionCaught = false; - var partialMessage = "Error: com.tns.NativeScriptException: Failed to find module: \"./a.js\", relative to: app/tests"; - var thrownException; - try - { - require("./a.js"); - } - catch(e) - { - thrownException = e.toString().substr(0, partialMessage.length); - exceptionCaught = true; - } - expect(exceptionCaught).toBe(true); - expect(partialMessage).toBe(thrownException); + it("when requiring a relative (./) non existing module and error should be thrown", function () { + expectModuleNotFound("./a.js", __dirname + "/a.js"); }); - - it("when requiring a relative non existing tns_module an error should be thrown", function () { - - var exceptionCaught = false; - var partialMessage = "Error: com.tns.NativeScriptException: Failed to find module: \"a.js\", relative to: app/tns_modules/"; - var thrownException; - try - { - require("a.js"); - } - catch(e) - { - thrownException = e.toString().substr(0, partialMessage.length); - exceptionCaught = true; - } - expect(exceptionCaught).toBe(true); - expect(partialMessage).toBe(thrownException); + it("when requiring a relative non existing tns_module an error should be thrown", function () { + expectModuleNotFound("a.js", appRoot + "/tns_modules/tns-core-modules/a.js"); }); - - it("when requiring a relative non existing tns_module from folder an error should be thrown", function () { - - var exceptionCaught = false; - var partialMessage = "Error: com.tns.NativeScriptException: Failed to find module: \"a/a.js\", relative to: app/tns_modules/"; - var thrownException; - try - { - require("a/a.js"); - } - catch(e) - { - thrownException = e.toString().substr(0, partialMessage.length); - exceptionCaught = true; - } - expect(exceptionCaught).toBe(true); - expect(partialMessage).toBe(thrownException); + it("when requiring a relative non existing tns_module from folder an error should be thrown", function () { + expectModuleNotFound("a/a.js", appRoot + "/tns_modules/tns-core-modules/a/a.js"); }); - + it("TestRequire", function () { __log("TEST: TestRequire"); @@ -161,4 +106,28 @@ describe("Tests require exceptions ", function () { expect(exceptionCaught).toBe(false); }); + + it("throws when a script that exists cannot be read", function () { + var name = "unreadable-" + Date.now() + ".js"; + var path = __dirname + "/" + name; + var file = new java.io.File(path); + var writer = new java.io.FileWriter(file); + try { + writer.write("module.exports = { loaded: true };"); + } finally { + writer.close(); + } + file.setReadable(false, false); + var message; + try { + require(path); + message = "loaded"; + } catch (e) { + message = String(e.message || e); + } finally { + file.delete(); + } + expect(message).toContain("Cannot read module "); + expect(message).toContain(name); + }); }); \ No newline at end of file diff --git a/test-app/app/src/main/assets/app/tests/testCreateRequire.js b/test-app/app/src/main/assets/app/tests/testCreateRequire.js index 832a97ab9..a4a56fcf2 100644 --- a/test-app/app/src/main/assets/app/tests/testCreateRequire.js +++ b/test-app/app/src/main/assets/app/tests/testCreateRequire.js @@ -58,13 +58,15 @@ describe("createRequire", function () { }); }); - // Absent rather than present-but-throwing, so a feature check that - // guards on them takes the fallback path. - it("mints a require without resolve, cache or main", function () { + // cache is absent rather than present-but-throwing, so a feature check + // that guards on it takes the fallback path. + it("mints a require with resolve and main, without cache", function () { var req = nsModule.createRequire(fixtureDir + "/anything.js"); - expect(req.resolve).toBeUndefined(); + expect(typeof req.resolve).toBe("function"); + expect(req.resolve("./target.js")).toBe(fixtureDir + "/target.js"); + expect(req.main.id).toBe("."); + expect(req.main.filename).toBe(appRoot + "/boot.js"); expect(req.cache).toBeUndefined(); - expect(req.main).toBeUndefined(); }); }); @@ -347,6 +349,91 @@ describe("createRequire", function () { expect(messageOf(function () { req("./tla-foreground-task.mjs"); })) .toContain("the module graph contains top-level await"); }); + + it("waits for a module whose top-level await is still running", function (done) { + import("~/esm/createrequire/tla-still-running.mjs").catch(function () {}); + + function whenStarted() { + if (!globalThis.__nsTlaStillRunningStarted) { + __ns__setTimeout(whenStarted, 5); + return; + } + onFreshTask(function () { + var req = nsModule.createPumpingRequire(fixtureDir + "/anything.js", + { pumpRunLoop: true }); + var result = ""; + try { + result = String(req("./tla-still-running.mjs").value); + } catch (e) { + result = "threw: " + ((e && e.message) || e); + } + expect(result).toBe("settled"); + done(); + }); + } + whenStarted(); + }); + + it("throws ERR_REQUIRE_CYCLE_MODULE for a module still evaluating up the stack", + function (done) { + import("~/esm/createrequire/cycle-root.mjs").then(function (ns) { + expect(ns.outcome).toContain("ERR_REQUIRE_CYCLE_MODULE: Cannot require() ES Module "); + expect(ns.outcome).toContain("cycle-root.mjs in a cycle."); + done(); + }).catch(function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }); + }); + }); + + describe("module identity", function () { + function evaluations() { + return globalThis.__nsIdentityEvaluations || {}; + } + + it("shares one module between import() and a later require()", function (done) { + import("~/esm/createrequire/identity-import-first.mjs").then(function (ns) { + var req = nsModule.createRequire(fixtureDir + "/anything.js"); + expect(req("./identity-import-first.mjs").token).toBe(ns.token); + expect(evaluations().importFirst).toBe(1); + done(); + }).catch(function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }); + }); + + it("shares one module between require() and a later import()", function (done) { + var req = nsModule.createRequire(fixtureDir + "/anything.js"); + var required = req("./identity-require-first.mjs"); + import("~/esm/createrequire/identity-require-first.mjs").then(function (ns) { + expect(ns.token).toBe(required.token); + expect(evaluations().requireFirst).toBe(1); + done(); + }).catch(function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }); + }); + + // The Context names the data directory /data/user//; the app + // root is spelled under its canonical /data/data/. + it("keys a file reached through the data directory's other spelling as one module", function () { + var dataDir = String(com.tns.NativeScriptApplication.getInstance().getApplicationInfo().dataDir); + var canonical = String(new java.io.File(dataDir).getCanonicalPath()); + if (dataDir === canonical || fixtureDir.indexOf(canonical + "/") !== 0) { + pending("the data directory has one spelling on this device"); + return; + } + var aliasDir = dataDir + fixtureDir.substr(canonical.length); + var req = nsModule.createRequire(fixtureDir + "/anything.js"); + + var viaAlias = req(aliasDir + "/target.js"); + + expect(viaAlias).toBe(req(fixtureDir + "/target.js")); + expect(req.resolve(aliasDir + "/target.js")).toBe(fixtureDir + "/target.js"); + }); }); }); diff --git a/test-app/app/src/main/assets/app/tests/testDynamicImport.js b/test-app/app/src/main/assets/app/tests/testDynamicImport.js index 24c660077..c71240628 100644 --- a/test-app/app/src/main/assets/app/tests/testDynamicImport.js +++ b/test-app/app/src/main/assets/app/tests/testDynamicImport.js @@ -11,6 +11,7 @@ describe("import() resolution table", function () { var appRoot = __dirname.slice(0, __dirname.length - "/tests".length); var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); var blobUrl = null; + var blobImporterUrl = null; // Loopback fetches can outrun the 5s default on a cold emulator. var originalTimeout; @@ -80,6 +81,9 @@ describe("import() resolution table", function () { globalThis.__importPinSpec = spec; return (0, eval)("import(globalThis.__importPinSpec)"); }, + blob: function (spec) { + return import(blobImporterUrl).then(function (m) { return m.load(spec); }); + }, http: function (spec) { return import(origin + "/esm/resolve/import-pin/importer.mjs").then(function (m) { return m.load(spec); @@ -95,6 +99,8 @@ describe("import() resolution table", function () { "ns-pin-relative-target": "./leaf.mjs", "ns-pin-chain": "ns-pin-mapped", "ns-pin-dir/": "~/esm/import-pin/dir/", + "ns-pin-builtin": "node:url", + "404": "~/esm/import-pin/leaf.mjs", }, }, }); @@ -110,6 +116,9 @@ describe("import() resolution table", function () { }; blobUrl = URL.createObjectURL(new Blob(["export const name = 'blob';\n"], { type: "text/javascript" }), { ext: ".mjs" }); + blobImporterUrl = URL.createObjectURL( + new Blob(["export function load(spec) { return import(spec); }\n"], + { type: "text/javascript" }), { ext: ".mjs" }); if (typeof previousBlob === "undefined") { delete globalThis.Blob; } else { @@ -119,6 +128,7 @@ describe("import() resolution table", function () { afterAll(function () { URL.revokeObjectURL(blobUrl); + URL.revokeObjectURL(blobImporterUrl); nsModule.configureLoader({ importMap: { imports: {} } }); }); @@ -137,12 +147,29 @@ describe("import() resolution table", function () { ["esm", "ns-pin-chain", "rejected:Error:Cannot find module 'ns-pin-mapped' (tried /ns-pin-mapped)"], ["esm", "ns-pin-dir/index.mjs", "ok:dir-index"], ["esm", "ns-pin-unmapped", "rejected:Error:Cannot find module 'ns-pin-unmapped' (tried /ns-pin-unmapped)"], + ["esm", "ns-pin-builtin", "ok:keys=URL,URLSearchParams,default"], + ["esm", "404", "ok:leaf"], + ["esm", "./leaf.mjs\u0000x", "rejected:Error:Cannot resolve module specifier \"./leaf.mjs\\u0000x\": a module specifier must not contain U+0000"], ["esm", "~/esm/import-pin/leaf.mjs", "ok:leaf"], ["esm", "/esm/import-pin/leaf.mjs", "ok:leaf"], ["esm", "/app/esm/import-pin/leaf.mjs", "ok:leaf"], ["esm", function () { return appRoot + "/esm/import-pin/leaf.mjs"; }, "ok:leaf"], ["esm", "file:///app/esm/import-pin/leaf.mjs", "ok:leaf"], ["esm", function () { return "file://" + appRoot + "/esm/import-pin/leaf.mjs"; }, "ok:leaf"], + ["esm", "file://localhost/app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "file:///app/esm/import-pin/le%61f.mjs", "ok:leaf"], + ["esm", "app:///esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "app://localhost/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "app:esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module 'app:esm/import-pin/leaf.mjs' (tried app:esm/import-pin/leaf.mjs)"], + ["esm", "FILE:///app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "file:/app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "file:///app/esm/import-pin/leaf.mjs%00", "rejected:Error:Cannot find module 'file:///app/esm/import-pin/leaf.mjs%00' (tried file:///app/esm/import-pin/leaf.mjs%00)"], + ["esm", "~/../../esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "/../../esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "esm/../../../esm/import-pin/leaf.mjs", "ok:leaf"], + ["esm", "../../../../../../../../../../esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module '../../../../../../../../../../esm/import-pin/leaf.mjs' (tried /esm/import-pin/leaf.mjs)"], + ["esm", "file://host/app/esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module 'file://host/app/esm/import-pin/leaf.mjs' (tried file://host/app/esm/import-pin/leaf.mjs)"], + ["esm", "file:///app/esm/import-pin%2Fleaf.mjs", "rejected:Error:Cannot find module 'file:///app/esm/import-pin%2Fleaf.mjs' (tried file:///app/esm/import-pin%2Fleaf.mjs)"], ["esm", "./data.json", "ok:default.name=json"], ["esm", "ns:module", "ok:createRequire=function"], ["esm", "node:url", "ok:keys=URL,URLSearchParams,default"], @@ -160,6 +187,7 @@ describe("import() resolution table", function () { ["esm", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], ["esm", "./tla.mjs", "ok:tla"], ["esm", "", "rejected:Error:Cannot find module '' (tried )"], + ["esm", "?v=1", "rejected:Error:Cannot find module '?v=1' (tried )"], ["esmEval", "./leaf.mjs", "ok:leaf"], @@ -181,6 +209,7 @@ describe("import() resolution table", function () { ["cjs", function () { return blobUrl + "#f"; }, "ok:blob"], ["cjs", "./missing.mjs", "rejected:Error:Cannot find module './missing.mjs' (tried /esm/import-pin/missing.mjs)"], ["cjs", "./throws.mjs", "rejected:TypeError:import-pin evaluation error"], + ["cjs", "./leaf.mjs\u0000x", "rejected:Error:Cannot resolve module specifier \"./leaf.mjs\\u0000x\": a module specifier must not contain U+0000"], ["newFunction", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], ["newFunction", "./esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module './esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], @@ -196,6 +225,10 @@ describe("import() resolution table", function () { ["indirectEval", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried /tests/leaf.mjs)"], ["indirectEval", "./esm/import-pin/leaf.mjs", "rejected:Error:Cannot find module './esm/import-pin/leaf.mjs' (tried /tests/esm/import-pin/leaf.mjs)"], ["indirectEval", "~/esm/import-pin/leaf.mjs", "ok:leaf"], + + ["blob", "./leaf.mjs", "rejected:Error:Cannot find module './leaf.mjs' (tried )"], + ["blob", "~/esm/import-pin/leaf.mjs", "ok:leaf"], + ["blob", "./leaf.mjs\u0000x", "rejected:Error:Cannot resolve module specifier \"./leaf.mjs\\u0000x\": a module specifier must not contain U+0000"], ]; var httpRows = [ @@ -207,6 +240,7 @@ describe("import() resolution table", function () { ["http", "ns-pin-unmapped", "rejected:Error:Cannot resolve module specifier \"ns-pin-unmapped\" imported from /esm/resolve/import-pin/importer.mjs: it is not in the import map (bare specifiers from an HTTP module must be mapped)."], ["http", "~/esm/import-pin/leaf.mjs", "rejected:Error:Cannot resolve module specifier \"~/esm/import-pin/leaf.mjs\" imported from /esm/resolve/import-pin/importer.mjs: app-relative \"~/\" paths are not available to modules loaded over HTTP (use a file:// URL, an import-map entry, or createRequire)."], ["http", "file:///app/esm/import-pin/leaf.mjs", "ok:leaf"], + ["http", "app:///esm/import-pin/leaf.mjs", "ok:leaf"], ["http", "file:///app/esm/import-pin/dir", "ok:dir-index"], ["http", "file:///app/esm/import-pin/data.json", "ok:default.name=json"], ["http", "file:///app/esm/import-pin/missing.mjs", "rejected:Error:Cannot find module 'file:///app/esm/import-pin/missing.mjs' (tried /esm/import-pin/missing.mjs)"], @@ -385,6 +419,21 @@ describe("file module instances per query", function () { }).catch(fail(done)); }); + it("invalidates through the file:///app/ and file:///android_asset/app/ spellings", function (done) { + var specs = ["./counted.mjs?v=virtual-app", "./counted.mjs?v=virtual-asset"]; + var virtualUrls = ["file:///app/esm/query-identity/counted.mjs?v=virtual-app", + "file:///android_asset/app/esm/query-identity/counted.mjs?v=virtual-asset"]; + Promise.all(specs.map(load)).then(function (first) { + nsModule.invalidateModules(virtualUrls); + return Promise.all(specs.map(load)).then(function (second) { + expect([first[0] === second[0], first[1] === second[1]]).toEqual([false, false]); + expect([evaluations(urlBase + "counted.mjs?v=virtual-app"), + evaluations(urlBase + "counted.mjs?v=virtual-asset")]).toEqual([2, 2]); + done(); + }); + }).catch(fail(done)); + }); + describe("inside a module imported with a query containing '/', '..' and '://'", function () { var query = "?a=/../../y&u=http://h/z"; var probe; diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 803a85339..f0cafb77f 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -481,6 +481,18 @@ describe("HTTP ESM Loader", function () { }); }); + // A served module has no directory on the device. + it("gives a served module no import.meta.dirname", function (done) { + var url = origin + "/esm/resolve/meta/x.mjs"; + import(url).then(function (ns) { + expect(ns.url).toBe(url); + expect(ns.hasDirname).toBe(false); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("imports one module for every spelling of its URL from a static import", function (done) { function staticImporter(spec) { return import(origin + "/esm/resolve/static.mjs?spec=" + encodeURIComponent(spec)); @@ -544,8 +556,7 @@ describe("HTTP ESM Loader", function () { var scopes = {}; scopes[base + "/x/../dots/"] = { "ns-scope-norm": base + "/target.mjs?k=dots" }; scopes[base + "/m\u00f6dir/"] = { "ns-scope-norm": base + "/target.mjs?k=nonascii" }; - // No trailing slash: still a plain prefix, here inside a segment. - scopes[base + "/pla"] = { "ns-scope-norm": base + "/target.mjs?k=plain" }; + scopes[base + "/plain/importer.mjs"] = { "ns-scope-norm": base + "/target.mjs?k=plain" }; scopes[origin] = { "ns-scope-norm-origin": base + "/target.mjs?k=origin" }; nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); function load(dir, spec) { @@ -567,6 +578,32 @@ describe("HTTP ESM Loader", function () { }); }); + it("matches a scope key without a trailing '/' to that exact URL only", function (done) { + var base = origin + "/esm/resolve/scope-exact"; + var scopes = {}; + scopes[base + "/pla"] = { "ns-scope-exact": base + "/target.mjs?k=partial" }; + scopes[base + "/plain"] = { "ns-scope-exact": base + "/target.mjs?k=dir" }; + scopes[base + "/exact/importer.mjs"] = { "ns-scope-exact": base + "/target.mjs?k=exact" }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + function load(dir) { + return importer(origin, "scope-exact/" + dir).then(function (mod) { + return mod.load("ns-scope-exact").then(function (m) { + return m.query; + }, function (error) { + return String((error && error.message) || error); + }); + }); + } + Promise.all([load("plain"), load("exact"), load("exact/nested")]).then(function (r) { + expect(r[0]).toContain("it is not in the import map"); + expect(r[1]).toBe("k=exact"); + expect(r[2]).toContain("it is not in the import map"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("does not widen an http(s) scope whose key ends in a dot segment", function (done) { var base = origin + "/esm/resolve/scope-dot-end"; var scopes = {}; diff --git a/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js b/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js index 73b43bd89..422cd9f96 100644 --- a/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js +++ b/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js @@ -18,6 +18,7 @@ describe("Large file modules", function () { // Debuggable builds are the development flavor: no code caches. var isDebugBuild = typeof require("ns:module").canonicalizeHttpUrlKey === "function"; var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); + var codeCaches = require("./codeCacheFiles"); var originalTimeout; function writeModule(name, body) { @@ -100,21 +101,13 @@ describe("Large file modules", function () { return name + String((error && error.message) || error); } - function modifiedSeconds(path) { - var file = new java.io.File(path); - return file.exists() ? Math.floor(file.lastModified() / 1000) : -1; - } - - // Resolves once a code cache stamped with `path`'s current modification - // time exists, the one the runtime treats as fresh. + // Resolves once a code cache for `path` as it is now exists, the one the + // runtime treats as fresh. function freshCodeCache(path) { var deadline = Date.now() + 5000; return new Promise(function (resolve, reject) { (function poll() { - var source = modifiedSeconds(path); - if (codeCacheEntries(path).some(function (entry) { - return modifiedSeconds(entry) === source; - })) { + if (codeCaches.isFresh(codeCacheFile(path), path)) { resolve(); } else if (Date.now() > deadline) { reject(new Error("no fresh code cache for " + path)); @@ -165,9 +158,9 @@ describe("Large file modules", function () { }); } - // `path`'s module code cache, which the runtime keeps beside the source. - function codeCacheEntries(path) { - return new java.io.File(path + ".mcache").exists() ? [path + ".mcache"] : []; + // `path`'s module code cache. + function codeCacheFile(path) { + return codeCaches.fileFor(path, "module"); } beforeAll(function () { @@ -558,22 +551,23 @@ describe("Large file modules", function () { var firstSource; import(spec + "?v=1").then(function (mod) { expectWholeBody(mod, "file-edited-1", CONSUME_LINES); - firstSource = modifiedSeconds(module.path); + firstSource = codeCaches.sourceToken(module.path); return isDebugBuild ? undefined : freshCodeCache(module.path); }).then(function () { var edited = bigModule("file-edited-2", CONSUME_LINES + 7).body; expect(edited.length).toBeGreaterThan(CACHE_CONSUME_THRESHOLD); writeModule("edited", edited); - // Freshness is compared in whole seconds, so an edit within the - // first source's second would leave the old cache looking fresh. - if (modifiedSeconds(module.path) === firstSource) { - new java.io.File(module.path).setLastModified((firstSource + 2) * 1000); + // On a file system with coarse timestamps the edit could keep the + // first source's mtime, and with it the old cache's freshness token. + if (codeCaches.sourceToken(module.path) === firstSource) { + var source = new java.io.File(module.path); + source.setLastModified(source.lastModified() + 2000); } if (!isDebugBuild) { - var stale = codeCacheEntries(module.path); - expect(stale.length).toBe(1); - expect(modifiedSeconds(stale[0])).toBe(firstSource); - expect(modifiedSeconds(module.path)).not.toBe(firstSource); + var stale = codeCaches.readHeader(codeCacheFile(module.path)); + expect(stale !== null).toBe(true); + expect(stale && stale.token).toBe(firstSource); + expect(codeCaches.sourceToken(module.path)).not.toBe(firstSource); } return import(spec + "?v=2"); }).then(function (mod) { @@ -593,12 +587,10 @@ describe("Large file modules", function () { expectWholeBody(mod, "file-cache-probe", LINES); var deadline = Date.now() + 5000; function poll() { - var entries = codeCacheEntries(module.path); - if (entries.length > 0 || Date.now() > deadline) { - expect(entries.length).toBe(isDebugBuild ? 0 : 1); - for (var i = 0; i < entries.length; i++) { - new java.io.File(entries[i]).delete(); - } + var cache = new java.io.File(codeCacheFile(module.path)); + if (cache.exists() || Date.now() > deadline) { + expect(cache.exists()).toBe(!isDebugBuild); + cache.delete(); done(); return; } @@ -616,31 +608,25 @@ describe("Large file modules", function () { } var module = writeBig("corrupt-cache", "file-corrupt-cache", CONSUME_LINES); expect(module.body.length).toBeGreaterThan(CACHE_CONSUME_THRESHOLD); - var cachePath = module.path + ".mcache"; - var garbage = "not a code cache"; + var cachePath = codeCacheFile(module.path); import(module.spec + "?v=1").then(function (mod) { expectWholeBody(mod, "file-corrupt-cache", CONSUME_LINES); return freshCodeCache(module.path); }).then(function () { - var cacheFile = new java.io.File(cachePath); - var stamp = cacheFile.lastModified(); - var out = new java.io.FileOutputStream(cacheFile); - try { - out.write(new java.lang.String(garbage).getBytes("UTF-8")); - } finally { - out.close(); - } - cacheFile.setLastModified(stamp); - // Still looks fresh, so the next load consumes it. - expect(modifiedSeconds(cachePath)).toBe(modifiedSeconds(module.path)); + // The header still matches, so the next load hands the zeroed + // payload to V8, which rejects it. + codeCaches.zeroPayload(cachePath); + expect(codeCaches.isFresh(cachePath, module.path)).toBe(true); + expect(codeCaches.readHeader(cachePath).zeroPayload).toBe(true); return import(module.spec + "?v=2"); }).then(function (mod) { expectWholeBody(mod, "file-corrupt-cache", CONSUME_LINES, 2); var deadline = Date.now() + 5000; return new Promise(function (resolve, reject) { (function poll() { - if (new java.io.File(cachePath).length() > garbage.length && - modifiedSeconds(cachePath) === modifiedSeconds(module.path)) { + var header = codeCaches.readHeader(cachePath); + if (header !== null && !header.zeroPayload && + codeCaches.isFresh(cachePath, module.path)) { resolve(); } else if (Date.now() > deadline) { reject(new Error("the corrupt cache was not rewritten")); @@ -740,4 +726,55 @@ describe("Large file modules", function () { } sweep(0); }, 60000); + + // Half the workers close themselves and import again in the same task; + // the others are terminated as soon as their imports are issued. Either + // way the runtime tears down with file and HTTP loads in flight. + it("survives import()s in flight and issued while a worker closes", function (done) { + var WORKERS = 6; + var large = writeBig("closing", "file-closing", 20000).spec; + var slowHttp = origin + "/esm/slow/leaf.mjs?k=closing&delayMs=1500"; + var remaining = WORKERS; + + function importOnMain() { + var module = writeBig("after-closing", "file-after-closing", LINES); + import(module.spec).then(function (mod) { + expectWholeBody(mod, "file-after-closing", LINES); + done(); + }).catch(failWith(done)); + } + + function finished() { + if (--remaining === 0) { + // Past the slow fetch, so its completion reaches each + // torn-down loader first. + setTimeout(importOnMain, 2000); + } + } + + for (var i = 0; i < WORKERS; i++) { + (function (worker, close) { + var ended = false; + worker.onmessage = function (msg) { + if (ended || msg.data !== "issued") { + return; + } + ended = true; + if (!close) { + worker.terminate(); + } + finished(); + }; + worker.onerror = function (error) { + fail("worker errored: " + formatError(error)); + if (!ended) { + ended = true; + worker.terminate(); + finished(); + } + }; + worker.postMessage({ specs: [large, slowHttp], close: close }); + })(new Worker("./importOnCloseWorker.js"), i % 2 === 0); + } + }, 60000); }); diff --git a/test-app/app/src/main/assets/app/tests/testImportCommonJs.js b/test-app/app/src/main/assets/app/tests/testImportCommonJs.js new file mode 100644 index 000000000..f7e6a7695 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testImportCommonJs.js @@ -0,0 +1,251 @@ +// import() of files that are not .mjs. A .js file is an ES module when it has +// module syntax and CommonJS otherwise; any other extension is CommonJS. A +// CommonJS file imports as a module exporting `default` and 'module.exports', +// both its module.exports from the cache require() uses. The fixtures are +// written at run time under a name unique to this run: modules evaluate once +// per process, and code caches outlive it. +describe("import() of CommonJS and .js files", function () { + var runId = String(Date.now()); + var fixtureDir = __dirname + "/esm/cjs-import-" + runId; + var fixtureSpec = "./esm/cjs-import-" + runId; + var isDebugBuild = typeof require("ns:module").canonicalizeHttpUrlKey === "function"; + var codeCaches = require("./codeCacheFiles"); + var metaBody = "export const keys = Object.keys(import.meta);\nexport const meta = import.meta;\n"; + var fixtures = { + "esm-syntax.js": "export const kind = \"esm\";\nexport default 7;\n", + "esm-tla.js": "globalThis.__nsImportCjsTla = await Promise.resolve(\"tla\");\n", + "broken.js": "const = ;\n", + "plain.js": "module.exports = { kind: \"cjs\" };\n", + "imported-first.js": "module.exports = { kind: \"imported-first\" };\n", + "required-first.js": "module.exports = { kind: \"required-first\" };\n", + "exports-only.js": "exports.a = 1;\n", + "lib.cjs": "exports.kind = \"cjs-ext\";\n" + + "exports.types = [typeof require, typeof module, typeof exports];\n", + "esm-syntax.cjs": "export const kind = \"esm\";\n", + "throws.js": "var error = new TypeError(\"cjs-throws\");\n" + + "globalThis.__nsImportCjsThrown = error;\nthrow error;\n", + "throws-primitive.js": "throw 42;\n", + // `late` is in its temporal dead zone until the body finishes, so a + // namespace handed out before then throws on reading it. + "self.mjs": "const order = globalThis.__nsSelfImportOrder = [];\n" + + "export const self = import(\"./self.mjs\").then(function (ns) {\n" + + " order.push(\"settled:\" + ns.late);\n return ns;\n});\n" + + "await new Promise(function (resolve) { setTimeout(resolve, 20); });\n" + + "order.push(\"evaluated\");\nexport const late = \"late\";\n", + "cycle-a.mjs": "import { fromB } from \"./cycle-b.mjs\";\n" + + "export const sawB = fromB;\nglobalThis.__nsCycleOrder.push(\"a-evaluated\");\n" + + "export const late = \"late\";\n", + "cycle-b.mjs": "const order = globalThis.__nsCycleOrder = [];\nexport const fromB = \"b\";\n" + + "export const aPromise = import(\"./cycle-a.mjs\").then(function (ns) {\n" + + " order.push(\"settled:\" + ns.late);\n return ns;\n});\n" + + "order.push(\"b-evaluated\");\n", + "meta.mjs": metaBody, + "meta-js.js": metaBody + }; + + function writeFile(path, body) { + var writer = new java.io.OutputStreamWriter(new java.io.FileOutputStream(path), "UTF-8"); + try { + writer.write(body); + } finally { + writer.close(); + } + } + + function deleteTree(file) { + var children = file.listFiles(); + for (var i = 0; children && i < children.length; i++) { + deleteTree(children[i]); + } + file.delete(); + } + + function load(name) { + return import(fixtureSpec + "/" + name); + } + + function failWith(done) { + return function (error) { + fail("unexpected rejection: " + String((error && error.stack) || error)); + done(); + }; + } + + function expectRejection(promise, done, check) { + promise.then(function () { + fail("resolved"); + done(); + }, function (error) { + check(error); + done(); + }); + } + + beforeAll(function () { + new java.io.File(fixtureDir).mkdirs(); + Object.keys(fixtures).forEach(function (name) { + writeFile(fixtureDir + "/" + name, fixtures[name]); + }); + }); + + afterAll(function () { + deleteTree(new java.io.File(fixtureDir)); + }); + + it("loads a .js file with ES module syntax as an ES module", function (done) { + load("esm-syntax.js").then(function (ns) { + expect(ns.kind).toBe("esm"); + expect(ns.default).toBe(7); + expect("module.exports" in ns).toBe(false); + done(); + }).catch(failWith(done)); + }); + + it("loads a .js file with only top-level await as an ES module", function (done) { + load("esm-tla.js").then(function (ns) { + expect(Object.keys(ns)).toEqual([]); + expect(globalThis.__nsImportCjsTla).toBe("tla"); + done(); + }).catch(failWith(done)); + }); + + it("rejects a .js file that parses neither way with a SyntaxError", function (done) { + expectRejection(load("broken.js"), done, function (error) { + expect(error instanceof SyntaxError).toBe(true); + }); + }); + + it("loads a CommonJS .js file as default and 'module.exports'", function (done) { + load("plain.js").then(function (ns) { + expect(Object.keys(ns)).toEqual(["default", "module.exports"]); + expect(ns.default.kind).toBe("cjs"); + expect(ns["module.exports"]).toBe(ns.default); + done(); + }).catch(failWith(done)); + }); + + it("shares require()'s cache when import() comes first", function (done) { + load("imported-first.js").then(function (ns) { + expect(require(fixtureDir + "/imported-first.js")).toBe(ns.default); + done(); + }).catch(failWith(done)); + }); + + it("shares require()'s cache when require() comes first", function (done) { + var exports = require(fixtureDir + "/required-first.js"); + load("required-first.js").then(function (ns) { + expect(ns.default).toBe(exports); + expect(ns["module.exports"]).toBe(exports); + done(); + }).catch(failWith(done)); + }); + + it("exports a CommonJS module's exports object", function (done) { + load("exports-only.js").then(function (ns) { + expect(ns.default.a).toBe(1); + done(); + }).catch(failWith(done)); + }); + + it("loads a .cjs file as CommonJS", function (done) { + load("lib.cjs").then(function (ns) { + expect(ns.default.kind).toBe("cjs-ext"); + expect(ns.default.types).toEqual(["function", "object", "object"]); + expect(ns["module.exports"]).toBe(ns.default); + done(); + }).catch(failWith(done)); + }); + + it("rejects ES module syntax in a .cjs file with a SyntaxError", function (done) { + expectRejection(load("esm-syntax.cjs"), done, function (error) { + expect(error instanceof SyntaxError).toBe(true); + }); + }); + + it("rejects with the value a CommonJS module throws", function (done) { + expectRejection(load("throws.js"), done, function (error) { + expect(error).toBe(globalThis.__nsImportCjsThrown); + expect(error instanceof TypeError).toBe(true); + expect(error.message).toBe("cjs-throws"); + }); + }); + + it("rejects with the primitive a CommonJS module throws", function (done) { + expectRejection(load("throws-primitive.js"), done, function (error) { + expect(error).toBe(42); + }); + }); + + it("settles a module's import() of itself after it evaluates", function (done) { + load("self.mjs").then(function (ns) { + return ns.self.then(function (self) { + expect(self).toBe(ns); + expect(globalThis.__nsSelfImportOrder).toEqual(["evaluated", "settled:late"]); + done(); + }); + }).catch(failWith(done)); + }); + + it("settles import() of a module still evaluating its dependencies after it evaluates", function (done) { + load("cycle-a.mjs").then(function (a) { + return load("cycle-b.mjs").then(function (b) { + return b.aPromise; + }).then(function (fromB) { + expect(fromB).toBe(a); + expect(a.sawB).toBe("b"); + expect(globalThis.__nsCycleOrder).toEqual(["b-evaluated", "a-evaluated", "settled:late"]); + done(); + }); + }).catch(failWith(done)); + }); + + it("gives an ES module import.meta url and dirname, and no filename", function (done) { + Promise.all([load("meta.mjs"), load("meta-js.js")]).then(function (results) { + [["meta.mjs", results[0]], ["meta-js.js", results[1]]].forEach(function (entry) { + var ns = entry[1]; + expect(ns.keys).toEqual(["url", "dirname"]); + expect(ns.meta.dirname).toBe(fixtureDir); + expect(ns.meta.url).toBe("file://" + fixtureDir + "/" + entry[0]); + expect("filename" in ns.meta).toBe(false); + }); + done(); + }).catch(failWith(done)); + }); + + function moduleCache(path) { + var file = codeCaches.fileFor(path, "module"); + var deadline = Date.now() + 5000; + return new Promise(function (resolve, reject) { + (function poll() { + var header = codeCaches.readHeader(file); + if (header !== null) { + resolve(header); + } else if (Date.now() > deadline) { + reject(new Error("no module code cache for " + path)); + } else { + setTimeout(poll, 100); + } + })(); + }); + } + + it("records each .js file's detected format in its code cache", function (done) { + if (isDebugBuild) { + pending("debuggable builds write no code caches"); + done(); + return; + } + Promise.all([load("plain.js"), load("esm-syntax.js")]).then(function () { + return Promise.all([moduleCache(fixtureDir + "/plain.js"), + moduleCache(fixtureDir + "/esm-syntax.js")]); + }).then(function (headers) { + expect(headers[0].version).toBe(2); + expect(headers[0].format).toBe(1); + expect(headers[0].payloadLength).toBe(0); + expect(headers[1].version).toBe(2); + expect(headers[1].format).toBe(2); + expect(headers[1].payloadLength).toBeGreaterThan(0); + done(); + }).catch(failWith(done)); + }); +}); diff --git a/test-app/app/src/main/assets/app/tests/testImportMetaResolution.js b/test-app/app/src/main/assets/app/tests/testImportMetaResolution.js index 4d9e6850f..0e4dd2304 100644 --- a/test-app/app/src/main/assets/app/tests/testImportMetaResolution.js +++ b/test-app/app/src/main/assets/app/tests/testImportMetaResolution.js @@ -36,3 +36,196 @@ describe("import.meta resolution", function () { }, rejected(done)); }); }); + +// Script origins and import.meta.url spell a file's path verbatim, as +// "file://" + the absolute path, not percent-encoded. Written at run time: the +// fixtures live in the app's files directory only for the duration of the +// specs. +describe("module and script URLs of files with unusual names", function () { + var appRoot = __dirname.slice(0, __dirname.length - "/tests".length); + var fixtureDir = appRoot + "/esm/ident ö"; + var outsidePath = appRoot.slice(0, appRoot.lastIndexOf("/")) + "/ident-outside ö.mjs"; + var queryDir = fixtureDir + "/q?dir"; + var siblingRoot = appRoot + "x"; + var nsModule = require("ns:module"); + var metaBody = + "export const url = import.meta.url;\n" + + "export const dirname = import.meta.dirname;\n" + + "export function fail() { throw new Error(\"ident\"); }\n"; + + function writeFile(path, body) { + var writer = new java.io.OutputStreamWriter(new java.io.FileOutputStream(path), "UTF-8"); + try { + writer.write(body); + } finally { + writer.close(); + } + } + + function stackOf(fn) { + try { + fn(); + } catch (e) { + return String(e.stack); + } + return "did not throw"; + } + + function rejected(done) { + return function (error) { + expect("rejected: " + String((error && error.message) || error)).toBe("resolved"); + done(); + }; + } + + beforeAll(function () { + new java.io.File(fixtureDir).mkdirs(); + writeFile(fixtureDir + "/meta.mjs", metaBody); + writeFile(fixtureDir + "/pct%41.mjs", metaBody); + writeFile(fixtureDir + "/h#.mjs", metaBody); + writeFile(fixtureDir + "/cjs.js", "exports.fail = function () { throw new Error(\"ident\"); };\n"); + writeFile(outsidePath, metaBody); + new java.io.File(queryDir).mkdirs(); + writeFile(queryDir + "/m.mjs", metaBody + "export { url as siblingUrl } from \"./sibling.mjs\";\n"); + writeFile(queryDir + "/sibling.mjs", "export const url = import.meta.url;\n"); + new java.io.File(siblingRoot).mkdirs(); + writeFile(siblingRoot + "/y.mjs", metaBody); + }); + + function deleteTree(file) { + var children = file.listFiles(); + if (children !== null) { + for (var i = 0; i < children.length; i++) { + deleteTree(children[i]); + } + } + file.delete(); + } + + afterAll(function () { + deleteTree(new java.io.File(fixtureDir)); + deleteTree(new java.io.File(siblingRoot)); + new java.io.File(outsidePath).delete(); + }); + + it("spells a module's import.meta.url, dirname and stack frames verbatim", function (done) { + import("~/esm/ident ö/meta.mjs").then(function (m) { + var url = "file://" + fixtureDir + "/meta.mjs"; + expect(m.url).toBe(url); + expect(m.dirname).toBe(fixtureDir); + expect(stackOf(m.fail)).toContain("(" + url + ":3:"); + done(); + }, rejected(done)); + }); + + it("keeps the query in import.meta.url and stack frames", function (done) { + import("~/esm/ident ö/meta.mjs?q=a b").then(function (m) { + var url = "file://" + fixtureDir + "/meta.mjs?q=a%20b"; + expect(m.url).toBe(url); + expect(stackOf(m.fail)).toContain("(" + url + ":3:"); + done(); + }, rejected(done)); + }); + + it("does not decode a '%' sequence in a file name", function (done) { + import("~/esm/ident ö/pct%41.mjs").then(function (m) { + expect(m.url).toBe("file://" + fixtureDir + "/pct%41.mjs"); + done(); + }, rejected(done)); + }); + + it("keeps a '#' in a file name", function () { + var m = require(fixtureDir + "/h#.mjs"); + expect(m.url).toBe("file://" + fixtureDir + "/h#.mjs"); + expect(stackOf(m.fail)).toContain("(file://" + fixtureDir + "/h#.mjs:3:"); + }); + + it("invalidates a '%' file name through its own import.meta.url", function (done) { + import("~/esm/ident ö/pct%41.mjs").then(function (first) { + nsModule.invalidateModules([first.url]); + return import("~/esm/ident ö/pct%41.mjs").then(function (second) { + expect(second).not.toBe(first); + expect(second.url).toBe(first.url); + done(); + }); + }).catch(rejected(done)); + }); + + it("imports a '#' file name through a file: URL and invalidates it through its import.meta.url", function (done) { + var spec = "file://" + fixtureDir + "/h%23.mjs"; + import(spec).then(function (first) { + expect(first.url).toBe("file://" + fixtureDir + "/h#.mjs"); + nsModule.invalidateModules([first.url]); + return import(spec).then(function (second) { + expect(second).not.toBe(first); + expect(second.url).toBe(first.url); + done(); + }); + }).catch(rejected(done)); + }); + + it("resolves inside a directory whose name has '?'", function (done) { + import("file://" + fixtureDir + "/q%3Fdir/m.mjs").then(function (m) { + expect(m.url).toBe("file://" + queryDir + "/m.mjs"); + expect(m.dirname).toBe(queryDir); + expect(m.siblingUrl).toBe("file://" + queryDir + "/sibling.mjs"); + done(); + }, rejected(done)); + }); + + // A root-absolute specifier is used as written only when it is under the + // app root by whole path segments, after "." and ".." are folded. + it("looks up a root-absolute path beside the app root under the app root", function (done) { + import(siblingRoot + "/y.mjs").then(function () { + expect("resolved").toBe("rejected"); + done(); + }, function (e) { + expect(e.message).toBe("Cannot find module '" + siblingRoot + "/y.mjs' (tried " + + appRoot + siblingRoot + "/y.mjs)"); + return import("file://" + siblingRoot + "/y.mjs").then(function (m) { + expect(m.url).toBe("file://" + siblingRoot + "/y.mjs"); + done(); + }); + }).catch(rejected(done)); + }); + + // A root-absolute path is folded before it is tested against the app root; + // "~/", bare and prefixed root-absolute paths then drop a ".." at the app + // root, as a URL drops one at its root. + it("does not let '..' in a root-absolute path leave the app root", function (done) { + import(appRoot + "/../ident-outside ö.mjs").then(function () { + expect("resolved").toBe("rejected"); + done(); + }, function (e) { + expect(e.message).toBe("Cannot find module '" + appRoot + "/../ident-outside ö.mjs' (tried " + + appRoot + outsidePath + ")"); + done(); + }); + }); + + it("clamps '..' at the app root for '~/', root-absolute and bare specifiers", function (done) { + Promise.all([ + import("~/../../esm/ident ö/meta.mjs"), + import("/../../esm/ident ö/meta.mjs"), + import("esm/../../esm/ident ö/meta.mjs"), + import("~/esm/ident ö/meta.mjs"), + ]).then(function (r) { + expect([r[0] === r[3], r[1] === r[3], r[2] === r[3]]).toEqual([true, true, true]); + expect(r[3].url).toBe("file://" + fixtureDir + "/meta.mjs"); + done(); + }, rejected(done)); + }); + + it("spells a file outside the app root the same way", function (done) { + import("file://" + outsidePath).then(function (m) { + expect(m.url).toBe("file://" + outsidePath); + expect(stackOf(m.fail)).toContain("(file://" + outsidePath + ":3:"); + done(); + }, rejected(done)); + }); + + it("spells a script's stack frames verbatim", function () { + var cjs = require(fixtureDir + "/cjs.js"); + expect(stackOf(cjs.fail)).toContain("file://" + fixtureDir + "/cjs.js:"); + }); +}); diff --git a/test-app/app/src/main/assets/app/tests/testJsonModules.js b/test-app/app/src/main/assets/app/tests/testJsonModules.js new file mode 100644 index 000000000..3a07b1338 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testJsonModules.js @@ -0,0 +1,142 @@ +// A JSON module is JSON.parse of its text: text that is not strict JSON is a +// SyntaxError naming the module, and nothing in it runs. +describe("JSON modules", function () { + var appRoot = __dirname.slice(0, __dirname.length - "/tests".length); + var dir = "~/esm/json-strict/"; + var fileUrl = "file://" + appRoot + "/esm/json-strict/"; + var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); + var httpSeq = 0; + var isDebugBuild = typeof require("ns:module").canonicalizeHttpUrlKey === "function"; + + function skipHttpInRelease() { + if (!isDebugBuild) { + pending("the release allowlist does not admit the loopback module server"); + return true; + } + return false; + } + + var originalTimeout; + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000; + }); + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + function load(spec) { + return import(dir + "importer.mjs").then(function (m) { return m.load(spec); }); + } + + // A URL of its own for each call, so no row reuses another's module. + function httpJson(text) { + return origin + "/esm/json-text.json?n=" + (++httpSeq) + "&text=" + encodeURIComponent(text); + } + + function expectResolved(done) { + return function (e) { + expect("rejected: " + (e && e.name) + ": " + (e && e.message)).toBe("resolved"); + done(); + }; + } + + // The message is ": "; `urlPrefix` is + // the URL, or its start when the server reports it. + function expectSyntaxError(promise, urlPrefix, done) { + promise.then(function () { + expect("resolved").toBe("rejected with a SyntaxError"); + done(); + }, function (e) { + expect(e instanceof SyntaxError).toBe(true); + expect(String(e && e.message).indexOf(urlPrefix)).toBe(0); + expect(String(e && e.message)).toContain("JSON"); + done(); + }); + } + + it("loads strict JSON as the default export", function (done) { + load("./ok.json").then(function (ns) { + expect(ns.default).toEqual({ name: "strict" }); + expect(Object.keys(ns)).toEqual(["default"]); + done(); + }, expectResolved(done)); + }); + + it("rejects a trailing comma with the SyntaxError itself", function (done) { + expectSyntaxError(load("./trailing-comma.json"), fileUrl + "trailing-comma.json: ", done); + }); + + it("rejects a comment", function (done) { + expectSyntaxError(load("./comment.json"), fileUrl + "comment.json: ", done); + }); + + it("rejects whitespace-only text", function (done) { + expectSyntaxError(load("./empty.json"), fileUrl + "empty.json: ", done); + }); + + it("rejects code after the value without running it", function (done) { + delete globalThis.__jsonStrictInjected; + load("./injection.json").then(function () { + expect("resolved").toBe("rejected with a SyntaxError"); + done(); + }, function (e) { + expect(e instanceof SyntaxError).toBe(true); + expect(String(e && e.message).indexOf(fileUrl + "injection.json: ")).toBe(0); + expect(globalThis.__jsonStrictInjected).toBeUndefined(); + done(); + }); + }); + + it("keeps __proto__ as an own property", function (done) { + load("./proto.json").then(function (ns) { + var value = ns.default; + expect(Object.getPrototypeOf(value)).toBe(Object.prototype); + expect(Object.prototype.hasOwnProperty.call(value, "__proto__")).toBe(true); + expect(value.polluted).toBeUndefined(); + expect(value.own).toBe(1); + done(); + }, expectResolved(done)); + }); + + it("fails the importer's link on a static import of invalid JSON", function (done) { + import(dir + "static-trailing-comma.mjs").then(function () { + expect("resolved").toBe("rejected"); + done(); + }, function (e) { + var message = String(e && e.message); + expect(message.indexOf("Failed to instantiate module: ")).toBe(0); + expect(message).toContain("SyntaxError: " + fileUrl + "trailing-comma.json: "); + done(); + }); + }); + + it("loads strict JSON served over HTTP", function (done) { + if (skipHttpInRelease()) { done(); return; } + import(httpJson('{"served": [1, 2]}'), { with: { type: "json" } }).then(function (ns) { + expect(ns.default).toEqual({ served: [1, 2] }); + done(); + }, expectResolved(done)); + }); + + it("rejects an HTTP JSON root that does not parse with the SyntaxError itself", function (done) { + if (skipHttpInRelease()) { done(); return; } + var url = httpJson('{"a": 1,}'); + expectSyntaxError(import(url, { with: { type: "json" } }), + url.slice(0, url.indexOf("&text=")), done); + }); + + it("runs no code after the value of an HTTP JSON root", function (done) { + if (skipHttpInRelease()) { done(); return; } + delete globalThis.__jsonStrictInjected; + var url = httpJson('{"a": 1};globalThis.__jsonStrictInjected = true'); + import(url, { with: { type: "json" } }).then(function () { + expect("resolved").toBe("rejected with a SyntaxError"); + done(); + }, function (e) { + expect(e instanceof SyntaxError).toBe(true); + expect(globalThis.__jsonStrictInjected).toBeUndefined(); + done(); + }); + }); +}); diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index a34e5efe5..dd2341e45 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -38,8 +38,8 @@ describe("ns:module", function () { }); }); - // Boot state is derived natively from the entry-evaluation window; there is - // no client signal and no JS-visible mirror. + // Boot state is derived natively from the main entry's settlement; there + // is no client signal and no JS-visible mirror. it("exposes no boot-complete signal", function () { var nsModule = require("ns:module"); expect(nsModule.setDevBootComplete).toBeUndefined(); diff --git a/test-app/app/src/main/assets/app/tests/testPrebuiltExtendClasses.js b/test-app/app/src/main/assets/app/tests/testPrebuiltExtendClasses.js index 640d3f2e4..72d4166ce 100644 --- a/test-app/app/src/main/assets/app/tests/testPrebuiltExtendClasses.js +++ b/test-app/app/src/main/assets/app/tests/testPrebuiltExtendClasses.js @@ -80,6 +80,19 @@ describe("Prebuilt classes of anonymous extends", function () { expect(generatedDexFiles(instance)).toEqual([]); }); + it("names the classes of extends on the first line of a CommonJS file by the file's columns", function () { + var minified = require("./prebuiltExtendLineOneMinified"); + var first = new minified.First(); + var second = new minified.Second(); + + expect(first.toString()).toBe("first"); + expect(second.toString()).toBe("second"); + expect(String(first.getClass().getName())).toMatch(/_1_30_$/); + expect(String(second.getClass().getName())).toMatch(/_1_142_$/); + expect(generatedDexFiles(first)).toEqual([]); + expect(generatedDexFiles(second)).toEqual([]); + }); + it("loads the class of an extend on the first line of an ES module from the APK", function () { var LineOneObject = require("./prebuiltExtendLineOne.mjs").LineOneObject; var instance = new LineOneObject(); diff --git a/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js b/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js index 4a321aac5..c2a1fac2d 100644 --- a/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js +++ b/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js @@ -14,8 +14,12 @@ describe("Script code caches with workers starting together", function () { expected[name] = require("./concurrentStartup/" + name).value; }); + var codeCaches = require("./codeCacheFiles"); + var sourcePath = function (name) { + return fixtureDir + "/" + name + ".js"; + }; var cacheFile = function (name) { - return new java.io.File(fixtureDir, name + ".js.cache"); + return new java.io.File(codeCaches.fileFor(sourcePath(name), "script")); }; var dropCaches = function () { @@ -99,36 +103,32 @@ describe("Script code caches with workers starting together", function () { expectValues(await runBatch()); }, 120000); - it("publishes caches stamped with their source's mtime and leaves no temporaries", async function () { + it("publishes caches for their source's current mtime and leaves no temporaries", async function () { if (!cachesEnabled) { pending("code caches are off: debuggable build or no \"codeCache\": true"); } dropCaches(); expectValues(await runBatch(3000)); + // Every worker publishes the same caches through one serial writer, so + // a file exists while later writes of it may still be in flight. + var leftovers = function () { + return moduleNames.reduce(function (found, name) { + return found.concat(codeCaches.temporariesOf(String(cacheFile(name).getAbsolutePath()))); + }, []); + }; var deadline = Date.now() + 5000; - while (Date.now() < deadline && !moduleNames.every(function (name) { + while (Date.now() < deadline && (leftovers().length > 0 || !moduleNames.every(function (name) { return cacheFile(name).exists(); - })) { + }))) { await new Promise(function (resolve) { setTimeout(resolve, 100); }); } moduleNames.forEach(function (name) { - var cache = cacheFile(name); - var source = new java.io.File(fixtureDir, name + ".js"); - expect(name + ": " + cache.exists()).toBe(name + ": true"); - expect(Math.floor(cache.lastModified() / 1000)) - .toBe(Math.floor(source.lastModified() / 1000)); + var cache = String(cacheFile(name).getAbsolutePath()); + expect(name + ": " + codeCaches.isFresh(cache, sourcePath(name))).toBe(name + ": true"); }); - - var names = new java.io.File(fixtureDir).list(); - var leftovers = []; - for (var i = 0; i < names.length; i++) { - if (String(names[i]).indexOf(".cache.") !== -1) { - leftovers.push(String(names[i])); - } - } - expect(leftovers).toEqual([]); + expect(leftovers()).toEqual([]); }, 60000); }); diff --git a/test-app/app/src/main/assets/app/tests/testWorkerEntryNames.js b/test-app/app/src/main/assets/app/tests/testWorkerEntryNames.js new file mode 100644 index 000000000..7076aea6c --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/testWorkerEntryNames.js @@ -0,0 +1,86 @@ +// Worker entry names resolve as Node's Worker resolves them, except that a +// "./" or "../" name not found next to the caller is tried from the app root. +describe("Worker entry names", function () { + var originalTimeout; + + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000; + }); + + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + function constructionError(name) { + try { + new Worker(name).terminate(); + } catch (e) { + return e; + } + return undefined; + } + + it("throws ERR_WORKER_PATH from the constructor for a bare name", function () { + var error = constructionError("eventLoopEchoWorker.js"); + + expect(error instanceof TypeError).toBe(true); + expect(error.code).toBe("ERR_WORKER_PATH"); + expect(error.message).toContain('Received "eventLoopEchoWorker.js"'); + }); + + it("reports the caller's directory when neither it nor the app root has the entry", function () { + var error = constructionError("./missingEntryWorker.js"); + + expect(error instanceof Error).toBe(true); + expect(error.code).toBe("MODULE_NOT_FOUND"); + var prefix = "Cannot find module './missingEntryWorker.js' (tried " + __dirname + "/missingEntryWorker.js"; + expect(error.message.substr(0, prefix.length)).toBe(prefix); + }); + + it("runs a ./ entry from the app root when the caller's directory lacks it", function (done) { + var worker = new Worker("./tests/eventLoopEchoWorker.js"); + worker.onmessage = function (msg) { + expect(msg.data).toBe("app-root"); + worker.terminate(); + done(); + }; + worker.onerror = function (e) { + expect("worker error: " + e.message).toBe("no error"); + worker.terminate(); + done(); + }; + worker.postMessage("app-root"); + }); + + it("runs a ~name entry from the app root", function (done) { + var worker = new Worker("~tests/eventLoopEchoWorker.js"); + worker.onmessage = function (msg) { + expect(msg.data).toBe("tilde"); + worker.terminate(); + done(); + }; + worker.onerror = function (e) { + expect("worker error: " + e.message).toBe("no error"); + worker.terminate(); + done(); + }; + worker.postMessage("tilde"); + }); + + it("reports a JSON entry as not a JavaScript module", function (done) { + var worker = new Worker("~/tests/package.json"); + worker.onmessage = function (msg) { + expect("worker message: " + msg.data).toBe("no message"); + worker.terminate(); + done(); + }; + // Returns true so the error is not re-reported on the main global scope. + worker.onerror = function (e) { + expect(e.message).toContain("Cannot run " + __dirname + "/package.json as an entry: it is not a JavaScript module"); + worker.terminate(); + done(); + return true; + }; + }); +}); diff --git a/test-app/app/src/main/assets/app/tests/testWorkerEsmEntry.js b/test-app/app/src/main/assets/app/tests/testWorkerEsmEntry.js index 11aa225b2..c21783338 100644 --- a/test-app/app/src/main/assets/app/tests/testWorkerEsmEntry.js +++ b/test-app/app/src/main/assets/app/tests/testWorkerEsmEntry.js @@ -1,9 +1,9 @@ -// An ES module worker entry takes the same RunModule branch — and the same -// boot evaluation options — the app's main entry takes, so these pin that -// destination even though the suite cannot re-drive the app's own boot. -// A worker specifier is resolved through Java resolvePath whatever route the -// entry ends up taking, so app-root-absolute, relative and extension-less -// paths all reach an `.mjs` entry. +// A local ES module worker entry is evaluated without a pump: one whose +// top-level await is still running comes back pending, finishes from the +// worker's own event loop, and the worker's message queue enables when it +// settles. A worker specifier is resolved as require() resolves it whatever +// route the entry ends up taking, so app-root-absolute, relative and +// extension-less paths all reach an `.mjs` entry. describe("worker ES module entries", function () { var originalTimeout; @@ -26,11 +26,10 @@ describe("worker ES module entries", function () { worker.postMessage("ping"); }); - it("runs an ES module worker entry whose top-level await parks past the yield window", + it("runs an ES module worker entry whose top-level await parks on a non-nestable task", function (done) { - // The park is non-nestable, so the in-place window cannot settle it: - // the entry finishes from the real event loop afterwards, and the - // message queue enables on settle rather than being lost. + // The message queue enables on settle, so a message posted while the + // entry is still pending is delivered rather than lost. var worker = new Worker("~/tests/esmEntryTlaWorker.mjs"); worker.onmessage = function (msg) { expect(msg.data).toBe("tla-entry:ok:ping"); @@ -76,9 +75,9 @@ describe("worker ES module entries", function () { }); // Extension resolution tries `.js` before `.mjs`, and no `.js` sibling - // exists, so the ES module entry is what answers. Its top-level await also - // parks past the yield window, so the message posted here proves the - // settle-gated queue engages on a resolved specifier too. + // exists, so the ES module entry is what answers. Its top-level await is + // still running when the entry returns, so the message posted here proves + // the settle-gated queue engages on a resolved specifier too. it("runs an extension-less ES module worker entry past its top-level await", function (done) { var worker = new Worker("./esmEntryResolvedWorker"); @@ -91,8 +90,8 @@ describe("worker ES module entries", function () { }); // The worker isolate is published before its entry runs, so terminate() - // can interrupt an entry that is still evaluating - here one parked on a - // promise that never settles, inside the pump that waits for it. + // can interrupt a worker whose entry is still evaluating - here one parked + // on a promise that never settles. it("survives terminate() while an entry is parked in top-level await", function (done) { var ITERATIONS = 3; var FALLBACK_TERMINATE = 700; @@ -134,8 +133,8 @@ describe("worker ES module entries", function () { expect(msg.data).toBe("never-settles:started"); terminateOnce(); }; - // The evaluation pump is bounded, so a start message that never - // arrives must not push the terminate past the window it targets. + // A start message that never arrives must not hold the terminate + // back. setTimeout(terminateOnce, FALLBACK_TERMINATE); } diff --git a/test-app/app/src/main/java/com/tns/RuntimeHelper.java b/test-app/app/src/main/java/com/tns/RuntimeHelper.java index 695d9ee4d..114126022 100644 --- a/test-app/app/src/main/java/com/tns/RuntimeHelper.java +++ b/test-app/app/src/main/java/com/tns/RuntimeHelper.java @@ -160,7 +160,7 @@ public static Runtime initRuntime(Context context) { boolean isDebuggable = Util.isDebuggableApp(context); StaticConfiguration config = new StaticConfiguration(logger, appName, nativeLibDir, rootDir, - appDir, classLoader, dexDir, dexThumb, appConfig, isDebuggable); + appDir, classLoader, dexDir, dexThumb, appConfig, isDebuggable, context.getCodeCacheDir()); runtime = Runtime.initializeRuntimeWithConfiguration(config); if (isDebuggable) { diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index f997685b7..19e1317fb 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -416,7 +416,8 @@ private static void routeCounted(Socket socket, String path, String query, int o } else { body = "export const path = \"" + jsStringLiteral(path) + "\";\n" + "export const query = \"" + jsStringLiteral(query) + "\";\n" - + "export const url = import.meta.url;\n"; + + "export const url = import.meta.url;\n" + + "export const hasDirname = \"dirname\" in import.meta;\n"; } respond(socket, "200 OK", JS_MIME, body.getBytes(UTF8)); return; @@ -437,6 +438,15 @@ private static void routeCounted(Socket socket, String path, String query, int o return; } + // Serves the `text` param, decoded, as a JSON module: any text, JSON + // or not, under its own URL per text. + if ("/esm/json-text.json".equals(path)) { + String raw = param(query, "text="); + String body = raw == null ? "" : URLDecoder.decode(raw, "UTF-8"); + respond(socket, "200 OK", "application/json; charset=utf-8", body.getBytes(UTF8)); + return; + } + if ("/esm/empty.mjs".equals(path)) { respond(socket, "200 OK", JS_MIME, new byte[0]); return; diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index a17a37bef..674dbbd5a 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -107,7 +107,6 @@ set(RUNTIME_BUILTIN_JS ${RUNTIME_BUILTIN_JS_DIR}/ns-worker-threads.js ${RUNTIME_BUILTIN_JS_DIR}/performance.js ${RUNTIME_BUILTIN_JS_DIR}/primordials.js - ${RUNTIME_BUILTIN_JS_DIR}/require-factory.js ${RUNTIME_BUILTIN_JS_DIR}/structured-clone.js ${RUNTIME_BUILTIN_JS_DIR}/text-encoding.js ${RUNTIME_BUILTIN_JS_DIR}/weak-collections.js @@ -191,6 +190,12 @@ else () set(NAPI_TEST_SOURCES) endif () +# Code shared with the iOS runtime (NativeScript/runtime-common). Added after +# CMAKE_CXX_FLAGS is final: the library compiles with these flags, which carry +# the V8 configuration defines it must agree with. +set(NS_V8_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/src/main/cpp/include) +add_subdirectory(src/main/cpp/runtime-common) + # Command info: https://cmake.org/cmake/help/v3.4/command/add_library.html # Creates(shared static) and names a library given relative sources # Gradle automatically packages shared libraries with your APK. @@ -242,7 +247,6 @@ add_library( src/main/cpp/MethodCache.cpp src/main/cpp/ModuleBinding.cpp src/main/cpp/ModuleInternal.cpp - src/main/cpp/ModuleInternalCallbacks.cpp src/main/cpp/ModuleUrl.cpp src/main/cpp/NativeScriptAssert.cpp src/main/cpp/NativeScriptException.cpp @@ -278,6 +282,7 @@ add_library( src/main/cpp/URLSearchParamsImpl.cpp src/main/cpp/URLPatternImpl.cpp src/main/cpp/HttpLoader.cpp + src/main/cpp/RuntimeCommonPlatform.cpp src/main/cpp/TraceLog.cpp # Node-API: vendored upstream implementation plus the embedder half @@ -337,6 +342,7 @@ MESSAGE(STATUS "# CMAKE_C_FLAGS: " ${CMAKE_C_FLAGS}) MESSAGE(STATUS "# CMAKE_CXX_FLAGS: " ${CMAKE_CXX_FLAGS}) # Command info: https://cmake.org/cmake/help/v3.4/command/target_link_libraries.html +target_link_libraries(NativeScript ns_runtime_common) target_link_libraries(NativeScript ${PROJECT_SOURCE_DIR}/src/main/libs/${ANDROID_ABI}/libzip.a) # libv8_monolith.a carries the NDK libc++ it was compiled against, and libc++ is # only ABI-compatible with itself, so v8-buildscripts has to build V8 with the diff --git a/test-app/runtime/src/main/cpp/Base64.cpp b/test-app/runtime/src/main/cpp/Base64.cpp index 76a192e59..0587fea0d 100644 --- a/test-app/runtime/src/main/cpp/Base64.cpp +++ b/test-app/runtime/src/main/cpp/Base64.cpp @@ -1,9 +1,8 @@ #include "Base64.h" -#include - #include "BuiltinLoader.h" #include "Util.h" +#include "ns/Base64Binding.h" using namespace v8; @@ -11,168 +10,11 @@ namespace tns { namespace { -constexpr char kAlphabet[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -// 6-bit value per ASCII byte; 0xFF marks everything outside the alphabet. -constexpr uint8_t kInvalid = 0xFF; - -uint8_t SixBits(uint8_t c) { - if (c >= 'A' && c <= 'Z') { - return static_cast(c - 'A'); - } - if (c >= 'a' && c <= 'z') { - return static_cast(c - 'a' + 26); - } - if (c >= '0' && c <= '9') { - return static_cast(c - '0' + 52); - } - if (c == '+') { - return 62; - } - if (c == '/') { - return 63; - } - return kInvalid; -} - -bool IsAsciiWhitespace(uint8_t c) { - return c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' '; -} - -// The string's code units as bytes. Fails when any unit is above U+00FF, -// which neither op can represent. -bool GetLatin1Bytes(Isolate* isolate, Local value, - std::vector* out) { - if (!value->IsString()) { - return false; - } - Local str = value.As(); - if (!str->ContainsOnlyOneByte()) { - return false; - } - const int length = str->Length(); - out->resize(static_cast(length)); - if (length > 0) { - str->WriteOneByteV2(isolate, 0, static_cast(length), out->data()); - } - return true; -} - -// btoa: base64-encode the input's code units. -void BtoaCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector input; - if (!GetLatin1Bytes(isolate, info[0], &input)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve((input.size() + 2) / 3 * 4); - size_t i = 0; - for (; i + 3 <= input.size(); i += 3) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8) | - input[i + 2]; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back(kAlphabet[group & 0x3F]); - } - const size_t remaining = input.size() - i; - if (remaining == 1) { - const uint32_t group = static_cast(input[i]) << 16; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back('='); - out.push_back('='); - } else if (remaining == 2) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8); - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back('='); - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - -// atob: forgiving-base64 decode -// (https://infra.spec.whatwg.org/#forgiving-base64-decode). -void AtobCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector raw; - if (!GetLatin1Bytes(isolate, info[0], &raw)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector data; - data.reserve(raw.size()); - for (uint8_t c : raw) { - if (!IsAsciiWhitespace(c)) { - data.push_back(c); - } - } - - if (data.size() % 4 == 0) { - size_t strip = 0; - while (strip < 2 && !data.empty() && data.back() == '=') { - data.pop_back(); - strip++; - } - } - if (data.size() % 4 == 1) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve(data.size() / 4 * 3 + 2); - uint32_t accumulator = 0; - uint32_t bits = 0; - for (uint8_t c : data) { - const uint8_t value = SixBits(c); - if (value == kInvalid) { - info.GetReturnValue().SetNull(); - return; - } - accumulator = (accumulator << 6) | value; - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((accumulator >> bits) & 0xFF)); - } - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - MaybeLocal CreateBinding(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - tns::SetMethodNoSideEffect(context, binding, "btoa", BtoaCallback); - tns::SetMethodNoSideEffect(context, binding, "atob", AtobCallback); + tns::SetMethodNoSideEffect(context, binding, "btoa", nativescript::common::base64::Btoa); + tns::SetMethodNoSideEffect(context, binding, "atob", nativescript::common::base64::Atob); return binding; } diff --git a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp index 5878756d5..43e77fe94 100644 --- a/test-app/runtime/src/main/cpp/CallbackHandlers.cpp +++ b/test-app/runtime/src/main/cpp/CallbackHandlers.cpp @@ -20,6 +20,12 @@ #include #include "HttpLoader.h" #include "ModuleUrl.h" +#include "ns/JsError.h" +#include "ns/loader/CommonJs.h" +#include "ns/loader/LoaderState.h" +#include "ns/loader/ModuleIdentity.h" +#include "ns/loader/PackageJson.h" +#include "ns/loader/RequireResolver.h" #include "MethodCache.h" #include "ModuleInternal.h" #include "SimpleProfiler.h" @@ -1772,42 +1778,24 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo= 2 && workerPath[1] == '/' ? workerPath.substr(2) : workerPath.substr(1); - resolvedPath = Constants::APP_ROOT_FOLDER_PATH + tail; - } - - /* - * Relative worker paths are resolved against the calling module's - * directory. The caller may have no script name (e.g. eval'd code) or - * the script may not be found there - in both cases fall back to - * app-root-relative resolution, mirroring the iOS runtime. - */ - std::string currentDir = Constants::APP_ROOT_FOLDER_PATH; + // The calling module's directory, for a "./" or "../" entry; empty, + // which ResolveEntry reads as the app root, when the caller has no + // file of its own (eval'd code, an http(s) module). + std::string callerDir; auto stack = isHttpEntry ? Local() : StackTrace::CurrentStackTrace(isolate, 1, StackTrace::kScriptName); if (!stack.IsEmpty() && stack->GetFrameCount() > 0) { - auto currentExecutingScriptName = stack->GetFrame(isolate, 0)->GetScriptName(); - auto currentExecutingScriptNameStr = ArgConverter::ConvertToString( - currentExecutingScriptName); // A file module's script URL carries its query, whose slashes are // not path syntax. - const std::string callerPath = FileModulePath(currentExecutingScriptNameStr); - if (!callerPath.empty()) { - currentExecutingScriptNameStr = callerPath; - } - auto lastForwardSlash = currentExecutingScriptNameStr.find_last_of("/"); - if (lastForwardSlash != std::string::npos) { - auto callerDir = currentExecutingScriptNameStr.substr(0, lastForwardSlash + 1); - string fileSchema("file://"); - if (callerDir.compare(0, fileSchema.length(), fileSchema) == 0) { - callerDir = callerDir.substr(fileSchema.length()); - } - currentDir = callerDir; + const std::optional callerPath = + nativescript::common::loader::OriginToPath( + ArgConverter::ConvertToString( + stack->GetFrame(isolate, 0)->GetScriptName()), + nativescript::common::loader::LoaderConfigFor(isolate)); + if (callerPath && !callerPath->empty() && (*callerPath)[0] == '/') { + const size_t lastSlash = callerPath->find_last_of('/'); + callerDir = lastSlash == 0 ? "/" : callerPath->substr(0, lastSlash); } } @@ -1821,20 +1809,21 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo(isolate, workerId, entryPath, currentDir, + auto wrapper = std::make_shared(isolate, workerId, entryPath, priority, std::move(resourceLimits), thiz); WorkerWrapper::Insert(workerId, wrapper); @@ -1854,6 +1843,8 @@ void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfoStart(); } catch (NativeScriptException &e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError &e) { + e.ThrowToV8(v8::Isolate::GetCurrent()); } catch (std::exception e) { stringstream ss; ss << "Error: c exception: " << e.what() << endl; diff --git a/test-app/runtime/src/main/cpp/EventLoop.cpp b/test-app/runtime/src/main/cpp/EventLoop.cpp index df6a28c43..0b705c1e2 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.cpp +++ b/test-app/runtime/src/main/cpp/EventLoop.cpp @@ -17,6 +17,7 @@ #include "JniLocalRef.h" #include "NativeScriptAssert.h" #include "NativeScriptException.h" +#include "ns/JsError.h" using namespace v8; @@ -46,6 +47,10 @@ void RunGuarded(F&& body) { body(); } catch (tns::NativeScriptException& ex) { ex.ReThrowToJava(); + } catch (nativescript::common::JsError& ex) { + // No isolate scope is open here to build its JS value in. + tns::NativeScriptException(ex.message()).ReThrowToJava(); + } catch (nativescript::common::Terminated&) { } catch (std::exception& ex) { DEBUG_WRITE_FORCE("Error: c++ exception in event loop task: %s", ex.what()); } catch (...) { @@ -266,20 +271,22 @@ void EventLoop::PostOrderedLocked(Entry entry, double delayMs) { } } -void EventLoop::PostInternal(std::function fn) { +bool EventLoop::PostInternal(std::function fn) { std::lock_guard lock(mutex_); if (stopped_) { - return; + return false; } PostInternalLocked(Entry{nullptr, std::move(fn), true, false, 0}, 0); + return true; } -void EventLoop::PostInternalDelayed(std::function fn, double delayMs) { +bool EventLoop::PostInternalDelayed(std::function fn, double delayMs) { std::lock_guard lock(mutex_); if (stopped_) { - return; + return false; } PostInternalLocked(Entry{nullptr, std::move(fn), true, false, 0}, delayMs); + return true; } void EventLoop::PostInternalBare(std::function fn) { @@ -418,13 +425,14 @@ void EventLoop::SetTimerSource(OrderedTaskSource* source) { timerSource_ = source; } -void EventLoop::PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds) { +bool EventLoop::PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds) { std::lock_guard lock(mutex_); if (stopped_) { - return; + return false; } PostInternalLocked(Entry{std::move(task), nullptr, nestable, false, 0}, delaySeconds * 1000.0); + return true; } bool EventLoop::IsStopped() { @@ -614,6 +622,9 @@ void EventLoop::GuardEntryRun(const std::function& body) { // what() may read a JNI local ref that cannot outlive this dispatch, // so only its text is carried DeferJavaThrow(std::make_shared(std::string(ex.what()))); + } catch (nativescript::common::JsError& ex) { + DeferJavaThrow(std::make_shared(ex.message())); + } catch (nativescript::common::Terminated&) { } catch (std::exception& ex) { DEBUG_WRITE_FORCE("Error: c++ exception in event loop task: %s", ex.what()); } catch (...) { @@ -735,37 +746,54 @@ int EventLoop::RunDueOrderedEntries() { return ran; } -EventLoop::PumpResult EventLoop::PumpUntil(double deadlineSeconds, - const std::function& settled, - bool drainLooperWork) { +nativescript::common::PumpResult EventLoop::PumpUntil( + const nativescript::common::Deadline& deadline, const std::function& settled, + nativescript::common::PumpMode mode, const std::function& idle) { + using nativescript::common::PumpMode; + using nativescript::common::PumpResult; // home thread only: the drains below take ordered/timer slots and eventfd // units that the looper's own dispatch owns on that thread NS_DCHECK(looper_ == nullptr || ALooper_forThread() == looper_); PumpScope pumpScope; - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::duration(deadlineSeconds); + const bool platformWork = mode == PumpMode::kPlatformWork; for (;;) { - // Both probes: IsExecutionTerminating is true only while JS frames - // unwind with the termination exception active, so a pump parked with - // nothing queued would never observe TerminateExecution through it. - // Termination outranks settlement: consuming a settled result means - // running more JS, which a terminating isolate must not do. - if (terminationRequested_.load(std::memory_order_acquire) || - isolate_->IsExecutionTerminating()) { + // IsExecutionTerminating is true only while JS frames unwind with the + // termination exception active, so a pump parked with nothing queued + // would never observe TerminateExecution through it; the flag covers + // that. A stopped loop drops every post, so nothing can settle + // anymore. Termination outranks settlement: consuming a settled + // result means running more JS, which a terminating isolate must not + // do. + if (TerminationRequested() || isolate_->IsExecutionTerminating() || IsStopped()) { return PumpResult::kTerminated; } if (settled()) { return PumpResult::kSettled; } - if (IsStopped()) { - // a stopped loop drops every post, so nothing can settle anymore - return PumpResult::kTerminated; - } - if (std::chrono::steady_clock::now() >= deadline) { + if (nativescript::common::DeadlinePassed(deadline)) { return PumpResult::kDeadline; } - RunDueInternalWork(drainLooperWork ? DrainFilter::kPumpDeliverable - : DrainFilter::kNestableV8); + if (mode == PumpMode::kNestableOnly) { + { + v8::Locker locker(isolate_); + v8::Isolate::Scope isolateScope(isolate_); + v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_); + RunDueInternalWork(DrainFilter::kNestableV8); + } + if (settled()) { + // back through the loop head, where termination outranks the + // settlement this drain produced + continue; + } + if (idle != nullptr) { + idle(kQuietPumpPollMs); + } else { + WaitForInternalWork(kQuietPumpPollMs); + } + continue; + } + RunDueInternalWork(platformWork ? DrainFilter::kPumpDeliverable + : DrainFilter::kNestableV8); { // work may enqueue microtasks without entering JS; scopes are // re-entrant, so callers already holding them pay nothing @@ -775,54 +803,18 @@ EventLoop::PumpResult EventLoop::PumpUntil(double deadlineSeconds, isolate_->PerformMicrotaskCheckpoint(); } int ranLooperWork = 0; - if (drainLooperWork) { + if (platformWork) { ranLooperWork = RunDueOrderedEntries(); if (pumpDrainHook_ != nullptr) { ranLooperWork += pumpDrainHook_(); } } if (settled()) { - // back through the loop head, where termination outranks the - // settlement this drain produced continue; } if (ranLooperWork == 0) { - WaitForInternalWork(10, /*pumpDeliverable=*/drainLooperWork); - } - } -} - -EventLoop::PumpResult EventLoop::PumpNestableV8TasksUntil( - double deadlineSeconds, const std::function& settled, - const std::function& idle) { - NS_DCHECK(looper_ == nullptr || ALooper_forThread() == looper_); - PumpScope pumpScope; - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::duration(deadlineSeconds); - for (;;) { - if (terminationRequested_.load(std::memory_order_acquire) || - isolate_->IsExecutionTerminating()) { - return PumpResult::kTerminated; - } - if (settled()) { - return PumpResult::kSettled; - } - if (IsStopped()) { - return PumpResult::kTerminated; - } - if (std::chrono::steady_clock::now() >= deadline) { - return PumpResult::kDeadline; - } - { - v8::Locker locker(isolate_); - v8::Isolate::Scope isolateScope(isolate_); - v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_); - RunDueInternalWork(DrainFilter::kNestableV8); - } - if (settled()) { - continue; + WaitForInternalWork(10, /*pumpDeliverable=*/platformWork); } - idle(kQuietPumpPollMs); } } @@ -946,6 +938,9 @@ extern "C" JNIEXPORT void JNICALL Java_com_tns_EventLoopHandler_nativeRunTask( loop->ReportDeferredJavaError(); } catch (tns::NativeScriptException& e) { e.ReThrowToJava(); + } catch (nativescript::common::JsError& e) { + tns::NativeScriptException(e.message()).ReThrowToJava(); + } catch (nativescript::common::Terminated&) { } catch (std::exception& e) { std::string msg = std::string("Error: c++ exception: ") + e.what(); tns::NativeScriptException nsEx(msg); diff --git a/test-app/runtime/src/main/cpp/EventLoop.h b/test-app/runtime/src/main/cpp/EventLoop.h index 8beecffe6..88fc1edb2 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.h +++ b/test-app/runtime/src/main/cpp/EventLoop.h @@ -14,6 +14,8 @@ #include #include "v8.h" #include "v8-platform.h" +#include "ns/Deadline.h" +#include "ns/Loop.h" namespace tns { @@ -76,11 +78,11 @@ class OrderedTaskSource { * sibling, possibly on this loop), so Shutdown moves the lanes out and lets * them die after the unlock. */ -class EventLoop { +class EventLoop : public nativescript::common::Loop { public: explicit EventLoop(v8::Isolate* isolate) : isolate_(isolate) {} - ~EventLoop(); + ~EventLoop() override; /** * Attaches both lanes to the calling thread (Java handler on the thread's @@ -157,8 +159,8 @@ class EventLoop { void SetTimerSource(OrderedTaskSource* source); // internal lane: runs on the home thread as soon as the looper polls - void PostInternal(std::function fn); - void PostInternalDelayed(std::function fn, double delayMs); + bool PostInternal(std::function fn) override; + bool PostInternalDelayed(std::function fn, double delayMs) override; /** * Internal-lane post whose fn does its OWN isolate ceremony: RunEntry @@ -172,15 +174,16 @@ class EventLoop { /** * Posts a v8 foreground task into the internal lane. Called by the - * platform's per-isolate v8::TaskRunner adapter, from any thread. + * platform's per-isolate v8::TaskRunner adapter, from any thread. False, + * with the task dropped, once the loop has stopped. */ - void PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds); + bool PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds) override; /** * True once Shutdown ran. A stopped loop found in the platform registry * for a (reused) isolate pointer is stale and must be replaced. */ - bool IsStopped(); + bool IsStopped() override; /** * Runs the internal-lane v8 tasks that are due and nestable, bounded to @@ -189,7 +192,7 @@ class EventLoop { * non-nestable tasks and plain function posts stay queued and run from * their own wakeups after the loop unwinds. */ - void RunNestableV8Tasks(); + void RunNestableV8Tasks() override; /** * True while this loop's home thread is inside one of the loop's ALooper @@ -197,23 +200,27 @@ class EventLoop { * Looper::pollInner holds a Response& into its response vector across * each callback; a nested ALooper_pollOnce on the same looper clears and * reallocates that vector, so the outer poll resumes over freed memory. Any code that pumps the looper (module - * evaluation, the boot backstop, the fetch yield) must consult this and + * evaluation, the boot hold, the fetch yield) must consult this and * drain queues directly instead of polling when it is set. */ bool IsInLooperCallback() const { return looperCallbackDepth_ > 0; } /** * Marks this loop's isolate as termination-requested. Callable from any - * thread. Pumps consult it alongside Isolate::IsExecutionTerminating, - * which per its contract is true only while JS frames are unwinding with - * the termination exception active - a pump parked with nothing queued - * never runs JS, so TerminateExecution alone cannot end it before the - * deadline. + * thread, and called before the isolate's TerminateExecution. Pumps + * consult it alongside Isolate::IsExecutionTerminating, which per its + * contract is true only while JS frames are unwinding with the + * termination exception active - a pump parked with nothing queued never + * runs JS, so TerminateExecution alone cannot end it before the deadline. */ void NoteTerminationRequested() { terminationRequested_.store(true, std::memory_order_release); } + bool TerminationRequested() const override { + return terminationRequested_.load(std::memory_order_acquire); + } + /** * Blocks the calling thread until this loop's internal lane has work (the * eventfd or timerfd is readable) or `timeoutMs` elapses, whichever comes @@ -240,52 +247,37 @@ class EventLoop { */ int RunDueOrderedEntries(); - enum class PumpResult { kSettled, kDeadline, kTerminated }; - /** - * Drives this loop in place on the home thread until `settled()` returns - * true or `deadlineSeconds` elapses, idling in WaitForInternalWork - * between slices. The one pump primitive behind module evaluation, the - * graph walk, and the boot backstop; `settled` may throw and the - * exception propagates. Returns kTerminated when the isolate is - * terminating or the loop has been shut down. - * - * `drainLooperWork` picks what a pump iteration runs, mirroring the iOS - * pump's pumpRunLoop split: - * - false: nestable v8 tasks and a microtask checkpoint only, exactly - * like the inspector pause loops (iOS's default pump body). - * - true (the looper-equivalent drain, standing in for iOS's runloop - * slice): additionally runs due ordered-lane work (JS timers included) - * and plain internal-lane posts (worker->parent messages, Node-API - * completions), plus the registered pump drain hook. Non-nestable v8 - * tasks stay queued in both modes (the v8 nestability contract: JS - * frames are on the stack throughout), and so do bare posts - their - * fns lock a DIFFERENT isolate, and running one under a caller - * holding this isolate's Locker nests Lockers across isolates. + * Loop::PumpUntil. What each mode runs per slice: + * - kNestableOnly: nestable v8 tasks with microtasks suppressed, then + * `idle(kQuietPumpPollMs)` (WaitForInternalWork when `idle` is null). + * No timer, plain post, worker message or promise job runs inside it. + * V8 asks for the GC a background compile is blocked on with a + * nestable PostTask, which only the next slice runs - hence the bound + * on `idle`. + * - kV8Tasks: nestable v8 tasks and a microtask checkpoint, exactly like + * the inspector pause loops; idles in WaitForInternalWork. + * - kPlatformWork: additionally due ordered-lane work (JS timers + * included), plain internal-lane posts (worker->parent messages, + * Node-API completions) and the registered pump drain hook. + * Non-nestable v8 tasks stay queued in every mode (the v8 nestability + * contract: JS frames are on the stack throughout), and so do bare posts + * - their fns lock a DIFFERENT isolate, and running one under a caller + * holding this isolate's Locker nests Lockers across isolates. */ - PumpResult PumpUntil(double deadlineSeconds, const std::function& settled, - bool drainLooperWork); + nativescript::common::PumpResult PumpUntil( + const nativescript::common::Deadline& deadline, const std::function& settled, + nativescript::common::PumpMode mode, + const std::function& idle = nullptr) override; - /** - * A quieter PumpUntil for waits whose completions all arrive as nestable - * v8 tasks: each iteration runs only those, with microtasks suppressed, - * then calls `idle(kQuietPumpPollMs)` instead of waiting on the looper's - * fds. No timer, plain post, worker message or promise job runs inside - * it. `idle` must return within that bound even when nothing signals it: - * V8 asks for the GC a background compile is blocked on with a nestable - * PostTask, which only the next iteration runs. - */ static constexpr int kQuietPumpPollMs = 2; - PumpResult PumpNestableV8TasksUntil(double deadlineSeconds, - const std::function& settled, - const std::function& idle); /** * True on the thread BindToCurrentThread ran on. Any thread may ask: with * multithreaded JavaScript, JS also runs on threads that only hold the * isolate's Locker, and those must not wait on work this loop delivers. */ - bool IsOnHomeThread() const; + bool IsOnHomeThread() const override; /** * True while the calling thread is inside PumpUntil. Callback code that @@ -439,7 +431,7 @@ class EventLoop { Lane internal_; Lane ordered_; std::atomic claimCells_[kClaimCells] = {}; - // Set by NoteTerminationRequested (any thread), read by PumpUntil. + // Set by NoteTerminationRequested (any thread), read by the pumps. std::atomic_bool terminationRequested_{false}; // Depth, not a flag: an fd callback can dispatch JS that lands back in // another callback through a nested drain. Home thread only, like the fd diff --git a/test-app/runtime/src/main/cpp/File.cpp b/test-app/runtime/src/main/cpp/File.cpp index da5c6b737..9f3d59d59 100644 --- a/test-app/runtime/src/main/cpp/File.cpp +++ b/test-app/runtime/src/main/cpp/File.cpp @@ -20,47 +20,6 @@ using namespace std; namespace tns { -string File::ReadText(const string& filePath) { - bool ok; - return ReadText(filePath, ok); -} - -string File::ReadText(const string& filePath, bool& ok) { - ok = false; - - FILE* file = fopen(filePath.c_str(), READ_BINARY); - if (file == nullptr) { - // A path that never existed, or one deleted between a caller's stat and - // this open. Callers surface their own error; reading on regardless - // aborts the process on a null FILE*. - DEBUG_WRITE_FORCE("File::ReadText: cannot open %s", filePath.c_str()); - return string(); - } - - fseek(file, 0, SEEK_END); - auto size = ftell(file); - if (size < 0) { - DEBUG_WRITE_FORCE("File::ReadText: cannot size %s", filePath.c_str()); - fclose(file); - return string(); - } - rewind(file); - - // Read straight into the string that is returned: main and worker runtimes - // read modules concurrently from their own threads, so there is no scratch - // buffer to share, and the caller needs a string either way. - string content(static_cast(size), '\0'); - auto bytesRead = fread(content.data(), 1, static_cast(size), file); - fclose(file); - - // A short read is a truncated file, not a failure to open; `size` is only - // what the directory entry claimed. - content.resize(bytesRead); - - ok = true; - return content; -} - void* File::ReadBinary(const string& filePath, int& length) { length = 0; @@ -77,9 +36,8 @@ void* File::ReadBinary(const string& filePath, int& length) { } rewind(file); - // A file truncated after the size was taken reads short. Callers hand the - // buffer to consumers that trust its length (V8 does not checksum code - // caches in release builds), so it is all of the file or nothing. + // A file truncated after the size was taken reads short; callers get all + // of the file or nothing. uint8_t* data = new uint8_t[size]; auto bytesRead = fread(data, sizeof(uint8_t), size, file); fclose(file); @@ -92,46 +50,5 @@ void* File::ReadBinary(const string& filePath, int& length) { return data; } -bool File::WriteBinary(const string& filePath, const void* data, int length, time_t modificationTime) { - // Exclusive creation in the target's directory, so concurrent writers of - // the same path never share a temporary and rename stays on one file system. - string tempPath(filePath); - tempPath.append(".ns-XXXXXX"); - int fd = mkstemp(tempPath.data()); - if (fd < 0) { - return false; - } - - bool ok = length >= 0; - auto cursor = static_cast(data); - size_t remaining = ok ? static_cast(length) : 0; - while (ok && remaining > 0) { - ssize_t written = write(fd, cursor, remaining); - if (written < 0) { - ok = errno == EINTR; - continue; - } - cursor += written; - remaining -= static_cast(written); - } - - if (ok && modificationTime >= 0) { - struct timespec times[2]; - times[0].tv_sec = 0; - times[0].tv_nsec = UTIME_NOW; - times[1].tv_sec = modificationTime; - times[1].tv_nsec = 0; - ok = futimens(fd, times) == 0; - } - - ok = (close(fd) == 0) && ok; - ok = ok && rename(tempPath.c_str(), filePath.c_str()) == 0; - if (!ok) { - unlink(tempPath.c_str()); - } - - return ok; -} - const char* File::READ_BINARY = "rb"; } diff --git a/test-app/runtime/src/main/cpp/File.h b/test-app/runtime/src/main/cpp/File.h index 6e3f4a0bd..f045079f3 100644 --- a/test-app/runtime/src/main/cpp/File.h +++ b/test-app/runtime/src/main/cpp/File.h @@ -8,25 +8,11 @@ #ifndef JNI_FILE_H_ #define JNI_FILE_H_ -#include #include namespace tns { class File { public: - static std::string ReadText(const std::string& filePath); - /* - * `ok` distinguishes a file that could not be opened from one that is - * genuinely empty — the plain overload renders both as "". - */ - static std::string ReadText(const std::string& filePath, bool& ok); - /* - * Replaces the file atomically: readers of `filePath` see the previous - * file or the complete new one, never a partial write. A non-negative - * `modificationTime` becomes the file's mtime before it is published. - */ - static bool WriteBinary(const std::string& filePath, const void* inData, int length, - time_t modificationTime = -1); /* * The whole file in a buffer the caller frees with delete[], or * nullptr (length 0) when it cannot be read in full. diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index a0433ced8..7d3e9b38c 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -1,174 +1,46 @@ #include "HttpLoader.h" -#include - #include #include -#include -#include -#include -#include #include +#include #include -#include #include #include #include "ArgConverter.h" #include "ExactUtf8.h" #include "JEnv.h" -// CanonicalizeHttpUrlKey reads the calling isolate's canonicalization -// vocabulary — the one loader dependency here. -#include "ModuleInternalCallbacks.h" #include "ModuleUrl.h" #include "NativeScriptException.h" #include "Runtime.h" #include "TraceLog.h" +#include "ns/http/ModuleTransport.h" +// CanonicalizeHttpUrlKey reads the calling isolate's canonicalization +// vocabulary — the one loader dependency here. +#include "ns/loader/LoaderState.h" namespace tns { -static inline bool StartsWith(const std::string& s, const char* prefix) { - size_t n = strlen(prefix); - return s.size() >= n && s.compare(0, n, prefix) == 0; -} +namespace http = nativescript::common::http; -// ───────────────────────────────────────────────────────────── -// Remote-module security gate - -static std::once_flag s_securityConfigInitFlag; -static bool s_allowRemoteModules = false; -static RemoteModuleAllowlist s_remoteModuleAllowlist; -static bool s_isDebuggable = false; - -static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::string& entry) { - if (entry.empty()) return false; - if (url.size() < entry.size()) return false; - if (url.compare(0, entry.size(), entry) != 0) return false; - if (url.size() == entry.size()) return true; - if (entry.back() == '/') return true; - const char next = url[entry.size()]; - return next == '/' || next == '?' || next == '#'; -} - -static std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { - const std::string url = NormalizeHttpModuleUrl(entry); - return url.empty() ? entry : url; -} - -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( - const std::optional>>& items) { - RemoteModuleAllowlist allowlist; - if (!items.has_value() || items->empty()) { - return allowlist; - } - allowlist.inForce = true; - for (const std::optional& item : *items) { - if (item.has_value() && !item->empty()) { - allowlist.entries.push_back(NormalizeRemoteModuleAllowlistEntry(*item)); - } - } - return allowlist; -} - -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist) { - if (!allowlist.inForce) { - return true; - } - for (const std::string& entry : allowlist.entries) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - return false; -} - -static void InitializeSecurityConfig() { - std::call_once(s_securityConfigInitFlag, []() { - // Remote modules are enabled only after the allowlist was read in - // full: a failure part way keeps them disabled rather than enabling - // them with a list cut short. +bool IsDebuggable() { + static std::once_flag once; + static bool debuggable = false; + std::call_once(once, [] { + JEnv env; try { - JEnv env; jclass runtimeClass = env.FindClass("com/tns/Runtime"); - if (runtimeClass == nullptr) { - return; - } - - jmethodID isDebuggableMid = env.GetStaticMethodID(runtimeClass, "isDebuggable", "()Z"); - if (isDebuggableMid != nullptr) { - s_isDebuggable = env.CallStaticBooleanMethod(runtimeClass, isDebuggableMid) == - JNI_TRUE; - } - - if (s_isDebuggable) { - s_allowRemoteModules = true; - return; - } - - bool allowRemoteModules = false; - jmethodID allowRemoteMid = - env.GetStaticMethodID(runtimeClass, "isRemoteModulesAllowed", "()Z"); - if (allowRemoteMid != nullptr) { - allowRemoteModules = - env.CallStaticBooleanMethod(runtimeClass, allowRemoteMid) == JNI_TRUE; + if (runtimeClass != nullptr) { + jmethodID mid = env.GetStaticMethodID(runtimeClass, "isDebuggable", "()Z"); + debuggable = env.CallStaticBooleanMethod(runtimeClass, mid) == JNI_TRUE; } - - // Null when the list is not in force; a null element stands for an - // item that is not a string. - std::optional>> items; - jmethodID getAllowlistMid = env.GetStaticMethodID( - runtimeClass, "getRemoteModuleAllowlist", "()[Ljava/lang/String;"); - if (getAllowlistMid == nullptr) { - return; - } - jobjectArray allowlistArray = static_cast( - env.CallStaticObjectMethod(runtimeClass, getAllowlistMid)); - if (allowlistArray != nullptr) { - items.emplace(); - jsize len = env.GetArrayLength(allowlistArray); - for (jsize i = 0; i < len; i++) { - jstring jstr = - static_cast(env.GetObjectArrayElement(allowlistArray, i)); - items->push_back(ToExactUtf8(env, jstr)); - if (jstr != nullptr) { - env.DeleteLocalRef(jstr); - } - } - env.DeleteLocalRef(allowlistArray); - } - - s_remoteModuleAllowlist = RemoteModuleAllowlistFromConfig(items); - s_allowRemoteModules = allowRemoteModules; } catch (...) { - // Keep defaults (remote modules disabled) + // Not debuggable. } + static_cast(env)->ExceptionClear(); }); -} - -bool IsDebuggable() { - InitializeSecurityConfig(); - return s_isDebuggable; -} - -bool IsRemoteModulesAllowed() { - if (IsDebuggable()) { - return true; - } - InitializeSecurityConfig(); - return s_allowRemoteModules; -} - -bool IsRemoteUrlAllowed(const std::string& url) { - if (IsDebuggable()) { - return true; - } - - InitializeSecurityConfig(); - if (!s_allowRemoteModules) { - return false; - } - - return RemoteUrlAllowedByAllowlist(url, s_remoteModuleAllowlist); + return debuggable; } // ───────────────────────────────────────────────────────────── @@ -180,97 +52,21 @@ std::string CanonicalizeHttpUrlKey(const std::string& url) { } std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { - size_t hashPos = normalizedUrl.find('#'); - std::string noHash = - (hashPos == std::string::npos) ? normalizedUrl : normalizedUrl.substr(0, hashPos); - - size_t schemePos = noHash.find("://"); - if (schemePos == std::string::npos) { - size_t q = noHash.find('?'); - return (q == std::string::npos) ? noHash : noHash.substr(0, q); - } - size_t pathStart = noHash.find('/', schemePos + 3); - if (pathStart == std::string::npos) { - return noHash; - } - size_t qPos = noHash.find('?', pathStart); - std::string originAndPath = (qPos == std::string::npos) ? noHash : noHash.substr(0, qPos); - std::string query = (qPos == std::string::npos) ? std::string() : noHash.substr(qPos + 1); - - // This key is the module registry/cache key. For general-purpose HTTP - // module loading the query can be part of a module's identity (auth, - // content versioning, routing), so query normalization applies only to the - // endpoints the client names, through the vocabulary it supplies. - // - // `preserveQueryFor` is checked BEFORE the dev-endpoint prefix test, so it - // covers endpoints nested under a dev prefix: for some endpoints the query - // IS the identity, and stripping it would collapse every refetch onto the - // boot-time key. - // - // Until a client supplies that vocabulary, canonicalization is purely - // mechanical: the fragment is gone and the query stays. Which params are - // cache-busters and which paths are dev endpoints is knowledge only the - // client has; guessing would silently collapse two distinct modules onto - // one registry key. - const CanonicalizationConfig* canon = CanonicalizationConfigForCurrentIsolate(); - if (canon == nullptr) { - return noHash; - } - { - std::string pathOnly = originAndPath.substr(pathStart); - for (const auto& p : canon->preserveQueryPrefixes) { - if (!p.empty() && pathOnly.find(p) != std::string::npos) { - return noHash; - } - } - bool isDevEndpoint = false; - for (const auto& p : canon->devPathPrefixes) { - if (!p.empty() && StartsWith(pathOnly, p.c_str())) { - isDevEndpoint = true; - break; - } - } - if (!isDevEndpoint) { - return noHash; - } - } - - if (query.empty()) return originAndPath; - - std::vector kept; - size_t start = 0; - while (start <= query.size()) { - size_t amp = query.find('&', start); - std::string pair = - (amp == std::string::npos) ? query.substr(start) : query.substr(start, amp - start); - if (!pair.empty()) { - size_t eq = pair.find('='); - std::string name = (eq == std::string::npos) ? pair : pair.substr(0, eq); - const bool drop = std::find(canon->stripParams.begin(), canon->stripParams.end(), - name) != canon->stripParams.end(); - if (!drop) kept.push_back(pair); - } - if (amp == std::string::npos) break; - start = amp + 1; - } - if (kept.empty()) return originAndPath; - std::sort(kept.begin(), kept.end()); - std::string rebuilt = originAndPath + "?"; - for (size_t i = 0; i < kept.size(); i++) { - if (i > 0) rebuilt += "&"; - rebuilt += kept[i]; - } - return rebuilt; + return http::CanonicalizeNormalizedHttpUrlKey( + normalizedUrl, + nativescript::common::loader::CanonicalizationConfigFor(v8::Isolate::TryGetCurrent())); } // ───────────────────────────────────────────────────────────── -// JNI fetch diagnostics + request builder +// The transport: one attempt over OkHttp or HttpURLConnection + +namespace { // Describes and clears a pending Java exception. The introspection calls go // through the raw JNIEnv: JEnv's wrappers turn a pending Java exception into a // thrown NativeScriptException, which here would replace the exception being // described with the failure to describe it. -static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std::string& outMessage) { +bool DrainPendingJniException(JEnv& env, std::string& outClassName, std::string& outMessage) { outClassName.clear(); outMessage.clear(); JNIEnv* raw = env; @@ -304,74 +100,6 @@ static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std:: return true; } -static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool useCache, - std::string& out, std::string& contentType, int& status); - -// ── The HTTP module cache switch ───────────────────────────── - -static std::once_flag s_moduleHttpCacheInitFlag; -static std::atomic s_moduleHttpCacheSetting{true}; -static std::atomic s_moduleHttpCacheInspectorDisables{0}; - -// The app config's and launch options' answer, read once. Every writer of the -// setting runs this first, so a later first read cannot overwrite a setter. -static void InitializeModuleHttpCacheSetting() { - std::call_once(s_moduleHttpCacheInitFlag, []() { - try { - JEnv env; - jclass cls = env.FindClass("com/tns/ModuleHttpCache"); - if (cls == nullptr) { - env.ExceptionClear(); - return; - } - jmethodID mid = env.GetStaticMethodID(cls, "isEnabledAtStartup", "()Z"); - if (mid == nullptr) { - env.ExceptionClear(); - return; - } - s_moduleHttpCacheSetting.store(env.CallStaticBooleanMethod(cls, mid) == JNI_TRUE); - } catch (...) { - // Enabled. - } - }); -} - -bool ModuleHttpCacheEnabled() { - InitializeModuleHttpCacheSetting(); - return s_moduleHttpCacheSetting.load() && s_moduleHttpCacheInspectorDisables.load() == 0; -} - -void SetModuleHttpCacheEnabled(bool enabled) { - InitializeModuleHttpCacheSetting(); - s_moduleHttpCacheSetting.store(enabled); -} - -void AddModuleHttpCacheInspectorDisable(int delta) { - InitializeModuleHttpCacheSetting(); - s_moduleHttpCacheInspectorDisables.fetch_add(delta); -} - -void ClearModuleHttpCache() { - JEnv env; - jclass cls = env.FindClass("com/tns/ModuleHttpCache"); - if (cls == nullptr) { - // Takes the ClassNotFoundException FindClass left pending. - throw NativeScriptException(env); - } - jmethodID mid = env.GetStaticMethodID(cls, "clear", "()V"); - env.CallStaticVoidMethod(cls, mid); -} - -// Each module-fetch attempt's connect timeout and read timeout, for both -// transports, matching iOS. Debug builds talk to dev servers that transform -// cold modules on demand (measured at 5-9 s); release builds fetch remote -// modules that should fail fast. -static int ModuleFetchTimeoutMs() { - return IsDebuggable() ? 30000 : 5000; -} - -static constexpr std::chrono::milliseconds kModuleFetchRetryDelay{120}; - // A blocking network call on the JS thread is exactly what StrictMode is meant // to flag, so the fetch relaxes the thread policy — but the policy belongs to // the app, not to this request: whatever runs next on this thread must get its @@ -448,189 +176,54 @@ struct StrictModeScope { } }; -// ── The module response policy ─────────────────────────────── -// -// Module scripts are strict about MIME: the HTML spec's "fetch a single module -// script" fails the fetch outright for anything that is not a JavaScript or -// JSON MIME type, where a classic script would sniff and run it anyway. That -// strictness is the whole point — an SPA dev server answering an unknown path -// with `200 text/html` should say so, not hand HTML to the parser and produce -// `Unexpected token '<'` from somewhere deep in the graph. -// -// Both transports classify here, so the synchronous fallback and the async -// walk cannot disagree about what a response means. - -// "text/javascript; charset=utf-8" → "text/javascript": parameters stripped, -// trimmed, lowercased. -static std::string MimeEssence(const std::string& contentType) { - size_t semi = contentType.find(';'); - std::string essence = - semi == std::string::npos ? contentType : contentType.substr(0, semi); - size_t begin = essence.find_first_not_of(" \t"); - if (begin == std::string::npos) { - return ""; +// Alternating header names and values, in order; null, with nothing pending, +// when the array could not be built. +jobjectArray NewHeaderArray(JEnv& env, const std::vector& headers) { + JNIEnv* raw = env; + jclass clsString = env.FindClass("java/lang/String"); + if (clsString == nullptr) { + raw->ExceptionClear(); + return nullptr; } - size_t end = essence.find_last_not_of(" \t"); - essence = essence.substr(begin, end - begin + 1); - for (char& c : essence) { - c = (char)tolower((unsigned char)c); + jobjectArray array = + raw->NewObjectArray(static_cast(headers.size() * 2), clsString, nullptr); + if (array == nullptr) { + raw->ExceptionClear(); + return nullptr; } - return essence; -} - -// The HTML spec's JavaScript MIME type essence list, verbatim. -static bool IsJavaScriptMimeEssence(const std::string& essence) { - static const char* const kJavaScriptEssences[] = {"application/ecmascript", - "application/javascript", - "application/x-ecmascript", - "application/x-javascript", - "text/ecmascript", - "text/javascript", - "text/javascript1.0", - "text/javascript1.1", - "text/javascript1.2", - "text/javascript1.3", - "text/javascript1.4", - "text/javascript1.5", - "text/jscript", - "text/livescript", - "text/x-ecmascript", - "text/x-javascript"}; - for (const char* candidate : kJavaScriptEssences) { - if (essence == candidate) { - return true; + jsize index = 0; + for (const http::RequestHeader& header : headers) { + for (const std::string* text : {&header.name, &header.value}) { + jstring jText = raw->NewStringUTF(text->c_str()); + if (jText == nullptr) { + raw->ExceptionClear(); + return nullptr; + } + raw->SetObjectArrayElement(array, index++, jText); + raw->DeleteLocalRef(jText); } } - return false; -} - -// A JSON MIME type is application/json, text/json, or any `+json` subtype. -static bool IsJsonMimeEssence(const std::string& essence) { - if (essence == "application/json" || essence == "text/json") { - return true; - } - const std::string suffix = "+json"; - return essence.size() > suffix.size() && - essence.compare(essence.size() - suffix.size(), suffix.size(), suffix) == 0; + return array; } -// `transportOk` means a response arrived at all; everything else about it — -// status, MIME, emptiness — is policy decided here. `body` is moved into the -// result on success. -static void ClassifyModuleResponse(const std::string& url, bool transportOk, int status, - const std::string& contentType, std::string& body, - ModuleFetchResult& result) { - result.status = status; - result.contentType = contentType; - - if (!transportOk) { - result.failureReason = "HTTP import failed: " + url + " (network error)"; - return; - } - if (status == 204 || status == 205) { - // "No content" carries no module, which the web treats as a network - // error for a module script rather than as an empty module. - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + - ", no content)"; - return; - } - if (status < 200 || status >= 300) { - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + ")"; - return; - } - - const std::string essence = MimeEssence(contentType); - if (essence.empty()) { - result.failureReason = - "Expected a JavaScript module but '" + url + "' responded with no MIME type"; - return; +// The strings of a Java String[], null elements skipped. +std::vector StringArrayValues(JNIEnv* raw, jobjectArray array) { + std::vector values; + if (array == nullptr) { + return values; } - - if (IsJsonMimeEssence(essence)) { - if (body.empty()) { - result.failureReason = - "Expected a JSON module but '" + url + "' responded with an empty body"; - return; - } - result.kind = ModuleResponseKind::kJson; - } else if (IsJavaScriptMimeEssence(essence)) { - result.kind = ModuleResponseKind::kJavaScript; - // An empty 2xx JavaScript body is a valid module: type-only TypeScript - // modules transform to zero runtime code and dev servers serve them as - // empty 200s. Failing here would kill the whole graph with a misleading - // "status=200". - if (body.empty()) { - body = "export {};\n"; - TNS_DEBUG(Esm, "[http-loader] empty 2xx body for %s — serving canonical empty module", - url.c_str()); + const jsize length = raw->GetArrayLength(array); + for (jsize i = 0; i < length; i++) { + auto value = static_cast(raw->GetObjectArrayElement(array, i)); + if (value != nullptr) { + values.push_back(ArgConverter::jstringToString(value)); + raw->DeleteLocalRef(value); } - } else { - result.failureReason = "Expected a JavaScript module but '" + url + - "' responded with MIME type '" + essence + "'"; - return; } - - result.ok = true; - result.body = std::move(body); + return values; } -bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { - result = ModuleFetchResult(); - - // Security gate: the single point of enforcement for all HTTP module - // loading, checked before any network turn. - if (!IsRemoteUrlAllowed(url)) { - result.status = 403; - result.failureReason = - "HTTP import blocked: remote module loading is not allowed for " + url; - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - return false; - } - - const bool urlLogEnabled = LogCategoryEnabled(LogCategory::Fetch); - const auto netStart = urlLogEnabled ? std::chrono::steady_clock::now() - : std::chrono::steady_clock::time_point{}; - - std::string body; - std::string contentType; - int status = 0; - const int timeoutMs = ModuleFetchTimeoutMs(); - const bool useCache = ModuleHttpCacheEnabled(); - bool transportOk = - PerformHttpFetchOnceSync(url, timeoutMs, useCache, body, contentType, status); - if (!transportOk) { - // One retry, and only for a transport error: an HTTP status is an - // answer, not a failure to communicate, so asking again would just - // repeat it. - TNS_DEBUG(Esm, "[http-loader] retrying %s after initial fetch error", url.c_str()); - std::this_thread::sleep_for(kModuleFetchRetryDelay); - transportOk = PerformHttpFetchOnceSync(url, timeoutMs, useCache, body, contentType, status); - } - - ClassifyModuleResponse(url, transportOk, status, contentType, body, result); - - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-sync][reject] %s", result.failureReason.c_str()); - return false; - } - - TNS_DEBUG(Esm, "[http-loader] fetched status=%d content-type=%s bytes=%llu", result.status, - result.contentType.empty() ? "" : result.contentType.c_str(), - (unsigned long long)result.body.size()); - if (urlLogEnabled) { - const auto netMs = std::chrono::duration_cast( - std::chrono::steady_clock::now() - netStart) - .count(); - TNS_DEBUG(Fetch, "[http-loader][fetch][network] %s bytes=%lu ms=%lld", url.c_str(), - (unsigned long)result.body.size(), (long long)netMs); - } - - return true; -} - -// ── OkHttp transport (see ActiveModuleTransportName) ───────── +// ── OkHttp ────────────────────────────────────────────────── struct OkHttpBridge { jclass fetcher = nullptr; @@ -638,14 +231,16 @@ struct OkHttpBridge { jfieldID status = nullptr; jfieldID contentType = nullptr; jfieldID body = nullptr; + jfieldID finalUrl = nullptr; + jfieldID clearSiteData = nullptr; }; -static std::atomic s_forcePlatformTransport{false}; -static std::atomic s_okHttpIncompatible{false}; +std::atomic s_forcePlatformTransport{false}; +std::atomic s_okHttpIncompatible{false}; // Null when the app does not ship OkHttp. isAvailable() is the first call into // the bridge: nothing else there may run without okhttp3. -static const OkHttpBridge* OkHttpBridgeIfAvailable() { +const OkHttpBridge* OkHttpBridgeIfAvailable() { static std::once_flag once; static OkHttpBridge bridge; static bool available = false; @@ -670,13 +265,19 @@ static const OkHttpBridge* OkHttpBridgeIfAvailable() { return; } bridge.fetch = raw->GetStaticMethodID( - fetcher, "fetch", "(Ljava/lang/String;IIIZ)Lcom/tns/OkHttpModuleFetcher$Result;"); + fetcher, "fetch", + "(Ljava/lang/String;[Ljava/lang/String;IIZ)Lcom/tns/OkHttpModuleFetcher$Result;"); bridge.status = bridge.fetch ? raw->GetFieldID(result, "status", "I") : nullptr; bridge.contentType = bridge.status ? raw->GetFieldID(result, "contentType", "Ljava/lang/String;") : nullptr; bridge.body = bridge.contentType ? raw->GetFieldID(result, "body", "[B") : nullptr; - if (!bridge.body) { + bridge.finalUrl = + bridge.body ? raw->GetFieldID(result, "finalUrl", "Ljava/lang/String;") : nullptr; + bridge.clearSiteData = bridge.finalUrl ? raw->GetFieldID(result, "clearSiteData", + "[Ljava/lang/String;") + : nullptr; + if (!bridge.clearSiteData) { raw->ExceptionClear(); return; } @@ -689,7 +290,7 @@ static const OkHttpBridge* OkHttpBridgeIfAvailable() { return available ? &bridge : nullptr; } -static const OkHttpBridge* ActiveOkHttpBridge() { +const OkHttpBridge* ActiveOkHttpBridge() { if (s_forcePlatformTransport.load(std::memory_order_relaxed) || s_okHttpIncompatible.load(std::memory_order_relaxed)) { return nullptr; @@ -697,14 +298,6 @@ static const OkHttpBridge* ActiveOkHttpBridge() { return OkHttpBridgeIfAvailable(); } -const char* ActiveModuleTransportName() { - return ActiveOkHttpBridge() != nullptr ? "okhttp" : "platform"; -} - -void SetForcePlatformModuleTransport(bool force) { - s_forcePlatformTransport.store(force, std::memory_order_relaxed); -} - // The OkHttp counterpart of the HttpURLConnection exchange in // PerformHttpFetchOnceSync, with the same contract: false for a transport // failure, true once a status arrived. A failed body read only fails the @@ -712,25 +305,28 @@ void SetForcePlatformModuleTransport(bool force) { // Empty when the app's OkHttp turned out to lack a call the bridge makes; the // caller then fetches through HttpURLConnection. template -static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bridge, - const std::string& url, int timeoutMs, - bool useCache, std::string& out, std::string& contentType, - int& status, OnFailure recordStageFailure) { +std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bridge, + const http::AttemptRequest& request, + http::AttemptOutcome& outcome, + OnFailure recordStageFailure) { JNIEnv* raw = env; // The pool keeps at least as many idle connections as the most fetches // that can run at once, so a burst's connections all survive to be reused. const size_t maxIdle = std::max(ModuleFetchConcurrency(ModuleFetchHostClass::kLoopback), ModuleFetchConcurrency(ModuleFetchHostClass::kRemote)); - jstring jUrl = raw->NewStringUTF(url.c_str()); + jstring jUrl = raw->NewStringUTF(request.url.c_str()); if (jUrl == nullptr) { raw->ExceptionClear(); return false; } - jobject result = raw->CallStaticObjectMethod(bridge.fetcher, bridge.fetch, jUrl, - static_cast(timeoutMs), - static_cast(ModuleFetchTimeoutMs()), + jobjectArray jHeaders = NewHeaderArray(env, request.headers); + if (jHeaders == nullptr) { + return false; + } + jobject result = raw->CallStaticObjectMethod(bridge.fetcher, bridge.fetch, jUrl, jHeaders, + static_cast(request.timeout.count()), static_cast(maxIdle), - useCache ? JNI_TRUE : JNI_FALSE); + request.useCache ? JNI_TRUE : JNI_FALSE); { std::string excClass, excMsg; if (DrainPendingJniException(env, excClass, excMsg)) { @@ -743,26 +339,35 @@ static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bri return std::nullopt; } - status = raw->GetIntField(result, bridge.status); + outcome.status = raw->GetIntField(result, bridge.status); auto jct = static_cast(raw->GetObjectField(result, bridge.contentType)); if (jct != nullptr) { - contentType = ArgConverter::jstringToString(jct); + outcome.contentType = ArgConverter::jstringToString(jct); + } + auto jFinalUrl = static_cast(raw->GetObjectField(result, bridge.finalUrl)); + if (jFinalUrl != nullptr) { + outcome.finalUrl = ArgConverter::jstringToString(jFinalUrl); } + outcome.clearSiteData = StringArrayValues( + raw, static_cast(raw->GetObjectField(result, bridge.clearSiteData))); auto bytes = static_cast(raw->GetObjectField(result, bridge.body)); if (bytes == nullptr) { recordStageFailure("read-body", "", "the response body could not be read"); - return !(status >= 200 && status < 300); + return !(outcome.status >= 200 && outcome.status < 300); } const jsize len = raw->GetArrayLength(bytes); - out.resize(static_cast(len)); + outcome.body.resize(static_cast(len)); if (len > 0) { - raw->GetByteArrayRegion(bytes, 0, len, reinterpret_cast(&out[0])); + raw->GetByteArrayRegion(bytes, 0, len, reinterpret_cast(&outcome.body[0])); } return true; } -// Runs on whichever thread drives the fetch — the JS thread for the sync path, -// a detached background thread for the async one. +// ── One attempt ───────────────────────────────────────────── + +// Runs on whichever thread the core runs the attempt on — the JS thread for +// the synchronous fallback, a core fetch thread for the graph walk. True when +// the attempt arrived (AttemptOutcome::arrived). // // The network calls below go through the raw JNIEnv rather than JEnv's // wrappers: a wrapper converts a pending Java exception into a thrown @@ -770,18 +375,18 @@ static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bri // tells a status-bearing answer (an empty 404) apart from a transport failure, // and past the InputStream close. The wrappers stay on the setup calls, whose // failures have no per-stage verdict and are caught below. -// `timeoutMs` must be positive: HttpURLConnection reads 0 as no timeout. -static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool useCache, - std::string& out, std::string& contentType, int& status) { - out.clear(); - contentType.clear(); - status = 0; +// `request.timeout` must be positive: HttpURLConnection reads 0 as no timeout. +bool PerformHttpFetchOnceSync(const http::AttemptRequest& request, http::AttemptOutcome& outcome) { + const std::string& url = request.url; + const int timeoutMs = static_cast(request.timeout.count()); TNS_DEBUG(Esm, "[http-esm][fetch][enter] url=%s timeoutMs=%d", url.c_str(), timeoutMs); - auto recordStageFailure = [&url](const char* stage, const std::string& excClass, - const std::string& excMsg) { + auto recordStageFailure = [&url, &outcome](const char* stage, const std::string& excClass, + const std::string& excMsg) { TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=%s url=%s class=%s msg=%s", stage, url.c_str(), excClass.c_str(), excMsg.c_str()); + outcome.errorDescription = std::string("stage=") + stage + " class=" + excClass + + " msg=" + excMsg; }; JEnv env; @@ -809,9 +414,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool StrictModeScope strictMode(env); if (const OkHttpBridge* okhttp = ActiveOkHttpBridge()) { - if (std::optional fetched = PerformOkHttpFetch( - env, *okhttp, url, timeoutMs, useCache, out, contentType, status, - recordStageFailure)) { + if (std::optional fetched = + PerformOkHttpFetch(env, *okhttp, request, outcome, recordStageFailure)) { return *fetched; } } @@ -847,8 +451,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool jmethodID setReadTimeout = env.GetMethodID(clsConn, "setReadTimeout", "(I)V"); jmethodID setDoInput = env.GetMethodID(clsConn, "setDoInput", "(Z)V"); jmethodID setUseCaches = env.GetMethodID(clsConn, "setUseCaches", "(Z)V"); - jmethodID setReqProp = - env.GetMethodID(clsConn, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); + jmethodID addReqProp = + env.GetMethodID(clsConn, "addRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); env.CallVoidMethod(conn, setConnectTimeout, timeoutMs); env.CallVoidMethod(conn, setReadTimeout, timeoutMs); if (setDoInput) { @@ -859,18 +463,12 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool if (setUseCaches) { env.CallVoidMethod(conn, setUseCaches, JNI_FALSE); } - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Accept"), - env.NewStringUTF("application/javascript, text/javascript, */*;q=0.1")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Accept-Encoding"), - env.NewStringUTF("identity")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("User-Agent"), - env.NewStringUTF("NativeScript-HTTP-ESM")); - // This transport has no cache, but a proxy on the way may. - if (!useCache) { - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Cache-Control"), - env.NewStringUTF("no-cache")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Pragma"), - env.NewStringUTF("no-cache")); + for (const http::RequestHeader& header : request.headers) { + jstring jName = env.NewStringUTF(header.name.c_str()); + jstring jValue = env.NewStringUTF(header.value.c_str()); + env.CallVoidMethod(conn, addReqProp, jName, jValue); + env.DeleteLocalRef(jName); + env.DeleteLocalRef(jValue); } jclass clsHttp = env.FindClass("java/net/HttpURLConnection"); @@ -880,6 +478,7 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool jmethodID getErrorStream = isHttp ? env.GetMethodID(clsHttp, "getErrorStream", "()Ljava/io/InputStream;") : nullptr; + int& status = outcome.status; // Once a status line has been read the server has answered, and every // body-side failure below stops being a transport error: an empty 404 // is an answer, and reporting it as "network error" would both hide @@ -971,27 +570,48 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool env.CallVoidMethod(baos, baosClose); if (bytes) { jsize len = env.GetArrayLength(bytes); - out.resize(static_cast(len)); + outcome.body.resize(static_cast(len)); if (len > 0) { - env.GetByteArrayRegion(bytes, 0, len, reinterpret_cast(&out[0])); + env.GetByteArrayRegion(bytes, 0, len, + reinterpret_cast(&outcome.body[0])); } } else { readFailed = true; } } } - // Clear-Site-Data, now that the stream is closed, and whether or not - // the body arrived whole, as on the OkHttp transport. A failure here - // costs only the clear, never the module. + // The final URL and Clear-Site-Data, whether or not the body arrived + // whole, as on the OkHttp transport. A failure here costs only those, + // never the module. if (isHttp) { + // getURL() is the URL the redirects ended at. + jmethodID getURL = raw->GetMethodID(clsConn, "getURL", "()Ljava/net/URL;"); + jobject finalUrl = getURL ? raw->CallObjectMethod(conn, getURL) : nullptr; + raw->ExceptionClear(); + jmethodID urlToString = + finalUrl ? raw->GetMethodID(clsURL, "toString", "()Ljava/lang/String;") : nullptr; + auto jFinalUrl = urlToString + ? static_cast(raw->CallObjectMethod(finalUrl, urlToString)) + : nullptr; + raw->ExceptionClear(); + if (jFinalUrl != nullptr) { + outcome.finalUrl = ArgConverter::jstringToString(jFinalUrl); + } + jclass clsCache = env.FindClass("com/tns/ModuleHttpCache"); - jmethodID onResponse = - clsCache ? raw->GetStaticMethodID(clsCache, "onPlatformResponse", - "(Ljava/net/HttpURLConnection;)V") + jmethodID clearSiteDataValues = + clsCache ? raw->GetStaticMethodID(clsCache, "clearSiteDataValues", + "(Ljava/net/HttpURLConnection;)[Ljava/lang/String;") : nullptr; - if (onResponse) { - raw->CallStaticVoidMethod(clsCache, onResponse, conn); + auto values = clearSiteDataValues + ? static_cast( + raw->CallStaticObjectMethod(clsCache, clearSiteDataValues, conn)) + : nullptr; + if (raw->ExceptionCheck()) { + raw->ExceptionClear(); + values = nullptr; } + outcome.clearSiteData = StringArrayValues(raw, values); raw->ExceptionClear(); } @@ -1006,14 +626,12 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool env.GetMethodID(clsConn, "getContentType", "()Ljava/lang/String;"); jstring jct = static_cast(env.CallObjectMethod(conn, getContentType)); if (jct) { - contentType = ArgConverter::jstringToString(jct); + outcome.contentType = ArgConverter::jstringToString(jct); } if (status == 0) status = 200; // Pure transport: true means a response arrived. Whether that response - // is a usable module — status, MIME, emptiness — is - // ClassifyModuleResponse's call, so both fetch paths answer it the - // same way. + // is a usable module — status, MIME, emptiness — is the core's call. return true; } catch (NativeScriptException& nse) { std::string what = nse.what() ? nse.what() : ""; @@ -1022,342 +640,226 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool } TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=native-script-exception url=%s msg=%s", url.c_str(), what.c_str()); + outcome.errorDescription = "stage=native-script-exception msg=" + what; return false; } catch (std::exception& ex) { std::string what = ex.what() ? ex.what() : ""; TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=std-exception url=%s msg=%s", url.c_str(), what.c_str()); + outcome.errorDescription = "stage=std-exception msg=" + what; return false; } catch (...) { TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=unknown-cpp-exception url=%s", url.c_str()); + outcome.errorDescription = "stage=unknown-cpp-exception"; return false; } } -// ── Fetch concurrency ──────────────────────────────────────── - -// The defaults per host class (see ModuleFetchHostClass). adbd's reverse -// listener has a backlog of 4, so a burst of new connections overflows it, and -// each overflow costs the client a 1 s SYN retry. Remote hosts are -// bound by their round trip, so more fetches in flight load faster. -static constexpr size_t kLoopbackModuleFetchConcurrency = 6; -static constexpr size_t kRemoteModuleFetchConcurrency = 32; - -static std::once_flag s_fetchConcurrencyInitFlag; -// 0 = not configured. -static size_t s_configuredLoopbackConcurrency = 0; -static size_t s_configuredRemoteConcurrency = 0; - -static void InitializeFetchConcurrencyConfig() { - std::call_once(s_fetchConcurrencyInitFlag, []() { - try { - JEnv env; - jclass runtimeClass = env.FindClass("com/tns/Runtime"); - if (runtimeClass == nullptr) { - return; - } - jmethodID getter = - env.GetStaticMethodID(runtimeClass, "getModuleFetchConcurrency", "()[I"); - if (getter == nullptr) { - return; - } - jintArray values = - static_cast(env.CallStaticObjectMethod(runtimeClass, getter)); - if (values == nullptr) { - return; - } - if (env.GetArrayLength(values) == 2) { - jint pair[2] = {0, 0}; - env.GetIntArrayRegion(values, 0, 2, pair); - s_configuredLoopbackConcurrency = pair[0] > 0 ? static_cast(pair[0]) : 0; - s_configuredRemoteConcurrency = pair[1] > 0 ? static_cast(pair[1]) : 0; - } - env.DeleteLocalRef(values); - } catch (...) { - // Keep the defaults. +// ModuleHttpCache., with `origin` as its argument when not null. A +// Java failure comes back as the reader-facing message the runtime gives a +// Java exception. +http::CacheOpResult CallModuleHttpCache(const char* method, const std::string* origin) { + try { + JEnv env; + jclass cls = env.FindClass("com/tns/ModuleHttpCache"); + if (cls == nullptr) { + // Takes the ClassNotFoundException FindClass left pending. + throw NativeScriptException(env); + } + if (origin == nullptr) { + jmethodID mid = env.GetStaticMethodID(cls, method, "()V"); + env.CallStaticVoidMethod(cls, mid); + } else { + // Clear-Site-Data, applied on the thread that fetched: for the + // synchronous fallback that is the JS thread, and the cache's disk + // work is no more the app's StrictMode business than the fetch was. + StrictModeScope strictMode(env); + jmethodID mid = env.GetStaticMethodID(cls, method, "(Ljava/lang/String;)V"); + jstring jOrigin = env.NewStringUTF(origin->c_str()); + // Deleted on both paths: a JNI exception leaves the ref valid. + struct DeleteRef { + JNIEnv* jni; + jobject ref; + ~DeleteRef() { + if (ref != nullptr) jni->DeleteLocalRef(ref); + } + } deleteOrigin{env, jOrigin}; + env.CallStaticVoidMethod(cls, mid, jOrigin); } - }); + return {}; + } catch (NativeScriptException& e) { + return {false, e.GetErrorMessage()}; + } catch (const std::exception& e) { + return {false, e.what()}; + } } -static std::string LowercaseHostOf(const std::string& url) { - const size_t schemeEnd = url.find("://"); - if (schemeEnd == std::string::npos) return ""; - const size_t start = schemeEnd + 3; - const size_t end = url.find_first_of("/?#", start); - std::string authority = - url.substr(start, end == std::string::npos ? std::string::npos : end - start); - const size_t at = authority.rfind('@'); - if (at != std::string::npos) authority.erase(0, at + 1); - std::string host; - if (!authority.empty() && authority[0] == '[') { - const size_t close = authority.find(']'); - host = close == std::string::npos ? authority : authority.substr(0, close + 1); - } else { - host = authority.substr(0, authority.find(':')); +class AndroidModuleTransport final : public http::ModuleTransport { +public: + // "okhttp" when the app ships OkHttp (com.tns.OkHttpModuleFetcher: a + // dedicated client with an on-disk HTTP cache under + // /ns-module-http-cache) and it has not been forced off or + // found incompatible, otherwise "platform" (HttpURLConnection, uncached). + const char* Name() const override { + return ActiveOkHttpBridge() != nullptr ? "okhttp" : "platform"; } - for (char& c : host) { - c = static_cast(tolower(static_cast(c))); + + // Neither HTTP stack makes a blocking request wait for a connection + // another request holds, so FetchPath needs no separate connections. + // `waitBound` is not honoured: neither stack can abandon an attempt in + // flight. + http::AttemptOutcome FetchBlocking(const http::AttemptRequest& request) override { + http::AttemptOutcome outcome; + outcome.arrived = PerformHttpFetchOnceSync(request, outcome); + return outcome; } - return host; -} -ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url) { - const std::string host = LowercaseHostOf(url); - // 10.0.2.2 and 10.0.3.2 are the development machine as seen from the - // Android emulator and Genymotion. - if (host == "127.0.0.1" || host == "[::1]" || host == "localhost" || host == "10.0.2.2" || - host == "10.0.3.2") { - return ModuleFetchHostClass::kLoopback; + http::CacheOpResult ClearAll() override { + return CallModuleHttpCache("clear", nullptr); } - return ModuleFetchHostClass::kRemote; -} -const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass) { - return hostClass == ModuleFetchHostClass::kLoopback ? "loopback" : "remote"; -} + http::CacheOpResult ClearOrigin(const std::string& origin) override { + return CallModuleHttpCache("clearOrigin", &origin); + } -size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass) { - InitializeFetchConcurrencyConfig(); - if (hostClass == ModuleFetchHostClass::kLoopback) { - return s_configuredLoopbackConcurrency > 0 ? s_configuredLoopbackConcurrency - : kLoopbackModuleFetchConcurrency; + // The JVM attach is paid once per fetch thread rather than once per + // module. + void OnFetchThreadStart() override { + JavaVM* jvm = Runtime::GetJVM(); + if (jvm == nullptr) { + return; + } + JNIEnv* raw = nullptr; + if (jvm->GetEnv(reinterpret_cast(&raw), JNI_VERSION_1_6) != JNI_OK && + jvm->AttachCurrentThread(&raw, nullptr) == JNI_OK) { + s_attachedForFetches = true; + } } - return s_configuredRemoteConcurrency > 0 ? s_configuredRemoteConcurrency - : kRemoteModuleFetchConcurrency; -} -// ── Bounded async fetch ────────────────────────────────────── -// -// One module fetch, with everything the fetch thread needs; nothing here -// touches V8 or an isolate. -namespace { + void OnFetchThreadExit() override { + if (!s_attachedForFetches) { + return; + } + s_attachedForFetches = false; + if (JavaVM* jvm = Runtime::GetJVM()) { + jvm->DetachCurrentThread(); + } + } -struct ModuleFetchJob { - std::string url; - ModuleFetchHostClass hostClass; - ModuleFetchDeadline deadline; - // The cache switch as it was when the fetch was issued. - bool useCache; - std::function completion; +private: + static thread_local bool s_attachedForFetches; }; -// The timeout for an attempt starting now, or nullopt when `deadline` has -// already passed. -std::optional AttemptTimeoutMs(const ModuleFetchDeadline& deadline) { - const int policyMs = ModuleFetchTimeoutMs(); - if (!deadline) return policyMs; - const auto now = std::chrono::steady_clock::now(); - if (now >= *deadline) return std::nullopt; - // Rounded up: a sub-millisecond remainder must not become 0, which - // HttpURLConnection reads as no timeout at all. - const auto remainingMs = std::chrono::ceil(*deadline - now).count(); - return remainingMs < policyMs ? static_cast(remainingMs) : policyMs; -} +thread_local bool AndroidModuleTransport::s_attachedForFetches = false; -bool RetryFitsDeadline(const ModuleFetchDeadline& deadline) { - return !deadline || *deadline - std::chrono::steady_clock::now() > kModuleFetchRetryDelay; -} +// ── Platform config ───────────────────────────────────────── -// One queue and thread count per ModuleFetchHostClass, all under one mutex. -struct ModuleFetchLane { - std::deque queue; - size_t threadCount = 0; -}; +// Runs `read`, then clears whatever Java exception it left pending. A failure +// keeps the defaults `read` had not overwritten yet. +template +void ReadJavaConfig(Read read) { + JEnv env; + try { + read(env); + } catch (...) { + } + static_cast(env)->ExceptionClear(); +} -std::mutex g_fetchQueueMutex; -ModuleFetchLane g_fetchLanes[2]; +} // namespace -ModuleFetchLane& LaneFor(ModuleFetchHostClass hostClass) { - return g_fetchLanes[hostClass == ModuleFetchHostClass::kLoopback ? 0 : 1]; +void SetForcePlatformModuleTransport(bool force) { + s_forcePlatformTransport.store(force, std::memory_order_relaxed); } -void RunModuleFetchJob(const ModuleFetchJob& job) { - // Nothing may escape this function: it runs at the top of a detached - // thread, where an unwinding exception is std::terminate for the whole - // process — and a throw past the caller's loop would also strand the - // queue bookkeeping. The fetch phase converts an escaped exception into a - // transport-error result so the completion still runs exactly once; the - // completion itself gets a log-only guard, since by then delivery has - // either happened or cannot be retried. - ModuleFetchResult result; - try { - std::string body; - std::string contentType; - int status = 0; - const auto start = std::chrono::steady_clock::now(); - bool transportOk = false; - std::optional timeoutMs = AttemptTimeoutMs(job.deadline); - if (timeoutMs) { - transportOk = PerformHttpFetchOnceSync(job.url, *timeoutMs, job.useCache, body, - contentType, status); - // Transport error → one retry, the same single-retry policy the - // sync path applies, while the deadline can still fit the delay. - if (!transportOk && !RetryFitsDeadline(job.deadline)) { - TNS_DEBUG(Esm, "[http-loader][fetch-async] no budget left to retry %s", - job.url.c_str()); - } else if (!transportOk) { - TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error", - job.url.c_str()); - std::this_thread::sleep_for(kModuleFetchRetryDelay); - timeoutMs = AttemptTimeoutMs(job.deadline); - if (timeoutMs) { - transportOk = PerformHttpFetchOnceSync(job.url, *timeoutMs, job.useCache, - body, contentType, status); - } - } - } - - if (timeoutMs) { - ClassifyModuleResponse(job.url, transportOk, status, contentType, body, result); - } else { - result.failureReason = - "HTTP import failed: " + job.url + " (module graph fetch deadline exceeded)"; - } +} // namespace tns - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] %s", result.failureReason.c_str()); - } else if (LogCategoryEnabled(LogCategory::Fetch)) { - const auto ms = std::chrono::duration_cast( - std::chrono::steady_clock::now() - start) - .count(); - TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%lld", job.url.c_str(), - (unsigned long)result.body.size(), (long long)ms); - } - } catch (NativeScriptException& e) { - result = ModuleFetchResult{}; - result.failureReason = "HTTP import failed: " + job.url + " (network error)"; - DEBUG_WRITE_FORCE("[http-loader][fetch-async] native exception fetching %s: %s", - job.url.c_str(), e.what()); - } catch (const std::exception& e) { - result = ModuleFetchResult{}; - result.failureReason = "HTTP import failed: " + job.url + " (network error)"; - DEBUG_WRITE_FORCE("[http-loader][fetch-async] c++ exception fetching %s: %s", - job.url.c_str(), e.what()); - } catch (...) { - result = ModuleFetchResult{}; - result.failureReason = "HTTP import failed: " + job.url + " (network error)"; - DEBUG_WRITE_FORCE("[http-loader][fetch-async] unknown exception fetching %s", - job.url.c_str()); - } +namespace nativescript::common::platform { - try { - job.completion(std::move(result)); - } catch (const std::exception& e) { - DEBUG_WRITE_FORCE("[http-loader][fetch-async] completion threw for %s: %s", - job.url.c_str(), e.what()); - } catch (...) { - DEBUG_WRITE_FORCE("[http-loader][fetch-async] completion threw for %s", job.url.c_str()); - } -} +// Called once, from whichever thread reaches the loader first: the JS thread, +// a worker, a core fetch thread or the inspector's socket thread. JEnv +// attaches a thread that is not attached yet. +http::HttpLoaderConfig ReadHttpLoaderConfig() { + using tns::JEnv; + http::HttpLoaderConfig config; + config.isDebug = tns::IsDebuggable(); -// A fetch thread serves its own job and then drains the queue, so the JVM -// attach is paid once per thread rather than once per module and the cap -// bounds threads, not just sockets. Exiting checks the queue and decrements -// the count in ONE critical section: a producer that queues therefore always -// observes — and is observed by — a thread that has not yet exited, so a -// queued job cannot be stranded behind a thread on its way out. -void ModuleFetchThreadMain(ModuleFetchJob job) { - JavaVM* jvm = Runtime::GetJVM(); - bool attachedHere = false; - if (jvm != nullptr) { - JNIEnv* raw = nullptr; - if (jvm->GetEnv(reinterpret_cast(&raw), JNI_VERSION_1_6) != JNI_OK) { - if (jvm->AttachCurrentThread(&raw, nullptr) == JNI_OK) { - attachedHere = true; + // Debuggable apps load remote modules regardless of the security config. + if (!config.isDebug) { + tns::ReadJavaConfig([&config](JEnv& env) { + jclass runtimeClass = env.FindClass("com/tns/Runtime"); + if (runtimeClass == nullptr) { + return; } - } - } - struct DetachIfAttached { - JavaVM* jvm; - bool attached; - ~DetachIfAttached() { - if (attached && jvm != nullptr) { - jvm->DetachCurrentThread(); + jmethodID allowRemoteMid = + env.GetStaticMethodID(runtimeClass, "isRemoteModulesAllowed", "()Z"); + const bool allowRemoteModules = + env.CallStaticBooleanMethod(runtimeClass, allowRemoteMid) == JNI_TRUE; + + // Null when the list is not in force; a null element stands for an + // item that is not a string. + std::optional>> items; + jmethodID getAllowlistMid = env.GetStaticMethodID( + runtimeClass, "getRemoteModuleAllowlist", "()[Ljava/lang/String;"); + jobjectArray allowlistArray = static_cast( + env.CallStaticObjectMethod(runtimeClass, getAllowlistMid)); + if (allowlistArray != nullptr) { + items.emplace(); + jsize len = env.GetArrayLength(allowlistArray); + for (jsize i = 0; i < len; i++) { + jstring jstr = + static_cast(env.GetObjectArrayElement(allowlistArray, i)); + items->push_back(tns::ToExactUtf8(env, jstr)); + if (jstr != nullptr) { + env.DeleteLocalRef(jstr); + } + } + env.DeleteLocalRef(allowlistArray); } - } - } detachGuard{jvm, attachedHere}; - ModuleFetchLane& lane = LaneFor(job.hostClass); - for (;;) { - RunModuleFetchJob(job); + // Remote modules are enabled only after the allowlist was read in + // full: a failure part way keeps them disabled rather than enabling + // them with a list cut short. + config.remoteModuleAllowlist = std::move(items); + config.allowRemoteModules = allowRemoteModules; + }); + } - std::lock_guard lock(g_fetchQueueMutex); - if (lane.queue.empty()) { - lane.threadCount--; + tns::ReadJavaConfig([&config](JEnv& env) { + jclass cls = env.FindClass("com/tns/ModuleHttpCache"); + if (cls == nullptr) { return; } - job = std::move(lane.queue.front()); - lane.queue.pop_front(); - } -} - -} // namespace - -void FetchModuleBodyAsync(const std::string& url, ModuleFetchDeadline fetchDeadline, - std::function completion) { - // Security gate: single point of enforcement, same as HttpFetchModule. - if (!IsRemoteUrlAllowed(url)) { - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - ModuleFetchResult blocked; - blocked.status = 403; - blocked.failureReason = - "HTTP import blocked: remote module loading is not allowed for " + url; - completion(std::move(blocked)); - return; - } + jmethodID mid = env.GetStaticMethodID(cls, "isEnabledAtStartup", "()Z"); + config.moduleHttpCacheAtStartup = env.CallStaticBooleanMethod(cls, mid) == JNI_TRUE; + }); - const ModuleFetchHostClass hostClass = ModuleFetchHostClassOf(url); - // Outside the lock: the first call reads the app config over JNI. - const size_t cap = ModuleFetchConcurrency(hostClass); - ModuleFetchLane& lane = LaneFor(hostClass); - ModuleFetchJob job{url, hostClass, fetchDeadline, ModuleHttpCacheEnabled(), - std::move(completion)}; - { - std::lock_guard lock(g_fetchQueueMutex); - if (lane.threadCount >= cap) { - lane.queue.push_back(std::move(job)); + tns::ReadJavaConfig([&config](JEnv& env) { + jclass runtimeClass = env.FindClass("com/tns/Runtime"); + if (runtimeClass == nullptr) { return; } - lane.threadCount++; - } - - // Copied, not moved: a throwing std::thread constructor leaves its - // decay-copies in an unspecified state, and the failure path below still - // has to deliver this job's completion. - try { - std::thread(ModuleFetchThreadMain, job).detach(); - return; - } catch (...) { - } - - // A counted slot with no thread behind it: anything queued against it has - // nothing left to drain it if this was the last one, so those jobs are - // failed here rather than left waiting on a thread that will never exist. - std::deque orphaned; - { - std::lock_guard lock(g_fetchQueueMutex); - lane.threadCount--; - if (lane.threadCount == 0) { - orphaned.swap(lane.queue); + jmethodID getter = env.GetStaticMethodID(runtimeClass, "getModuleFetchConcurrency", "()[I"); + jintArray values = static_cast(env.CallStaticObjectMethod(runtimeClass, getter)); + if (values == nullptr) { + return; } - } + if (env.GetArrayLength(values) == 2) { + jint pair[2] = {0, 0}; + env.GetIntArrayRegion(values, 0, 2, pair); + config.fetchConcurrency[0] = pair[0] > 0 ? static_cast(pair[0]) : 0; + config.fetchConcurrency[1] = pair[1] > 0 ? static_cast(pair[1]) : 0; + } + env.DeleteLocalRef(values); + }); - // The completion contract is exactly-once, and the caller's bookkeeping - // (pendingFetches) is already incremented — a swallowed spawn failure - // wedges the graph walk short of settling forever. - auto failSpawn = [](const ModuleFetchJob& failedJob) { - ModuleFetchResult failed; - failed.failureReason = "Could not fetch " + failedJob.url + - ": the runtime could not start a fetch thread"; - TNS_DEBUG(Esm, "[http-loader][fetch-async][spawn-fail] %s", failedJob.url.c_str()); - failedJob.completion(std::move(failed)); - }; + return config; +} - failSpawn(job); - for (const ModuleFetchJob& orphan : orphaned) { - failSpawn(orphan); - } +http::ModuleTransport& HttpTransport() { + static auto* transport = new tns::AndroidModuleTransport(); + return *transport; } -} // namespace tns +} // namespace nativescript::common::platform diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index efe45c266..9ce9cdb3d 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -1,210 +1,55 @@ #pragma once -#include -#include -#include #include -#include -namespace tns { - -// HttpLoader: the native half of the NativeScript HTTP module-loader -// contract. -// -// The runtime deliberately exposes *mechanism* only: -// - the synchronous HTTP text fetch backing the HTTP ESM loader's -// fallback path (V8's ResolveModuleCallback is synchronous — still -// true as of 14.9.207.39 — so the fallback must be native), -// - the async background-thread fetch behind the phase-1 module-graph -// walk (StartModuleGraphLoad), which is how module bodies -// normally arrive, -// - the remote-module security gate, seeded once from nativescript.config -// at boot and never exposed on ns:runtime getConfig/setConfig. +#include "ns/http/ModuleFetch.h" -// ───────────────────────────────────────────────────────────── -// HTTP loader helpers (used by dev/HMR and general-purpose HTTP module loading) -// -// The canonical-key *mechanism* (fragment strip, cache-buster param drop, -// param sort) must be native because it keys the module registry inside V8's -// synchronous resolve walk. The *vocabulary* — which query params are pure -// cache busters, which path prefixes identify dev endpoints whose queries may -// be normalized, and which paths must keep their query verbatim because the -// query IS the identity — is server/framework policy, supplied by the dev -// client via ns:module `configureLoader({ canonicalization: {...} })`. It is -// per-isolate loader vocabulary — installed through SetCanonicalizationConfig -// in ModuleInternalCallbacks.h — so CanonicalizeHttpUrlKey runs on the -// isolate's own thread only. The transport never canonicalizes. -// -// When unconfigured, canonicalization is purely mechanical (fragment strip). -struct CanonicalizationConfig { - std::vector stripParams; // query param names to drop - std::vector devPathPrefixes; // StartsWith → normalize query - std::vector preserveQueryPrefixes; // contains → keep query -}; +namespace tns { -// Normalize an HTTP(S) URL into a stable module registry/cache key. -// - Anything that is not HTTP(S) comes back unchanged; an http(s) URL is -// first spelled by NormalizeHttpModuleUrl. -// - The fragment is always stripped. -// - The query survives unless the isolate's canonicalization vocabulary says -// otherwise: a path matching `preserveQueryFor` keeps its query verbatim; -// a path under a `forPathPrefixes` prefix drops every `stripParams` name and -// sorts what remains, for stability. Unconfigured, every query is kept. -// Module identity IS the (canonical) URL — the dev server serves every -// module under exactly one URL and never varies it for freshness. +// The HTTP module loader's policy and orchestration (gate, allowlist, request +// headers, timeouts, retry, fetch threads, classification, the cache switch, +// Clear-Site-Data) live in the shared core, ns/http/ModuleFetch.h. This +// runtime supplies the transport (OkHttp when the app ships it, otherwise +// HttpURLConnection), the platform config read, and the per-isolate +// canonicalization vocabulary. + +using nativescript::common::http::CacheOpResult; +using nativescript::common::http::CanonicalizationConfig; +using nativescript::common::http::ClearModuleHttpCache; +using nativescript::common::http::FetchModuleBodyAsync; +using nativescript::common::http::HttpFetchModule; +using nativescript::common::http::IsRemoteModulesAllowed; +using nativescript::common::http::IsRemoteUrlAllowed; +using nativescript::common::http::ModuleFetchConcurrency; +using nativescript::common::http::ModuleFetchDeadline; +using nativescript::common::http::ModuleFetchHostClass; +using nativescript::common::http::ModuleFetchHostClassName; +using nativescript::common::http::ModuleFetchHostClassOf; +using nativescript::common::http::ModuleFetchResult; +using nativescript::common::http::ModuleHttpCacheEnabled; +using nativescript::common::http::ModuleResponseKind; +using nativescript::common::http::RemoteModuleAllowlist; +using nativescript::common::http::RemoteModuleAllowlistFromConfig; +using nativescript::common::http::RemoteUrlAllowedByAllowlist; +using nativescript::common::http::SetModuleHttpCacheDisabledBy; +using nativescript::common::http::SetModuleHttpCacheEnabled; + +// The module registry key of an HTTP(S) URL: anything that is not HTTP(S) +// comes back unchanged; an http(s) URL is spelled by NormalizeHttpModuleUrl, +// then canonicalized with the calling isolate's vocabulary (ns:module +// `configureLoader({ canonicalization })`, see loader::SetCanonicalizationConfig in +// ns/loader/LoaderState.h). Isolate thread only. std::string CanonicalizeHttpUrlKey(const std::string& url); // CanonicalizeHttpUrlKey for a URL already spelled by NormalizeHttpModuleUrl. std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl); -// What a module response turned out to be. Decided once, by the shared -// classifier, for whichever transport produced the response. -enum class ModuleResponseKind { - kJavaScript, - kJson, -}; - -// The outcome of fetching one module over HTTP. Both transports produce this -// same verdict, so the synchronous fallback and the async graph walk cannot -// drift apart on what counts as a usable module. -struct ModuleFetchResult { - bool ok = false; - int status = 0; - ModuleResponseKind kind = ModuleResponseKind::kJavaScript; - // Normalized: an empty 2xx JavaScript body becomes the canonical empty - // module. Meaningful only when `ok`. - std::string body; - std::string contentType; // as received, parameters included - // Reader-facing explanation, non-empty exactly when `!ok`. This is the text - // that reaches the importer's rejection, so it names the URL and the cause. - std::string failureReason; -}; - -// Synchronous module fetch with one retry on transport error — the fallback -// path for anything the module-graph walk missed. Blocks the calling thread. -// Returns `result.ok`. -bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); - -// An absolute bound on an async module fetch, retries included; nullopt = -// unbounded. -using ModuleFetchDeadline = std::optional; - -// Asynchronous single-URL module fetch — the I/O primitive behind the -// module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h). -// Same response policy as HttpFetchModule, minus the JS-thread block: -// - security gate (IsRemoteUrlAllowed) checked up front, -// - a GET on a background thread through the active transport (see -// ActiveModuleTransportName) with the same request shape as the sync -// path, over persistent connections, and one retry on transport error. -// `fetchDeadline` is the enclosing graph load's fetch budget: each attempt -// clamps its connect and read timeouts to the time remaining, the -// transport-error retry is skipped once the budget cannot fit it, and an -// attempt that would start with no budget left fails instead. Time spent -// queued behind the concurrency cap counts against it. The timeouts bound one -// connect and each read, not the whole response, so a body that keeps -// trickling in can still finish past the deadline. -// `completion(result)` is invoked exactly once, on an arbitrary thread — -// callers must hop to their JS thread before touching V8. -// -// Concurrency is capped per host class (ModuleFetchConcurrency), process-wide -// rather than per host as NSURLSession does on iOS: the fetch threads are a -// process resource, and a dev session's modules all come from one origin. Over -// the cap the request is queued and picked up by a fetch thread of its class -// as one frees — the CALLER never blocks, so this stays safe to call from the -// JS thread. -void FetchModuleBodyAsync( - const std::string& url, ModuleFetchDeadline fetchDeadline, - std::function completion); - -// The transport both fetch paths use: "okhttp" when the app ships OkHttp -// (com.tns.OkHttpModuleFetcher: a dedicated client with an on-disk HTTP cache -// under /ns-module-http-cache), otherwise "platform" -// (HttpURLConnection, uncached). Request headers, timeouts, redirects, the -// security gate and response classification are the same on both. -const char* ActiveModuleTransportName(); - // Debug builds only (ns:module forcePlatformHttpTransport): fetch through the // platform transport even when OkHttp is available, so that fallback stays // testable in an app that ships OkHttp. void SetForcePlatformModuleTransport(bool force); -// The HTTP module cache switch, process-wide: every isolate and both fetch -// paths. A fetch reads it once, when it is issued. Off, a fetch neither reads -// nor writes the cache and sends `Cache-Control: no-cache` and -// `Pragma: no-cache`, on either transport. -// -// Enabled = the setting (app config `moduleHttpCache`, the -// nativescript-no-module-cache launch option, then ns:module -// setHttpCacheEnabled) AND no inspector client has the cache disabled. -bool ModuleHttpCacheEnabled(); -void SetModuleHttpCacheEnabled(bool enabled); -// +1 when an inspector client disables the cache, -1 when it re-enables it or -// disconnects. -void AddModuleHttpCacheInspectorDisable(int delta); - -// Wipes the module cache (ModuleHttpCache.clear()), durably, before returning. -// Throws NativeScriptException when Java reports a failure. -void ClearModuleHttpCache(); - -// Which concurrency cap a module URL's fetches share. -// kLoopback: the host is 127.0.0.1, [::1] or localhost. On a device that -// is almost always `adb reverse`, whose listener overflows under a burst -// of connects; every overflow costs the client a ~1 s SYN retry. -// kRemote: any other host, where a fetch is bound by its round trip and -// more connections in flight hide more of it. -enum class ModuleFetchHostClass { kLoopback, kRemote }; - -ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url); - -const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass); - -// How many fetches of `hostClass` run at once: `android.moduleFetchConcurrency` -// from the app config when set (validated by AppConfig.java), otherwise the -// built-in default for the class. Read from the config once per process. -size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass); - -// ───────────────────────────────────────────────────────────── -// Remote-module security gate -// -// Seeded once from nativescript.config / package.json (`security.allowRemoteModules`, -// `security.remoteModuleAllowlist`) the first time a fetch is gated. Debug -// apps always allow. These values are not readable or writable through -// ns:runtime getConfig/setConfig — only nativescript.config at boot. - -// In debug mode (Runtime.isDebuggable()): always returns true. -// Otherwise returns the boot-time `security.allowRemoteModules` value. -bool IsRemoteModulesAllowed(); - -// Whether `url` may be fetched as a remote ES module. Debug apps always -// allow. Production requires allowRemoteModules, then RemoteUrlAllowedByAllowlist. -bool IsRemoteUrlAllowed(const std::string& url); - -// The allowlist IsRemoteUrlAllowed applies once remote modules are enabled. -struct RemoteModuleAllowlist { - // False only when `security.remoteModuleAllowlist` is absent, not an - // array, or an empty array: then every URL is allowed. - bool inForce = false; - // The usable items, each spelled the way the loader spells the URLs it - // fetches (NormalizeHttpModuleUrl) so path-scoped entries compare against - // resolved paths, or kept verbatim when it is not an http(s) URL. An item - // that is not a string, is empty or has no exact UTF-8 form is not here: - // it matches nothing but still keeps the list in force. - std::vector entries; -}; - -// The allowlist for the `security.remoteModuleAllowlist` config value: nullopt -// when it is absent or not an array, otherwise its items in order, each -// nullopt when it is not a string or has no exact UTF-8 form. -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( - const std::optional>>& items); - -// Whether `url` (as fetched) passes `allowlist`: always when it is not in -// force, otherwise when one entry matches it by prefix with the match ending -// at a URL-component boundary. -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist); - -// Mirrors com.tns.Runtime.isDebuggable(), cached once via the security -// config init. Fail-safe false until initialized. +// com.tns.Runtime.isDebuggable(), read once. False when it cannot be read. bool IsDebuggable(); } // namespace tns diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index b9cd119b5..256c23f5c 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -20,7 +20,10 @@ #include "Constants.h" #include "File.h" #include "HttpLoader.h" -#include "ModuleUrl.h" +#include "ns/JsError.h" +#include "ns/loader/CommonJs.h" +#include "ns/loader/LoaderState.h" +#include "ns/loader/ModuleIdentity.h" #include "Util.h" #include "Utils.h" #include "WorkerInspectorClient.h" @@ -54,6 +57,13 @@ namespace { // with Network.loadNetworkResource, which we answer from disk. constexpr const char* kSourceMapScheme = "nsruntime://"; +// The path a file: script URL names, read the way the runtime wrote it (a '%' +// is not an escape under legacy origins); empty when it names none. +std::string ScriptUrlPath(const std::string& url, + const nativescript::common::LoaderConfig& config) { + return nativescript::common::loader::OriginToPath(url, config).value_or(std::string()); +} + std::string JsonDump(const json& value) { // replace invalid UTF-8 instead of throwing across the JNI boundary return value.dump(-1, ' ', false, json::error_handler_t::replace); @@ -292,7 +302,8 @@ bool ShouldRewriteSourceMapURLs() { // Debugger.scriptFailedToParse events from a file url (or a url relative to // the script's file url) to an absolute nsruntime:// url, so DevTools // requests the map through the target instead of the frontend host. -std::string MaybeRewriteSourceMapURL(const std::string& message) { +std::string MaybeRewriteSourceMapURL(const std::string& message, + const nativescript::common::LoaderConfig& config) { if (message.find("\"Debugger.scriptParsed\"") == std::string::npos && message.find("\"Debugger.scriptFailedToParse\"") == std::string::npos) { return message; @@ -317,7 +328,7 @@ std::string MaybeRewriteSourceMapURL(const std::string& message) { std::string path; if (sourceMapURL.rfind("file://", 0) == 0) { - path = FileModulePath(sourceMapURL); + path = ScriptUrlPath(sourceMapURL, config); } else if (sourceMapURL[0] == '/') { path = sourceMapURL; } else { @@ -326,7 +337,7 @@ std::string MaybeRewriteSourceMapURL(const std::string& message) { if (scriptUrl.rfind("file://", 0) != 0) { return message; } - std::string scriptPath = FileModulePath(scriptUrl); + std::string scriptPath = ScriptUrlPath(scriptUrl, config); auto lastSlash = scriptPath.rfind('/'); if (lastSlash == std::string::npos) { return message; @@ -347,6 +358,7 @@ std::string MaybeRewriteSourceMapURL(const std::string& message) { JsV8InspectorClient::JsV8InspectorClient(v8::Isolate* isolate) : tracing_agent_(new tns::inspector::TracingAgentImpl()), isolate_(isolate), + loaderConfig_(nativescript::common::platform::LoaderSnapshot()), inspector_(nullptr), session_(nullptr), connection_(nullptr), @@ -835,16 +847,13 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message } std::optional JsV8InspectorClient::ClearModuleHttpCacheFromInspector() { - std::string failure = "Could not clear the HTTP module cache"; - try { - ClearModuleHttpCache(); + const CacheOpResult cleared = ClearModuleHttpCache(); + if (cleared.ok) { return std::nullopt; - } catch (NativeScriptException& e) { - const std::string detail = e.GetErrorMessage(); - if (!detail.empty()) { - failure += ": " + detail; - } - } catch (...) { + } + std::string failure = "Could not clear the HTTP module cache"; + if (!cleared.error.empty()) { + failure += ": " + cleared.error; } DEBUG_WRITE_FORCE("Network.clearBrowserCache: %s", failure.c_str()); return failure; @@ -854,21 +863,26 @@ void JsV8InspectorClient::SetCacheDisabledBy(jobject socket, bool cacheDisabled) if (socket == nullptr) { return; } + // Unique per process, as the core's holder set is. + static std::atomic nextCacheHolderId{1}; JEnv env; std::lock_guard lock(connectionMutex_); auto holder = std::find_if(cacheDisabledBy_.begin(), cacheDisabledBy_.end(), - [&](jobject held) { return env.isSameObject(held, socket); }); + [&](const CacheHolder& held) { + return env.isSameObject(held.socket, socket); + }); const bool holds = holder != cacheDisabledBy_.end(); if (cacheDisabled == holds) { return; } if (cacheDisabled) { - cacheDisabledBy_.push_back(env.NewGlobalRef(socket)); - AddModuleHttpCacheInspectorDisable(1); + const uint64_t id = nextCacheHolderId.fetch_add(1, std::memory_order_relaxed); + cacheDisabledBy_.push_back({env.NewGlobalRef(socket), id}); + SetModuleHttpCacheDisabledBy(id, true); } else { - env.DeleteGlobalRef(*holder); + SetModuleHttpCacheDisabledBy(holder->id, false); + env.DeleteGlobalRef(holder->socket); cacheDisabledBy_.erase(holder); - AddModuleHttpCacheInspectorDisable(-1); } } @@ -996,7 +1010,7 @@ std::string JsV8InspectorClient::HandleLoadNetworkResource(long long msgId, cons if (url.rfind(kSourceMapScheme, 0) == 0) { path = url.substr(strlen(kSourceMapScheme)); } else if (url.rfind("file://", 0) == 0) { - path = FileModulePath(url); + path = ScriptUrlPath(url, *loaderConfig_); } else { // Reply with a protocol error (not success:false) so DevTools falls // back to loading the resource from the frontend host, which is the @@ -1173,7 +1187,7 @@ void JsV8InspectorClient::sendNotification(std::unique_ptr message } void JsV8InspectorClient::SendToFrontend(const std::string& message) { - SendRawToFrontend(MaybeRewriteSourceMapURL(message)); + SendRawToFrontend(MaybeRewriteSourceMapURL(message, *loaderConfig_)); } void JsV8InspectorClient::SendRawToFrontend(const std::string& msg) { @@ -1226,11 +1240,12 @@ void JsV8InspectorClient::init() { createInspectorSession(); + // A failure to register the inspector's modules must not fail init(). try { this->registerModules(); } catch (NativeScriptException& e) { - // we don't want to throw if registering modules failed. - // e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + } catch (nativescript::common::Terminated&) { } } @@ -1417,9 +1432,14 @@ void JsV8InspectorClient::registerModules() { NS_DCHECK(success); TryCatch tc(isolate); - Runtime::GetRuntime(isolate)->RunModule("inspector_modules"); - - if(tc.HasCaught()) { + Local name = ArgConverter::ConvertToV8String(isolate, "inspector_modules"); + const bool loaded = !nativescript::common::loader::RequireFunctionFor( + context, nativescript::common::loader::LoaderConfigFor(isolate).appRoot, + nativescript::common::loader::ModuleEvaluationOptions::Require( + nativescript::common::loader::ModuleEvaluationPolicy::kSyncStrict)) + ->Call(context, global, 1, &name).IsEmpty(); + + if(!loaded || tc.HasCaught()) { throw NativeScriptException(tc, "Error loading inspector modules"); } } diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h index d091ea437..58adcfae7 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -10,6 +11,7 @@ #include #include "v8.h" #include "JEnv.h" +#include "ns/LoaderConfig.h" #include "v8-inspector.h" #include "v8_inspector/ns-v8-tracing-agent-impl.h" @@ -160,6 +162,8 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe std::unique_ptr tracing_agent_; v8::Isolate* isolate_; + // Read from the socket thread too, so not LoaderConfigFor(isolate_). + std::shared_ptr loaderConfig_; std::unique_ptr inspector_; v8::Persistent context_; std::unique_ptr session_; @@ -174,12 +178,16 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe // memory location with the bitfields above, which the main thread // writes. std::atomic isConnected_; - // Global refs to the websockets whose frontend has the HTTP module cache - // disabled, each holding one AddModuleHttpCacheInspectorDisable count - // until it re-enables it or its socket closes. A replaced frontend's - // socket can outlive connection_, so this is not tied to it. Guarded by - // connectionMutex_. - std::vector cacheDisabledBy_; + // The websockets whose frontend has the HTTP module cache disabled, + // each a global ref and the holder id it disables the cache under + // (SetModuleHttpCacheDisabledBy) until it re-enables it or its socket + // closes. A replaced frontend's socket can outlive connection_, so this + // is not tied to it. Guarded by connectionMutex_. + struct CacheHolder { + jobject socket; + uint64_t id; + }; + std::vector cacheDisabledBy_; // {N} specific helpers diff --git a/test-app/runtime/src/main/cpp/MetadataNode.cpp b/test-app/runtime/src/main/cpp/MetadataNode.cpp index ba45f2e13..dbe79fcca 100644 --- a/test-app/runtime/src/main/cpp/MetadataNode.cpp +++ b/test-app/runtime/src/main/cpp/MetadataNode.cpp @@ -2495,8 +2495,6 @@ bool MetadataNode::GetExtendLocation(v8::Isolate* isolate, string& extendLocatio string srcFileName = ArgConverter::ConvertToString(scriptName); string fullPathToFile; - // ES modules (`.mjs`, and HTTP-loaded modules) have no CommonJS wrapper. - bool hasCommonJsPrologue = true; if (srcFileName == "") { // Corner case, extend call is coming from the heap snapshot script // This is possible for lazily compiled code - e.g. from the body of a function @@ -2524,7 +2522,6 @@ bool MetadataNode::GetExtendLocation(v8::Isolate* isolate, string& extendLocatio stripPrefix(normalized, "file://"); if (normalized.rfind("http://", 0) == 0 || normalized.rfind("https://", 0) == 0) { - hasCommonJsPrologue = false; size_t schemeEnd = normalized.find("://"); size_t pathStart = normalized.find('/', schemeEnd + 3); if (pathStart == string::npos) { @@ -2549,7 +2546,6 @@ bool MetadataNode::GetExtendLocation(v8::Isolate* isolate, string& extendLocatio s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0; }; if (endsWith(normalized, ".mjs")) { - hasCommonJsPrologue = false; normalized.resize(normalized.size() - 4); } else if (endsWith(normalized, ".js")) { normalized.resize(normalized.size() - 3); @@ -2572,12 +2568,6 @@ bool MetadataNode::GetExtendLocation(v8::Isolate* isolate, string& extendLocatio return false; } - // Account for the column length offset added by the addition of the Common JS function wrapper - // See issue https://github.com/NativeScript/android-runtime/issues/975 - if (lineNumber == 1 && hasCommonJsPrologue) { - column = column - ModuleInternal::MODULE_PROLOGUE_LENGTH; - } - extendLocationStream << fullPathToFile.c_str() << "_" << lineNumber << "_" << column << "_"; } } diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index 5ec3645f6..cb5918ad5 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -5,632 +5,73 @@ * Author: gatanasov */ #include "ModuleInternal.h" -#include "ModuleInternalCallbacks.h" -#include "BuiltinLoader.h" -#include "File.h" -#include "HttpLoader.h" +#include "ManualInstrumentation.h" #include "ModuleUrl.h" -#include "JniLocalRef.h" -#include "ArgConverter.h" -#include "NativeScriptAssert.h" -#include "Constants.h" -#include "CrashBreadcrumbs.h" -#include "EventLoop.h" #include "NativeScriptException.h" -#include "NsBuiltinModules.h" -#include "napi/NapiModules.h" -#include "Util.h" -#include "SimpleProfiler.h" #include "CallbackHandlers.h" -#include "ManualInstrumentation.h" -#include "Runtime.h" -#include "RuntimeState.h" -#include "TraceLog.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "ns/JsError.h" +#include "ns/loader/Boot.h" +#include "ns/loader/CommonJs.h" +#include "ns/loader/Evaluate.h" +#include "ns/loader/ModuleIdentity.h" using namespace v8; using namespace std; using namespace tns; +using nativescript::common::loader::ModuleEvaluationOptions; +using nativescript::common::loader::ModuleEvaluationPolicy; + bool ModuleInternal::IsHttpModulePath(const std::string& path) { return !NormalizeHttpModuleUrl(path).empty(); } -// What a rejected evaluation promise says about itself. -struct RejectionDetail { - // The reason's own text: an Error's `message`, or the reason stringified. - std::string message; - // A bounded rendering of the reason's `stack`, filled only when asked for. - std::string stackPreview; -}; - -// `detail`, when non-null, receives the reason's parts unjoined; reading the -// stack costs a property get plus a copy, so callers pass null unless a trace -// is actually going to be emitted. -static std::string PromiseRejectionMessage(Isolate* isolate, Local promise, - const std::string& path, - RejectionDetail* detail = nullptr) { - std::string errorMessage = "Module evaluation promise rejected: " + path; - TryCatch tc(isolate); - Local reason = promise->Result(); - if (reason.IsEmpty()) { - return errorMessage; - } - std::string reasonText; - Local context = isolate->GetCurrentContext(); - if (reason->IsObject()) { - Local errorObj = reason.As(); - Local messageVal; - if (errorObj->Get(context, ArgConverter::ConvertToV8String(isolate, "message")) - .ToLocal(&messageVal) && - messageVal->IsString()) { - v8::String::Utf8Value messageUtf8(isolate, messageVal); - if (*messageUtf8) { - reasonText.assign(*messageUtf8); - } - } - Local stackVal; - if (detail != nullptr && - errorObj->Get(context, ArgConverter::ConvertToV8String(isolate, "stack")) - .ToLocal(&stackVal) && - stackVal->IsString()) { - v8::String::Utf8Value stackUtf8(isolate, stackVal); - if (*stackUtf8) { - std::string stack(*stackUtf8); - detail->stackPreview = stack.size() > 240 ? stack.substr(0, 240) + "…" : stack; - } - } - } else { - auto maybeReasonStr = reason->ToString(context); - if (!maybeReasonStr.IsEmpty()) { - v8::String::Utf8Value reasonUtf8(isolate, maybeReasonStr.ToLocalChecked()); - if (*reasonUtf8) { - reasonText.assign(*reasonUtf8); - } - } - } - if (!reasonText.empty()) { - errorMessage.append(" — "); - errorMessage.append(reasonText); - } - if (detail != nullptr) { - detail->message = std::move(reasonText); - } - if (tc.HasCaught()) { - tc.Reset(); - } - return errorMessage; -} - -// A package-style specifier: neither a path nor a scheme, so it may be claimed -// by a registry rather than resolved on disk. -static bool IsBareSpecifier(const std::string& specifier) { - if (specifier.empty() || specifier[0] == '.' || specifier[0] == '/' || - specifier[0] == '~') { - return false; - } - - return specifier.find(':') == std::string::npos; -} - -static ModuleEvaluationOptions BootEntryEvaluationOptions(bool isHttpModule); -static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy policy); - -// Helper function to check if a file path is an ES module (.mjs) but not a source map (.mjs.map) -bool ModuleInternal::IsESModule(const std::string& path) { - return path.size() >= 4 && path.compare(path.size() - 4, 4, ".mjs") == 0 && - !(path.size() >= 8 && path.compare(path.size() - 8, 8, ".mjs.map") == 0); -} - ModuleInternal::ModuleInternal() - : m_isolate(nullptr), m_requireFunction(nullptr), m_requireFactoryFunction(nullptr) { + : m_isolate(nullptr) { } -ModuleInternal::~ModuleInternal() { - delete this->m_requireFunction; - delete this->m_requireFactoryFunction; - for (const auto& pair: this->m_requireCache) { - delete pair.second; - } - this->m_requireCache.clear(); - - /* - * Runs after Isolate::Dispose, so the handles are freed with the isolate and - * only the wrappers are deleted -- v8::Persistent does not reset in its - * destructor, which is what makes that safe here. - * - * Deduplicated by pointer: a module is cached under both its resolved path - * and its cache key, and both entries hold the same Persistent. - */ - robin_hood::unordered_set*> freed; - for (const auto& pair: this->m_loadedModules) { - if (freed.insert(pair.second.obj).second) { - delete pair.second.obj; - } - } - this->m_loadedModules.clear(); -} - -void ModuleInternal::Init(Isolate* isolate, const string& baseDir) { - JEnv env; - - if (MODULE_CLASS == nullptr) { - MODULE_CLASS = env.FindClass("com/tns/Module"); - NS_CHECK(MODULE_CLASS != nullptr); - - RESOLVE_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "resolvePath", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); - NS_CHECK(RESOLVE_PATH_METHOD_ID != nullptr); - - GET_APPLICATION_FILES_PATH_METHOD_ID = env.GetStaticMethodID(MODULE_CLASS, "getApplicationFilesPath", "()Ljava/lang/String;"); - NS_CHECK(GET_APPLICATION_FILES_PATH_METHOD_ID != nullptr); - } - +void ModuleInternal::Init(Isolate* isolate) { m_isolate = isolate; - - auto context = isolate->GetCurrentContext(); - - auto global = context->Global(); - - Local result; - auto success = BuiltinLoader::RunBuiltin(context, BuiltinId::kRequireFactory).ToLocal(&result); - - NS_CHECK(success && result->IsFunction()); - - auto requireFactoryFunction = result.As(); - - m_requireFactoryFunction = new Persistent(isolate, requireFactoryFunction); - - auto external = External::New(isolate, this, v8::kExternalPointerTypeTagDefault); - - // Only the require factory receives this one, so the evaluation options it - // forwards were validated at mint time. - auto requireFuncTemplate = FunctionTemplate::New(isolate, RequireCallback, external); - auto requireFunc = requireFuncTemplate->GetFunction(context).ToLocalChecked(); - m_requireFunction = new Persistent(isolate, requireFunc); - - // App code can reach this one, so it reads nothing but the specifier and the - // calling directory: a caller must not be able to hand itself a pumping - // policy, an unbounded deadline or a looper-slicing require. - auto publicRequireTemplate = FunctionTemplate::New(isolate, RequirePublicCallback, external); - global->Set(context, ArgConverter::ConvertToV8String(isolate, "__nativeRequire"), - publicRequireTemplate->GetFunction(context).ToLocalChecked()); - - // terminate() cannot reach this isolate yet - a worker's is published to its - // parent only once the runtime is up - so this mint is checked as hard as - // the factory's own load above. - Local globalRequire; - const bool minted = GetRequireFunction( - isolate, baseDir.empty() ? Constants::APP_ROOT_FOLDER_PATH : baseDir, - RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict)).ToLocal(&globalRequire); - NS_CHECK(minted); - global->Set(context, ArgConverter::ConvertToV8String(isolate, "require"), globalRequire); -} - -// How an entry module's graph settles. For local modules the bound is a yield, -// not a timeout: the default pump runs only nestable V8 tasks while these JS -// frames are on the stack, so a TLA parked on anything else can never settle -// in-place — give it one short window, then return and let the real event -// loop (or the draining boot backstop) finish it after the turn. HTTP entries -// must settle in-pump — the dev client needs the rejection reason -// synchronously — so they get the full deadline and the looper-equivalent -// drain, the same split iOS makes with its runloop slice. -static ModuleEvaluationOptions BootEntryEvaluationOptions(bool isHttpModule) { - ModuleEvaluationOptions options; - options.policy = ModuleEvaluationPolicy::kSyncPumping; - options.deadlineSeconds = isHttpModule ? kModuleEvaluateDeadlineSeconds : 1.0; - options.timeoutBehavior = isHttpModule - ? ModuleEvaluationOptions::TimeoutBehavior::kThrow - : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; - options.pumpRunLoop = isHttpModule; - return options; -} - -// How a graph reached through require() settles. A pumping require must settle -// or throw — handing back a half-initialized namespace is what the strict -// policy exists to prevent — so it gets the full deadline. By default the -// pump runs nestable v8 tasks and microtasks only, matching iOS: running JS -// timers or loop posts in the middle of an arbitrary require is opt-in -// (pumpRunLoop), because those callbacks execute underneath the require's JS -// frames. -static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy policy) { - ModuleEvaluationOptions options; - options.policy = policy; - if (policy == ModuleEvaluationPolicy::kSyncPumping) { - options.deadlineSeconds = kModuleEvaluateDeadlineSeconds; - options.timeoutBehavior = ModuleEvaluationOptions::TimeoutBehavior::kThrow; - options.pumpRunLoop = false; - } - return options; -} - -// The require cache is keyed by directory AND by the options the require was -// minted with: a pumping require for a directory must never be served from a -// strict require cached for the same directory, in either direction. -static std::string RequireCacheKey(const std::string& dirName, - const ModuleEvaluationOptions& options) { - std::string key = dirName; - key += '\x1f'; - key += std::to_string(static_cast(options.policy)); - key += '\x1f'; - key += std::to_string(options.deadlineSeconds); - key += '\x1f'; - key += (options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow) ? '1' : '0'; - key += options.pumpRunLoop ? '1' : '0'; - return key; -} - -MaybeLocal ModuleInternal::GetRequireFunction(Isolate* isolate, const string& dirName, - const ModuleEvaluationOptions& options) { - TNSPERF(); - Local requireFunc; - - const std::string cacheKey = RequireCacheKey(dirName, options); - auto itFound = m_requireCache.find(cacheKey); - - if (itFound != m_requireCache.end()) { - requireFunc = Local::New(isolate, *itFound->second); - } else { - auto requireFuncFactory = Local::New(isolate, *m_requireFactoryFunction); - - auto context = isolate->GetCurrentContext(); - - auto requireInternalFunc = Local::New(isolate, *m_requireFunction); - - Local args[6] { - requireInternalFunc, - ArgConverter::ConvertToV8String(isolate, dirName), - Integer::New(isolate, static_cast(options.policy)), - Number::New(isolate, options.deadlineSeconds), - v8::Boolean::New(isolate, options.timeoutBehavior == - ModuleEvaluationOptions::TimeoutBehavior::kThrow), - v8::Boolean::New(isolate, options.pumpRunLoop) - }; - Local result; - auto thiz = Object::New(isolate); - // The factory cannot throw, but entering it is an interrupt check: a - // terminate() that reached this isolate since its last one surfaces - // here and stays pending for the caller to unwind with. - if (!requireFuncFactory->Call(context, thiz, 6, args).ToLocal(&result)) { - return MaybeLocal(); - } - - NS_CHECK(result->IsFunction()); - - requireFunc = result.As(); - - auto poFunc = new Persistent(isolate, requireFunc); - - m_requireCache.emplace(cacheKey, poFunc); - } - - return requireFunc; -} - -void ModuleInternal::CreateRequireCallback(const v8::FunctionCallbackInfo& args) { - Isolate* isolate = args.GetIsolate(); - if (args.Length() < 1 || !args[0]->IsString()) { - isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String( - isolate, "createRequire expects a base directory string"))); - return; - } - - Runtime* runtime = Runtime::TryGetRuntime(isolate); - ModuleInternal* moduleInternal = runtime != nullptr ? runtime->GetModuleInternal() : nullptr; - if (moduleInternal == nullptr) { - isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String( - isolate, "createRequire is unavailable: this isolate has no module loader"))); - return; - } - - string dirName = ArgConverter::ConvertToString(args[0].As()); - const bool pumping = args.Length() > 1 && args[1]->BooleanValue(isolate); - ModuleEvaluationOptions options = RequireEvaluationOptions( - pumping ? ModuleEvaluationPolicy::kSyncPumping : ModuleEvaluationPolicy::kSyncStrict); - - // ns-module.js has already validated these and passes undefined for anything - // the caller left out, so each present value simply overrides its default. - if (args.Length() > 2 && args[2]->IsNumber()) { - double deadlineSeconds = args[2].As()->Value(); - // A NaN or infinite window makes the pump's deadline arithmetic - // undefined, and a non-positive one is no window at all. - if (std::isfinite(deadlineSeconds) && deadlineSeconds > 0.0) { - options.deadlineSeconds = deadlineSeconds; - } - } - if (args.Length() > 3 && args[3]->IsBoolean()) { - options.timeoutBehavior = args[3]->BooleanValue(isolate) - ? ModuleEvaluationOptions::TimeoutBehavior::kThrow - : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; - } - if (args.Length() > 4 && args[4]->IsBoolean()) { - options.pumpRunLoop = args[4]->BooleanValue(isolate); - } - - Local require; - if (moduleInternal->GetRequireFunction(isolate, dirName, options).ToLocal(&require)) { - args.GetReturnValue().Set(require); - } -} - -bool ModuleInternal::InstallCreateRequireBinding(Local context, Local binding) { - Isolate* isolate = v8::Isolate::GetCurrent(); - Local fn; - if (!Function::New(context, ModuleInternal::CreateRequireCallback).ToLocal(&fn)) { - return false; - } - fn->SetName(ArgConverter::ConvertToV8String(isolate, "createRequire")); - return binding->CreateDataProperty(context, - ArgConverter::ConvertToV8String(isolate, "createRequire"), - fn) - .FromMaybe(false); -} - -// Node's `determineSpecificType` (lib/internal/errors.js), so an -// ERR_INVALID_ARG_TYPE-shaped message reads the same here as it does there. -// Deliberately side-effect free: no getter, no user `toString`, no `inspect`. -static std::string DescribeValueForTypeError(Isolate* isolate, Local value) { - if (value.IsEmpty() || value->IsUndefined()) { - return "undefined"; - } - if (value->IsNull()) { - return "null"; - } - - if (value->IsFunction()) { - std::string name = ArgConverter::ToString(isolate, value.As()->GetName()); - return name.empty() ? "an instance of Function" : "function " + name; - } - - if (value->IsObject()) { - std::string ctorName = ArgConverter::ToString(isolate, - value.As()->GetConstructorName()); - return ctorName.empty() ? "an object" : "an instance of " + ctorName; - } - - // A primitive: `type ()`. - const char* typeName = "object"; - std::string rendered; - if (value->IsBoolean()) { - typeName = "boolean"; - rendered = value->IsTrue() ? "true" : "false"; - } else if (value->IsNumber()) { - typeName = "number"; - double number = value.As()->Value(); - // String(-0) is "0", but Node renders the sign, and losing it here would - // hide exactly the distinction the message is meant to surface. - rendered = (number == 0 && std::signbit(number)) ? "-0" - : ArgConverter::ToString(isolate, value); - } else if (value->IsBigInt()) { - typeName = "bigint"; - rendered = ArgConverter::ToString(isolate, value) + "n"; - } else if (value->IsSymbol()) { - typeName = "symbol"; - Local description = value.As()->Description(isolate); - rendered = "Symbol(" + (description->IsUndefined() - ? std::string() - : ArgConverter::ToString(isolate, description)) + - ")"; - } else { - rendered = ArgConverter::ToString(isolate, value); - } - - if (rendered.size() > 28) { - rendered = rendered.substr(0, 25) + "..."; - } - return "type " + std::string(typeName) + " (" + rendered + ")"; -} - -void ModuleInternal::DispatchRequire(const v8::FunctionCallbackInfo& args, - bool honorEvaluationOptions) { - auto isolate = args.GetIsolate(); - - // Every path below assumes a string specifier — the builtin probe, the - // http(s) guard and the filesystem resolution all read it — so reject a - // non-string before any of them rather than casting one unchecked. - if (args.Length() < 1 || !args[0]->IsString()) { - Local received = args.Length() < 1 ? Local() : args[0]; - isolate->ThrowException(Exception::TypeError(ArgConverter::ConvertToV8String( - isolate, "The \"id\" argument must be of type string. Received " + - DescribeValueForTypeError(isolate, received)))); - return; - } - - try { - auto thiz = static_cast(args.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); - thiz->RequireCallbackImpl(args, honorEvaluationOptions); - } catch (NativeScriptException& e) { - e.ReThrowToV8(); - } catch (std::exception e) { - stringstream ss; - ss << "Error: c++ exception: " << e.what() << endl; - NativeScriptException nsEx(ss.str()); - nsEx.ReThrowToV8(); - } catch (...) { - NativeScriptException nsEx(std::string("Error: c++ exception!")); - nsEx.ReThrowToV8(); - } -} - -void ModuleInternal::RequireCallback(const v8::FunctionCallbackInfo& args) { - DispatchRequire(args, true /* honorEvaluationOptions */); -} - -void ModuleInternal::RequirePublicCallback(const v8::FunctionCallbackInfo& args) { - DispatchRequire(args, false /* honorEvaluationOptions */); -} - -void ModuleInternal::RequireCallbackImpl(const v8::FunctionCallbackInfo& args, - bool honorEvaluationOptions) { - auto isolate = args.GetIsolate(); - - if (args.Length() < 2) { - throw NativeScriptException(string("require should be called with at least two parameters")); - } - if (!args[0]->IsString()) { - throw NativeScriptException(string("require's first parameter should be string")); - } - if (!args[1]->IsString()) { - throw NativeScriptException(string("require's second parameter should be string")); - } - - string moduleName = ArgConverter::ConvertToString(args[0].As()); - - // Builtin modules resolve before any path handling, so they can never be - // shadowed by a file or a package, and an unknown one fails as a missing - // builtin rather than as a missing file. Only prefixed specifiers get - // here: a bare `util` still resolves through npm. - if (NsBuiltinModules::IsBuiltinScheme(moduleName)) { - auto context = isolate->GetCurrentContext(); - Local exports; - if (NsBuiltinModules::GetExports(context, moduleName).ToLocal(&exports)) { - args.GetReturnValue().Set(exports); - } else if (!NsBuiltinModules::IsRegistered(moduleName)) { - isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String( - isolate, NsBuiltinModules::NotFoundMessage(moduleName)))); - } - return; - } - - // Node-API addons claim a bare name only, so a path can never be diverted - // into the addon registry, and builtins keep priority over both. - if (IsBareSpecifier(moduleName) && NapiModules::IsRegistered(moduleName)) { - auto context = isolate->GetCurrentContext(); - Local exports; - if (NapiModules::GetExports(context, moduleName).ToLocal(&exports)) { - args.GetReturnValue().Set(exports); - } else if (!isolate->HasPendingException()) { - isolate->ThrowException(Exception::Error(ArgConverter::ConvertToV8String( - isolate, "Node-API module '" + moduleName + "' failed to initialize"))); - } - return; - } - - // URL-based modules must be loaded via dynamic import(). - if (!NormalizeHttpModuleUrl(moduleName).empty()) { - throw NativeScriptException("NativeScript: require() of URL module is not supported: " + - moduleName + ". Use dynamic import() instead."); - } - - tns::instrumentation::Frame frame("RequireCallback " + moduleName); - string callingModuleDirName = ArgConverter::ConvertToString(args[1].As()); - auto isData = false; - - ModuleEvaluationOptions evaluationOptions = - RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict); - if (honorEvaluationOptions) { - // The require factory forwards the options its require was minted with; - // an absent policy is the strict default every ordinary require uses. - ModuleEvaluationPolicy policy = ModuleEvaluationPolicy::kSyncStrict; - if (args.Length() > 2 && args[2]->IsInt32() && - args[2].As()->Value() == - static_cast(ModuleEvaluationPolicy::kSyncPumping)) { - policy = ModuleEvaluationPolicy::kSyncPumping; - } - evaluationOptions = RequireEvaluationOptions(policy); - if (args.Length() > 3 && args[3]->IsNumber()) { - double deadlineSeconds = args[3].As()->Value(); - // A NaN or infinite window makes the pump's deadline arithmetic - // undefined, and a non-positive one is no window at all. - if (std::isfinite(deadlineSeconds) && deadlineSeconds > 0.0) { - evaluationOptions.deadlineSeconds = deadlineSeconds; - } - } - if (args.Length() > 4 && args[4]->IsBoolean()) { - evaluationOptions.timeoutBehavior = - args[4]->BooleanValue(isolate) - ? ModuleEvaluationOptions::TimeoutBehavior::kThrow - : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; - } - if (args.Length() > 5 && args[5]->IsBoolean()) { - evaluationOptions.pumpRunLoop = args[5]->BooleanValue(isolate); - } - } - - auto moduleObj = LoadImpl(isolate, moduleName, callingModuleDirName, isData, evaluationOptions); - - if (isData) { - NS_DCHECK(!moduleObj.IsEmpty()); - - args.GetReturnValue().Set(moduleObj); - } else { - auto context = isolate->GetCurrentContext(); - Local exportsVal; - moduleObj->Get(context, ArgConverter::ConvertToV8String(isolate, "exports")).ToLocal(&exportsVal); - - NS_DCHECK(!exportsVal.IsEmpty()); - - auto exportsObj = exportsVal.As(); - args.GetReturnValue().Set(exportsObj); - } -} - -void ModuleInternal::RequireNativeCallback(const v8::FunctionCallbackInfo& args) { - TNSPERF(); - auto ext = args.Data().As(); - auto funcPtr = reinterpret_cast(ext->Value(v8::kExternalPointerTypeTagDefault)); - funcPtr(args); + nativescript::common::loader::InstallCommonJs(isolate->GetCurrentContext()); } void ModuleInternal::Load(Local context, const string& path) { TNSPERF(); - auto isolate = m_isolate; // The ES module branch compiles and links against // isolate->GetCurrentContext(); a caller that enters the isolate through a // fresh Isolate::Scope has no current context, and CompileModule would - // dereference a null native context. The require branch never needed this - // because Function::Call enters the context it is handed. + // dereference a null native context. Context::Scope context_scope(context); - const bool isHttpModule = IsHttpModulePath(path); - if (isHttpModule || IsESModule(path)) { - if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str()); - } - // The entry runs before this thread's event loop does, so its graph can - // only make progress from the pump inside LoadESModule. - LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); - if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); - } + const ModuleEvaluationOptions waitForTopLevelAwait = + ModuleEvaluationOptions::Require(ModuleEvaluationPolicy::kSyncPumping); + if (nativescript::common::loader::IsEsModuleEntry(path)) { + nativescript::common::loader::LoadEsModule(context, path, waitForTopLevelAwait); return; } - auto globalObject = context->Global(); - auto require = globalObject->Get(context, ArgConverter::ConvertToV8String(isolate, "require")).ToLocalChecked().As(); - Local args[] = { ArgConverter::ConvertToV8String(isolate, path) }; - // A failed entry must throw through this boundary in every build — the - // caller (boot, or a worker's onerror routing) owns the report, and the - // boot backstop must never pump with an exception pending on the isolate. - TryCatch tc(isolate); - Local result; - const bool ok = require->Call(context, globalObject, 1, args).ToLocal(&result); - if (!ok || tc.HasCaught()) { - throw NativeScriptException(tc, "require() failed for module " + path); + // A .js file with ES module syntax comes back still evaluating when its + // top-level await is pending; loading it again waits for that evaluation. + if (!nativescript::common::loader::RunCommonJsEntry(context, path).IsEmpty()) { + nativescript::common::loader::LoadEsModule(context, path, waitForTopLevelAwait); } } -void ModuleInternal::LoadWorker(Local context, const string& path) { +MaybeLocal ModuleInternal::LoadWorker(Local context, const string& path) { TNSPERF(); auto isolate = m_isolate; TryCatch tc(isolate); + MaybeLocal pendingEntry; try { - Load(context, path); + Context::Scope contextScope(context); + pendingEntry = nativescript::common::loader::IsEsModuleEntry(path) + ? nativescript::common::loader::RunEsModuleEntry(context, path) + : nativescript::common::loader::RunCommonJsEntry(context, path); } catch (NativeScriptException& e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + e.ThrowToV8(isolate); + } catch (nativescript::common::Terminated&) { + // A terminating worker reports nothing to its onerror. } if (tc.HasCaught()) { @@ -639,1271 +80,7 @@ void ModuleInternal::LoadWorker(Local context, const string& path) { // Check if `onerror` handle is implemented // Web behaviour - if onerror handle comes before exception throw - execute it, else - bubble up to main's worker object CallbackHandlers::CallWorkerScopeOnErrorHandle(isolate, tc); - } -} - -std::string ModuleInternal::CheckFileExists(Isolate* isolate, const std::string& path, const std::string& baseDir) { - JEnv env; - JniLocalRef jsModulename(env.NewStringUTF(path.c_str())); - JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str())); - - // Throws a NativeScriptException (through JEnv's pending-exception check) - // when nothing resolves, so the conversion below only ever sees a hit. - JniLocalRef jsModulePath(env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID, - (jstring) jsModulename, - (jstring) jsBaseDir)); - - return ArgConverter::jstringToString((jstring) jsModulePath); -} - -// The trailing extension without its dot, or an empty string when the last -// segment has none. A leading dot names a hidden file, not an extension. -static std::string PathExtension(const std::string& path) { - size_t dot = path.find_last_of('.'); - if (dot == std::string::npos || dot + 1 >= path.size()) { - return std::string(); - } - size_t slash = path.find_last_of('/'); - if (slash != std::string::npos && (dot < slash || dot == slash + 1)) { - return std::string(); - } - return path.substr(dot + 1); -} - -Local ModuleInternal::LoadImpl(Isolate* isolate, const string& moduleName, - const string& baseDir, bool& isData, - const ModuleEvaluationOptions& options) { - auto pathKind = GetModulePathKind(moduleName); - auto cachePathKey = (pathKind == ModulePathKind::Global) ? moduleName : (baseDir + "*" + moduleName); - - Local result; - - DEBUG_WRITE(">>LoadImpl cachePathKey=%s", cachePathKey.c_str()); - - auto it = m_loadedModules.find(cachePathKey); - - if (it == m_loadedModules.end()) { - std::string path; - - // Search App System libs - std::string sys_lib("system_lib://"); - if (moduleName.rfind(sys_lib, 0) == 0) { - auto pos = moduleName.find(sys_lib); - path = std::string(moduleName); - path.replace(pos, sys_lib.length(), ""); - } else { - // Handle tilde path resolution before calling Java path resolution - std::string resolvedModuleName = moduleName; - if (!moduleName.empty() && moduleName[0] == '~') { - // Convert ~/path to ApplicationPath/path - std::string tail = moduleName.size() >= 2 && moduleName[1] == '/' ? moduleName.substr(2) : moduleName.substr(1); - resolvedModuleName = Constants::APP_ROOT_FOLDER_PATH + "/" + tail; - - // For .mjs files with tilde paths, use resolved path directly - if (Util::EndsWith(resolvedModuleName, ".mjs")) { - path = resolvedModuleName; - } else { - // For non-.mjs files, still use Java resolution with the resolved name - JEnv env; - JniLocalRef jsModulename(env.NewStringUTF(resolvedModuleName.c_str())); - JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str())); - JniLocalRef jsModulePath( - env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID, - (jstring) jsModulename, (jstring) jsBaseDir)); - - path = ArgConverter::jstringToString((jstring) jsModulePath); - } - } else { - JEnv env; - JniLocalRef jsModulename(env.NewStringUTF(moduleName.c_str())); - JniLocalRef jsBaseDir(env.NewStringUTF(baseDir.c_str())); - JniLocalRef jsModulePath( - env.CallStaticObjectMethod(MODULE_CLASS, RESOLVE_PATH_METHOD_ID, - (jstring) jsModulename, (jstring) jsBaseDir)); - - path = ArgConverter::jstringToString((jstring) jsModulePath); - } - } - - auto it2 = m_loadedModules.find(path); - - if (it2 == m_loadedModules.end()) { - if (Util::EndsWith(path, ".js") || Util::EndsWith(path, ".mjs") || Util::EndsWith(path, ".so")) { - isData = false; - result = LoadModule(isolate, path, cachePathKey, options); - } else if (Util::EndsWith(path, ".json")) { - isData = true; - result = LoadData(isolate, path); - } else { - string errMsg = "Unsupported file extension: " + PathExtension(path); - throw NativeScriptException(errMsg); - } - } else { - auto& cacheEntry = it2->second; - isData = cacheEntry.isData; - result = Local::New(isolate, *cacheEntry.obj); - } - } else { - auto& cacheEntry = it->second; - isData = cacheEntry.isData; - result = Local::New(isolate, *cacheEntry.obj); - } - - return result; -} - -static bool NamespaceHasOwn(Isolate* isolate, Local context, Local ns, - const char* name) { - return ns->HasOwnProperty(context, ArgConverter::ConvertToV8String(isolate, name)) - .FromMaybe(false); -} - -// The live compiled module behind a registry key, or empty. -static Local RegisteredModuleForPath(Isolate* isolate, const std::string& canonicalPath) { - auto* registryPtr = ModuleRegistryFor(isolate); - if (registryPtr == nullptr) { - return Local(); - } - auto it = registryPtr->find(canonicalPath); - if (it == registryPtr->end()) { - return Local(); - } - return it->second.Get(isolate); -} - -// What `require()` of an ES module hands back, per Node's -// populateCJSExportsFromESM: an explicit `module.exports` export wins outright; -// a namespace with no default export, or one that already declares -// __esModule, passes through untouched; everything else gets the facade so -// transpiled consumers reading `_mod.__esModule ? _mod.default : _mod` find the -// default. Export names are arbitrary strings, hence the own-property probes. -static Local RequireExportsForNamespace(Isolate* isolate, Local context, - Local ns, - const std::string& canonicalPath) { - TryCatch tc(isolate); - - if (NamespaceHasOwn(isolate, context, ns, "module.exports")) { - Local moduleExports; - if (!ns->Get(context, ArgConverter::ConvertToV8String(isolate, "module.exports")) - .ToLocal(&moduleExports)) { - throw NativeScriptException( - tc, "Cannot read the 'module.exports' export of " + canonicalPath); - } - return moduleExports; - } - - bool hasDefault = NamespaceHasOwn(isolate, context, ns, "default"); - bool hasEsModuleMarker = NamespaceHasOwn(isolate, context, ns, "__esModule"); - if (!hasDefault || hasEsModuleMarker) { - return ns; - } - - Local target = RegisteredModuleForPath(isolate, canonicalPath); - if (target.IsEmpty()) { - // The load that produced this namespace registered the module under this - // very key, so a miss means the registry and the namespace disagree — - // returning the bare namespace would drop __esModule and misroute every - // transpiled consumer downstream. - throw NativeScriptException( - "require() cannot build the exports facade for " + canonicalPath + - ": the module evaluated but is absent from the registry under its canonical key"); - } - - Local facade; - if (!GetOrCreateRequireFacade(isolate, context, target, canonicalPath).ToLocal(&facade)) { - throw NativeScriptException("Cannot build the require() exports facade for " + - canonicalPath); - } - return facade->GetModuleNamespace(); -} - -Local ModuleInternal::LoadModule(Isolate* isolate, const string& modulePath, - const string& moduleCacheKey, - const ModuleEvaluationOptions& options) { - string frameName("LoadModule " + modulePath); - tns::instrumentation::Frame frame(frameName); - CrashBreadcrumbs::ModuleScope moduleBreadcrumb(modulePath.c_str()); - Local result; - - auto context = isolate->GetCurrentContext(); - auto moduleObj = Object::New(isolate); - auto exportsObj = Object::New(isolate); - auto exportsPropName = ArgConverter::ConvertToV8String(isolate, "exports"); - moduleObj->Set(context, exportsPropName, exportsObj); - auto fullRequiredModulePath = ArgConverter::ConvertToV8String(isolate, modulePath); - moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "filename"), fullRequiredModulePath); - - auto poModuleObj = new Persistent(isolate, moduleObj); - TempModule tempModule(this, modulePath, moduleCacheKey, poModuleObj); - - TryCatch tc(isolate); - - // Check if this is an ES module (.mjs) - if (Util::EndsWith(modulePath, ".mjs")) { - // require()'s route into the ES module system, which cannot wait: an - // async graph is refused rather than pumped. - Local moduleNamespace = LoadESModule(isolate, modulePath, options); - - // A load that produced no namespace produced no module either — an - // isolate torn down mid-load, or a graph that never settled. Caching the - // empty exports object would intern that failure for the process. - if (moduleNamespace.IsEmpty()) { - throw NativeScriptException("ES module load returned empty value " + modulePath); - } - if (!moduleNamespace->IsObject()) { - throw NativeScriptException("Failed to load ES module " + modulePath); - } - - // `module.exports` is what Node's populateCJSExportsFromESM produces for - // this namespace, not the namespace itself. - Local esmExports = RequireExportsForNamespace(isolate, context, - moduleNamespace.As(), - CanonicalizeRegistryKey(modulePath)); - moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "exports"), esmExports); - - tempModule.SaveToCache(); - result = moduleObj; - return result; - } - - Local moduleFunc; - - if (Util::EndsWith(modulePath, ".js")) { - auto script = LoadScript(isolate, modulePath, fullRequiredModulePath); - - Local moduleFuncValue; - if (!script->Run(context).ToLocal(&moduleFuncValue) || tc.HasCaught()) { - throw NativeScriptException(tc, "Error running script " + modulePath); - } - moduleFunc = moduleFuncValue.As(); - } else if (Util::EndsWith(modulePath, ".so")) { - // Registrations from libraries this loader did not dlopen (statically - // linked addons whose constructors ran at app start) must not be - // attributed to whatever `.so` happens to load next. - NapiModules::ClaimPendingModule(); - - auto handle = dlopen(modulePath.c_str(), RTLD_LAZY); - if (handle == nullptr) { - auto error = dlerror(); - string errMsg(error != nullptr ? error : "dlopen failed for " + modulePath); - throw NativeScriptException(errMsg); - } - - // A library whose constructors registered a Node-API module is a - // Node-API addon: its exports come from the addon registry (Node's - // dlopen consumes `modpending` the same way). A library carrying the - // NAPI_MODULE / node-addon-api registration symbol instead is - // initialized through it — this is also the path a *re*-dlopen of an - // already-loaded addon takes, since constructors only run on first - // load. NSMain remains the protocol for plain native modules. - string napiModuleName = NapiModules::ClaimPendingModule(); - void* napiInitSymbol = napiModuleName.empty() - ? dlsym(handle, "napi_register_module_v1") - : nullptr; - if (!napiModuleName.empty() || napiInitSymbol != nullptr) { - Local napiExports; - bool initialized = napiModuleName.empty() - ? NapiModules::InitAddonFromSymbol(context, napiInitSymbol, modulePath).ToLocal(&napiExports) - : NapiModules::GetExports(context, napiModuleName).ToLocal(&napiExports); - if (!initialized || tc.HasCaught()) { - throw NativeScriptException(tc, "Error initializing Node-API module " + - (napiModuleName.empty() ? modulePath : napiModuleName)); - } - moduleObj->Set(context, exportsPropName, napiExports); - tempModule.SaveToCache(); - result = moduleObj; - return result; - } - - auto func = dlsym(handle, "NSMain"); - if (func == nullptr) { - string errMsg("Cannot find 'NSMain' in " + modulePath); - throw NativeScriptException(errMsg); - } - auto extFunc = External::New(isolate, func, v8::kExternalPointerTypeTagDefault); - auto ft = FunctionTemplate::New(isolate, RequireNativeCallback, extFunc); - auto maybeFunc = ft->GetFunction(context); - if (maybeFunc.IsEmpty() || tc.HasCaught()) { - throw NativeScriptException(tc, "Cannot create native module function callback"); - } - moduleFunc = maybeFunc.ToLocalChecked(); - } else { - string errMsg = "Unsupported file extension: " + PathExtension(modulePath); - throw NativeScriptException(errMsg); - } - - SET_PROFILER_FRAME(); - - auto fileName = ArgConverter::ConvertToV8String(isolate, modulePath); - // dirname() semantics without its fixed-size copy: module paths can - // exceed any stack buffer (PATH_MAX is 4096 and node_modules nests). - const size_t lastSlash = modulePath.find_last_of('/'); - string strDirName = lastSlash == string::npos ? "." - : lastSlash == 0 ? "/" - : modulePath.substr(0, lastSlash); - auto dirName = ArgConverter::ConvertToV8String(isolate, strDirName); - // A module's own require inherits the options it was loaded under, so a - // pumping require's whole dependency tree keeps pumping. - Local require; - if (!GetRequireFunction(isolate, strDirName, options).ToLocal(&require)) { - throw NativeScriptException(tc, "Cannot create the require function for " + modulePath); - } - Local requireArgs[5] { - moduleObj, exportsObj, require, fileName, dirName - }; - - moduleObj->Set(context, ArgConverter::ConvertToV8String(isolate, "require"), require); - - auto moduleIdProp = ArgConverter::ConvertToV8String(isolate, "id"); - const auto readOnlyFlags = static_cast(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); - Maybe success = moduleObj->DefineOwnProperty(isolate->GetCurrentContext(), moduleIdProp, fileName, readOnlyFlags); - if (success.IsNothing()) { - throw NativeScriptException(string("Couldn't execute method 'DefineOwnProperty' on 'moduleObj' in 'Module::LoadModule'.")); - } - - auto thiz = Object::New(isolate); - auto extendsName = ArgConverter::ConvertToV8String(isolate, "__extends"); - Local extendsFunc; - if (!context->Global()->Get(context, extendsName).ToLocal(&extendsFunc) || tc.HasCaught()) { - throw NativeScriptException(tc, "Cannot read '__extends' while loading " + modulePath); - } - thiz->Set(context, extendsName, extendsFunc); - moduleFunc->Call(context, thiz, sizeof(requireArgs) / sizeof(Local ), requireArgs); - - if (tc.HasCaught()) { - throw NativeScriptException(tc, "Error calling module function "); - } - - tempModule.SaveToCache(); - result = moduleObj; - - return result; -} - -Local