You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit d57c103
Browse filesBrowse the repository at this point in the historyBrowse files
feat(runtime): ns:worker_threads and ns:url builtin modules (#2166)
### Description
Two new public builtin modules, ported from the iOS runtime. As there,
each one is a commit: `ns:worker_threads` first, then `ns:url`.
- `ns:worker_threads` mirrors NativeScript/ios#494.
- `ns:url` mirrors NativeScript/ios#497.
The `ns:` module owns the implementation. The matching `node:` shim now
reads from it instead of from the globals, the way `node:util` sits over
`ns:util`.
```js
import { Worker } from "ns:worker_threads";
import { URL, fileURLToPath, pathToFileURL } from "ns:url";
const worker = new Worker("./heavy.js", {
android: { priority: "lessFavorable" },
ios: { priority: "utility" }, // ignored here; read by the iOS runtime
resourceLimits: { maxOldGenerationSizeMb: 64 },
});
pathToFileURL("/app/my file.js").href; // "file:///app/my%20file.js"
```
#### `ns:worker_threads`
- Exports `Worker` only, frozen.
- The binding builds `Worker` from the template that
`CallbackHandlers::InitWorkerConstructor` puts on the global template
and keeps in `RuntimeState`. V8 instantiates a template once per
context, so the module returns the same function the global was created
with, even if the app has reassigned `globalThis.Worker`.
- `node:worker_threads` now gets its constructor from
`require("ns:worker_threads")` instead of `globalThis.Worker`.
#### `ns:url`
- Exports `URL`, `URLSearchParams`, `fileURLToPath` and `pathToFileURL`.
That is exactly `node:url`'s export set.
- The converters moved verbatim from `node-url.js`. `node:url` is now a
re-export shim on its own frozen module object, so `require("node:url")`
also gains `URL` and `URLSearchParams`, like Node's `node:url`.
`URLPattern` stays a global only.
- `URLImpl::Init` and `URLSearchParamsImpl::Init` now install the
globals and keep their templates, the same way as `Worker`.
- It also ports the two runtime fixes from the iOS PR:
- `URL` gets `toJSON` (returns `href`).
- The `searchParams` wrapper in `blob-url.js` passes `delete`'s value
argument through, so `url.searchParams.delete(name, value)` no longer
removes every pair with that name.
#### Types: Android extends the iOS declarations
The package now ships `types/`, with `"types"` in `package.json` and a
`copyTypes` step in the npm packaging.
The iOS package's `types/` stays the source of truth for the shared
`ns:` surface. If two `declare module` blocks both declare `Worker`,
TypeScript reports a conflict, so the Android files declare only new
names and merge into the iOS ones:
- `types/ns-worker-threads-android.d.ts` adds `WorkerAndroidPriority`,
`WorkerAndroidOptions`, and the `android` and deprecated
`androidPriority` options. They go on both the module's `WorkerOptions`
and the global `WorkerOptions`, so `new Worker(path, { android })`
type-checks whether you use the module's constructor or the global one.
- The file is a script with no top-level import or export. That makes
its `declare module` block merge with the iOS one instead of becoming a
module augmentation, which would fail to compile without the iOS types.
- The rest of iOS's `ns-worker-threads.d.ts` also describes Android
as-is: the `resourceLimits` keys (including `jsDispatchTableSizeMb`),
and the error event's `error: null` with `stackTrace`, `filename` and
`lineno`.
- `ns:url` needs no Android declaration: Android's
`URL`/`URLSearchParams` match iOS's `types/ns-url.d.ts` member for
member, including value-aware `has`/`delete`, `size`, `canParse` and the
blob-URL statics.
Checked with `tsc --strict` (TypeScript 5.9) against the iOS
`origin/main` types. All of these compile clean, and every
`@ts-expect-error` (bad priority name, non-object `android`, iOS
priority name under `android`, bad name on the global constructor)
fires:
| program | iOS then Android | Android then iOS | Android only |
|---|---|---|---|
| no DOM lib (`es2022`) | ✅ | ✅ | ✅ |
| DOM lib (`es2022,dom`) | ✅ | ✅ | ✅ |
**Known gap:** a program that includes only the Android types sees the
Android additions but not `ns:worker_threads`'s `Worker` or any of
`ns:url`. It needs `@nativescript/ios`'s types too. Removing that
requirement means moving the shared declarations into a package both
runtimes depend on. That is a separate change.
#### Docs
- `docs/ns-builtin-modules.md`:
- new `ns:url` and `ns:worker_threads` sections; the converter semantics
and the error-message table moved from the `node:url` row into `ns:url`;
- updated `node:url` and `node:worker_threads` rows;
- the public-row count is now eleven;
- the "Android ships no `.d.ts`" note is replaced.
- `docs/worker-threads.md`:
- new "Worker options" section covering `android.priority` and
`resourceLimits`, which were never documented;
- the `resourceLimits` export row no longer says the runtime imposes no
per-worker limits.
### Related Pull Requests
- NativeScript/ios#494 (`ns:worker_threads`)
- NativeScript/ios#497 (`ns:url`)
### Does your pull request have unit tests?
Yes:
- `testNsWorkerThreads.js` and `testNsUrl.js` check:
- the frozen export set;
- identity with the globals;
- the per-realm singleton, through both `require` and `import()`;
- that each module is a separate object from its `node:` shim;
- through a worker fixture that reassigns the global before its first
`require`, that the module still exports the original constructor.
- `testNsWorkerThreads.js` also constructs a worker with both `android`
and `ios` options plus `resourceLimits`, and checks the resulting thread
priority.
- `testNsUrl.js` also checks that `node:url` re-exports every member
unchanged.
- `testNodeUrlModule.js` now expects the four-name export set.
- `testURLImpl.js` covers `toJSON`. `testURLSearchParamsImpl.js` covers
value-aware `searchParams.delete`.
Full suite (`./gradlew runtestsAndVerifyResults`) on an API 36 arm64
emulator: 1975 specs, 0 failures. `npm run lint` is clean.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Added `ns:url` support for URL constructors and file URL/path
conversion utilities.
* Added `ns:worker_threads` support, including Android worker-priority
options and resource limits.
* Included TypeScript declarations with the package.
* **Bug Fixes**
* Improved URL JSON serialization and support for deleting URL search
parameters by name and value.
* **Documentation**
* Added guidance for the URL and worker-thread modules and their
options.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Copy file name to clipboardExpand all lines: docs/ns-builtin-modules.md
+92-37Lines changed: 92 additions & 37 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -620,6 +620,85 @@ workers for the change to reach them.** A worker started after the
620
620
`configureLoader` call resolves through the new vocabulary; a live worker
621
621
never observes a later reconfiguration.
622
622
623
+
### `ns:url`
624
+
625
+
The runtime's own `URL` and `URLSearchParams`, reachable by specifier, plus
626
+
the two path/URL converters. Its export set is exactly `node:url`'s, so that
627
+
shim re-exports every member unchanged. **Experimental.**
628
+
629
+
| export | description |
630
+
|---|---|
631
+
| `URL` | The runtime's `URL` constructor: the very function the global of that name was created with, so `require("ns:url").URL===globalThis.URL` unless the app has reassigned the global. `toJSON()` returns `href`, as WHATWG specifies, so `JSON.stringify(url)` is the href string. |
632
+
| `URLSearchParams` | Likewise the runtime's `URLSearchParams` constructor. |
633
+
| `fileURLToPath(url)` | Converts a `file:` URL (a string, or any object with a string `href`, so a `URL` from another realm works) to an absolute path, percent-decoding it. |
634
+
| `pathToFileURL(path)` | Converts an absolute path to a `file:` URL, returning this module's `URL`. |
635
+
636
+
`URLPattern` stays a global only: Node's `node:url` has no counterpart, and
637
+
nothing in the module needs it.
638
+
639
+
The module exists so that typed code can name the URL classes without
640
+
depending on what `globalThis.URL` resolves to in the program's type
641
+
environment. The iOS runtime's `types/ns-url.d.ts` declares it, along with
642
+
the global `URL` and `URLSearchParams`; Android adds nothing to that surface,
643
+
so this package ships no declaration of its own for it.
644
+
645
+
The converters parse through the module's own `URL`, so `file://localhost/x` is
646
+
accepted (the URL spec folds a `localhost` authority to none) while any other
647
+
host throws, and the query and fragment are never part of the path.
648
+
`fileURLToPath` rejects a non-`file:` scheme and rejects `%2F`in the path
649
+
rather than decoding a separator into it. `pathToFileURL` returns a real `URL`
650
+
and requires an **absolute** path:Node resolves a relative one against the
651
+
process working directory, and there is no such thing here.
| argument is neither a string nor a URL-like object, or is unparseable | `The "path" argument must be of type string or an instance of URL.` |
668
+
| non-`file:` scheme | `The URL must be of scheme file` |
669
+
| a host other than `localhost` or empty | `File URL host must be "localhost" or empty` |
670
+
| `%2F` in the path | `File URL path must not include encoded / characters` |
671
+
| `pathToFileURL` given a non-string | `The "path" argument must be of type string.` |
672
+
| `pathToFileURL` given a relative path | `The "path" argument must be an absolute path.` |
673
+
674
+
### `ns:worker_threads`
675
+
676
+
The runtime's own `Worker`, reachable by specifier; the `node:worker_threads`
677
+
shim adapts it. **Experimental.**
678
+
679
+
|export|description|
680
+
|---|---|
681
+
|`Worker`| The runtime's `Worker` constructor: the very function the global of that name was created with, so `require("ns:worker_threads").Worker === globalThis.Worker` unless the app has reassigned the global. Its constructor options — `android.priority` and Node's `resourceLimits` — are described in [worker-threads.md](worker-threads.md#worker-options). |
682
+
683
+
```js
684
+
import { Worker } from "ns:worker_threads";
685
+
686
+
const worker = new Worker("./heavy.js", {
687
+
android: { priority: "lessFavorable" },
688
+
resourceLimits: { maxOldGenerationSizeMb: 64 },
689
+
});
690
+
```
691
+
692
+
The module exists so that typed code can name the runtime's constructor and
693
+
its options without depending on what `globalThis.Worker` resolves to in the
694
+
program's type environment. The iOS runtime's `types/ns-worker-threads.d.ts`
695
+
declares the module, its cross-platform options and the global `Worker`; this
696
+
package's `types/ns-worker-threads-android.d.ts` adds `android` (and the
697
+
deprecated `androidPriority`) to both the module's and the global
698
+
`WorkerOptions`, merging with those declarations rather than restating them.
699
+
Cross-platform code can pass `ios` and `android` together: each runtime reads
700
+
its own object and ignores the other's.
701
+
623
702
### `node:` compatibility shims
624
703
625
704
The same registry serves the `node:` scheme with**compatibility shims** so
@@ -659,38 +738,9 @@ unmodified where a shim exists:
659
738
|module|exports| notes |
660
739
|---|---|---|
661
740
|`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. |
662
-
| `node:url` | `fileURLToPath`, `pathToFileURL` | Node-strict converters between `file:` URLs and paths. Documented as partial — no `URL`/`URLSearchParams` re-exports (both are globals), no legacy `url.parse`/`format`/`resolve`. |
741
+
| `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 throwNode's messages. Documented as partial — no legacy `url.parse`/`format`/`resolve`, and no `URLPattern` (Node's `node:url` has none). |
663
742
|`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. |
664
-
| `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 runtime's own `Worker`. It has no `ns:` counterpart — the 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. |
665
-
666
-
`node:url`'s parsing goes through the URL intrinsic, so `file://localhost/x` is
667
-
accepted (the URL spec folds a `localhost` authority to none) while any other
668
-
host throws, and the query and fragment are never part of the path.
669
-
`fileURLToPath` rejects a non-`file:` scheme and rejects `%2F`in the path
670
-
rather than decoding a separator into it. `pathToFileURL` returns a real `URL`
671
-
and requires an **absolute** path:Node resolves a relative one against the
672
-
process working directory, and there is no such thing here.
| argument is neither a string nor a URL-like object, or is unparseable | `The "path" argument must be of type string or an instance of URL.` |
689
-
| non-`file:` scheme | `The URL must be of scheme file` |
690
-
| a host other than `localhost` or empty | `File URL host must be "localhost" or empty` |
691
-
| `%2F` in the path | `File URL path must not include encoded / characters` |
692
-
| `pathToFileURL` given a non-string | `The "path" argument must be of type string.` |
693
-
| `pathToFileURL` given a relative path | `The "path" argument must be an absolute path.` |
743
+
| `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. |
694
744
695
745
## Loading ES modules
696
746
@@ -976,9 +1026,9 @@ resolvers read the same table differently:
976
1026
- The **`ns:`/`node:` resolver** — the app-facing one, behind `require()`,
977
1027
`import` and `import()` — serves only rows *not* marked internal-only. An
978
1028
internal-only specifier fails exactly as a name absent from the table does.
979
-
Nine rows are public today: `ns:interop`, `ns:interop/android`, `ns:module`,
Copy file name to clipboardExpand all lines: docs/worker-threads.md
+44-2Lines changed: 44 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -49,12 +49,12 @@ means deliberately unsupported.
49
49
|`markAsUncloneable(obj)`| real | Brands `obj` so serializing it at all is a `DataCloneError`, in `structuredClone` and every `postMessage` alike. |
50
50
|`setEnvironmentData(key, value)`| real, deviates | Clones and stores process-wide. No per-thread snapshot — see below. Passing `undefined` (or omitting the value) deletes the key. |
51
51
|`getEnvironmentData(key)`| real, deviates | Deserializes a fresh copy per read, on any isolate. |
52
-
|`resourceLimits`| shim | Always `{}`; the runtime imposes no per-worker limits and reports none. |
52
+
|`resourceLimits`| shim | Always `{}`. The export reports nothing; the `resourceLimits` constructor option is real — see [Worker options](#worker-options). |
53
53
|`SHARE_ENV`| shim | Exported so the spelling resolves, but inert — see below. |
54
54
|`threadName`| shim | Always `undefined`. |
55
55
|`workerData`| shim | Always `null` — see below. |
56
56
|`parentPort`| shim |`null` on the main isolate. Inside a worker, a `MessagePort`-shaped `EventTarget` over the worker's existing parent channel: `postMessage` forwards to the global `postMessage`, `message`/`messageerror` are re-dispatched from the worker global scope, `start()` and `close()` are no-ops. It is **not** a real port: not transferable, no queue of its own. |
57
-
|`Worker`| shim | A class over the runtime's global `Worker` with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. An `error` listener receives the worker's error rebuilt as an `Error` (see below). `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`androidPriority`) ride along untouched — the native constructor ignores keys it does not know. |
57
+
|`Worker`| shim | A class over the runtime's `Worker`(the one [`ns:worker_threads`](ns-builtin-modules.md#nsworker_threads) exports) with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. An `error` listener receives the worker's error rebuilt as an `Error` (see below). `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`android`, `resourceLimits` and the deprecated `androidPriority`) ride along untouched — the native constructor ignores keys it does not know. |
58
58
|`postMessageToThread`| throws |`Error: postMessageToThread is not supported in this runtime`. |
59
59
|`moveMessagePortToContext`| throws |`Error: moveMessagePortToContext is not supported in this runtime`. |
60
60
|`locks`| absent | Web Locks are not implemented; the property does not exist. |
@@ -271,6 +271,48 @@ it has no way out: a `message` event hands it over in `event.ports`, while
271
271
close such a port as soon as it arrives, so its sibling learns the channel is
272
272
gone instead of queueing into a port nothing can ever read.
273
273
274
+
## Worker options
275
+
276
+
The runtime's `Worker` constructor takes two options of its own, and the
277
+
`node:worker_threads` shim passes both through unchanged. Unknown keys inside
278
+
either object are ignored, so a later runtime can add more without breaking an
279
+
older one, and cross-platform code can pass the iOS runtime's `ios` object
280
+
alongside `android`. `null` for either object means the same as leaving it
`urgentDisplay`, `video`, `audio`, `urgentAudio`) or a nice value. A number
292
+
outside -20..19 is clamped into it; `NaN`, any other type and an unknown name
293
+
throw a `TypeError`, as does an `android` that is not an object. Omitted, the
294
+
thread runs at `background` (nice 10). Lowering a nice value below 0 may need
295
+
a privilege the app does not hold.
296
+
297
+
The top-level `androidPriority` is the deprecated spelling: it takes the same
298
+
values (a `NaN` there means `default`), logs a deprecation warning once per
299
+
process, and loses to `android.priority` when both are given.
300
+
301
+
### `resourceLimits`
302
+
303
+
Node's shape, in megabytes:
304
+
305
+
| key | effect |
306
+
|---|---|
307
+
|`maxOldGenerationSizeMb`| Caps the worker isolate's old generation. |
308
+
|`maxYoungGenerationSizeMb`| Caps the worker isolate's young generation. |
309
+
|`jsDispatchTableSizeMb`| NativeScript extension: the isolate's JS dispatch table reservation, a whole number from 1 to 256. Worker isolates reserve 64 MB when it is omitted; the main isolate keeps V8's default. With a V8 build that cannot size the table, passing it throws an `Error`. |
310
+
311
+
A value that is not a number throws a `TypeError`; a non-finite one, one worth
312
+
less than a byte or one too large to hold in bytes throws a `RangeError`.
313
+
Node's `stackSizeMb` and `codeRangeSizeMb` are ignored, like any other key the
314
+
runtime does not know.
315
+
274
316
## Worker messages
275
317
276
318
The runtime's own `Worker` and the worker global scope are `EventTarget`s that
0 commit comments