Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,12 @@ task copyReadme(type: Copy) {
into "$DIST_PATH"
}

task copyTypes(type: Copy) {
from "$rootDir/types"
include "*.d.ts"
into "$DIST_PATH/types"
}

task createNpmPackage(type: Exec) {
doFirst {
workingDir "$DIST_PATH"
Expand Down Expand Up @@ -422,7 +428,8 @@ copyProjectTemplate.dependsOn(verifyJsParserPackage)
copyPackageJson.dependsOn(copyProjectTemplate)
setPackageVersionInPackageJsonFile.dependsOn(copyPackageJson)
copyReadme.dependsOn(setPackageVersionInPackageJsonFile)
createNpmPackage.dependsOn(copyReadme)
copyTypes.dependsOn(copyReadme)
createNpmPackage.dependsOn(copyTypes)

task createPackage {
println "CCache version: " + getCCacheVersion()
Expand Down
129 changes: 92 additions & 37 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,85 @@ workers for the change to reach them.** A worker started after the
`configureLoader` call resolves through the new vocabulary; a live worker
never observes a later reconfiguration.

### `ns:url`

The runtime's own `URL` and `URLSearchParams`, reachable by specifier, plus
the two path/URL converters. Its export set is exactly `node:url`'s, so that
shim re-exports every member unchanged. **Experimental.**

| export | description |
|---|---|
| `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. |
| `URLSearchParams` | Likewise the runtime's `URLSearchParams` constructor. |
| `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. |
| `pathToFileURL(path)` | Converts an absolute path to a `file:` URL, returning this module's `URL`. |

`URLPattern` stays a global only: Node's `node:url` has no counterpart, and
nothing in the module needs it.

The module exists so that typed code can name the URL classes without
depending on what `globalThis.URL` resolves to in the program's type
environment. The iOS runtime's `types/ns-url.d.ts` declares it, along with
the global `URL` and `URLSearchParams`; Android adds nothing to that surface,
so this package ships no declaration of its own for it.

The converters parse through the module's own `URL`, so `file://localhost/x` is
accepted (the URL spec folds a `localhost` authority to none) while any other
host throws, and the query and fragment are never part of the path.
`fileURLToPath` rejects a non-`file:` scheme and rejects `%2F` in the path
rather than decoding a separator into it. `pathToFileURL` returns a real `URL`
and requires an **absolute** path: Node resolves a relative one against the
process working directory, and there is no such thing here.

```js
const { fileURLToPath, pathToFileURL } = require("ns:url");

fileURLToPath("file:///app/src/main.js"); // "/app/src/main.js"
fileURLToPath("file://localhost/app/a.js"); // "/app/a.js"
fileURLToPath("file:///app/a.js?v=2#frag"); // "/app/a.js"

pathToFileURL("/app/my file.js").href; // "file:///app/my%20file.js"
```

Its `TypeError` messages are Node's:

| condition | message |
|---|---|
| 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.` |
| non-`file:` scheme | `The URL must be of scheme file` |
| a host other than `localhost` or empty | `File URL host must be "localhost" or empty` |
| `%2F` in the path | `File URL path must not include encoded / characters` |
| `pathToFileURL` given a non-string | `The "path" argument must be of type string.` |
| `pathToFileURL` given a relative path | `The "path" argument must be an absolute path.` |

### `ns:worker_threads`

The runtime's own `Worker`, reachable by specifier; the `node:worker_threads`
shim adapts it. **Experimental.**

| export | description |
|---|---|
| `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). |

```js
import { Worker } from "ns:worker_threads";

const worker = new Worker("./heavy.js", {
android: { priority: "lessFavorable" },
resourceLimits: { maxOldGenerationSizeMb: 64 },
});
```

The module exists so that typed code can name the runtime's constructor and
its options without depending on what `globalThis.Worker` resolves to in the
program's type environment. The iOS runtime's `types/ns-worker-threads.d.ts`
declares the module, its cross-platform options and the global `Worker`; this
package's `types/ns-worker-threads-android.d.ts` adds `android` (and the
deprecated `androidPriority`) to both the module's and the global
`WorkerOptions`, merging with those declarations rather than restating them.
Cross-platform code can pass `ios` and `android` together: each runtime reads
its own object and ignores the other's.

### `node:` compatibility shims

The same registry serves the `node:` scheme with **compatibility shims** so
Expand Down Expand Up @@ -659,38 +738,9 @@ unmodified where a shim exists:
| module | exports | notes |
|---|---|---|
| `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` | `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`. |
| `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: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. |

`node:url`'s parsing goes through the URL intrinsic, so `file://localhost/x` is
accepted (the URL spec folds a `localhost` authority to none) while any other
host throws, and the query and fragment are never part of the path.
`fileURLToPath` rejects a non-`file:` scheme and rejects `%2F` in the path
rather than decoding a separator into it. `pathToFileURL` returns a real `URL`
and requires an **absolute** path: Node resolves a relative one against the
process working directory, and there is no such thing here.

```js
const { fileURLToPath, pathToFileURL } = require("node:url");

fileURLToPath("file:///app/src/main.js"); // "/app/src/main.js"
fileURLToPath("file://localhost/app/a.js"); // "/app/a.js"
fileURLToPath("file:///app/a.js?v=2#frag"); // "/app/a.js"

pathToFileURL("/app/my file.js").href; // "file:///app/my%20file.js"
```

Its `TypeError` messages are Node's:

| condition | message |
|---|---|
| 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.` |
| non-`file:` scheme | `The URL must be of scheme file` |
| a host other than `localhost` or empty | `File URL host must be "localhost" or empty` |
| `%2F` in the path | `File URL path must not include encoded / characters` |
| `pathToFileURL` given a non-string | `The "path" argument must be of type string.` |
| `pathToFileURL` given a relative path | `The "path" argument must be an absolute path.` |
| `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

Expand Down Expand Up @@ -976,9 +1026,9 @@ resolvers read the same table differently:
- The **`ns:`/`node:` resolver** — the app-facing one, behind `require()`,
`import` and `import()` — serves only rows *not* marked internal-only. An
internal-only specifier fails exactly as a name absent from the table does.
Nine rows are public today: `ns:interop`, `ns:interop/android`, `ns:module`,
`ns:runtime`, `ns:util`, `node:module`, `node:url`, `node:util`,
`node:worker_threads`.
Eleven rows are public today: `ns:interop`, `ns:interop/android`,
`ns:module`, `ns:runtime`, `ns:url`, `ns:util`, `ns:worker_threads`,
`node:module`, `node:url`, `node:util`, `node:worker_threads`.
- The **internal require** builtins receive (previous section) is the only
thing that can name an internal-only row. Seven rows are marked that way:
`internal/broadcast-channel`, `internal/dom-exception`, `internal/events`,
Expand Down Expand Up @@ -1103,6 +1153,11 @@ implicit port's message queue disabled until the worker entry finishes
evaluating — including after a pending top-level await settles. Messages sent
before that stay buffered.

Unlike iOS, Android ships no `.d.ts` declarations for the `ns:` modules; the
`.d.ts` files in this repo describe the Android platform classes, not this
surface.
Android's `.d.ts` declarations for the `ns:` modules live in `types/` and
cover only what this runtime adds to them (today, `ns:worker_threads`'s
`android` option). The iOS runtime's `types/` is the source of truth for the
shared surface: two `declare module` blocks that both declare the same value
conflict, so these files declare only new names and merge into the iOS ones.
A program that includes only the Android types therefore sees the additions
but not the shared exports. The other `.d.ts` files in this repo describe the
Android platform classes, not this surface.
46 changes: 44 additions & 2 deletions docs/worker-threads.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ means deliberately unsupported.
| `markAsUncloneable(obj)` | real | Brands `obj` so serializing it at all is a `DataCloneError`, in `structuredClone` and every `postMessage` alike. |
| `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. |
| `getEnvironmentData(key)` | real, deviates | Deserializes a fresh copy per read, on any isolate. |
| `resourceLimits` | shim | Always `{}`; the runtime imposes no per-worker limits and reports none. |
| `resourceLimits` | shim | Always `{}`. The export reports nothing; the `resourceLimits` constructor option is real — see [Worker options](#worker-options). |
| `SHARE_ENV` | shim | Exported so the spelling resolves, but inert — see below. |
| `threadName` | shim | Always `undefined`. |
| `workerData` | shim | Always `null` — see below. |
| `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. |
| `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. |
| `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. |
| `postMessageToThread` | throws | `Error: postMessageToThread is not supported in this runtime`. |
| `moveMessagePortToContext` | throws | `Error: moveMessagePortToContext is not supported in this runtime`. |
| `locks` | absent | Web Locks are not implemented; the property does not exist. |
Expand Down Expand Up @@ -271,6 +271,48 @@ it has no way out: a `message` event hands it over in `event.ports`, while
close such a port as soon as it arrives, so its sibling learns the channel is
gone instead of queueing into a port nothing can ever read.

## Worker options

The runtime's `Worker` constructor takes two options of its own, and the
`node:worker_threads` shim passes both through unchanged. Unknown keys inside
either object are ignored, so a later runtime can add more without breaking an
older one, and cross-platform code can pass the iOS runtime's `ios` object
alongside `android`. `null` for either object means the same as leaving it
out. The constructor is also exported by the
[`ns:worker_threads`](ns-builtin-modules.md#nsworker_threads) builtin, whose
type declarations describe both options and merge them into the global
`WorkerOptions`.

### `android.priority`

The worker thread's `android.os.Process` priority: one of the
`THREAD_PRIORITY_*` constants by camelCase name (`lowest`, `background`,
`lessFavorable`, `default`, `moreFavorable`, `foreground`, `display`,
`urgentDisplay`, `video`, `audio`, `urgentAudio`) or a nice value. A number
outside -20..19 is clamped into it; `NaN`, any other type and an unknown name
throw a `TypeError`, as does an `android` that is not an object. Omitted, the
thread runs at `background` (nice 10). Lowering a nice value below 0 may need
a privilege the app does not hold.

The top-level `androidPriority` is the deprecated spelling: it takes the same
values (a `NaN` there means `default`), logs a deprecation warning once per
process, and loses to `android.priority` when both are given.

### `resourceLimits`

Node's shape, in megabytes:

| key | effect |
|---|---|
| `maxOldGenerationSizeMb` | Caps the worker isolate's old generation. |
| `maxYoungGenerationSizeMb` | Caps the worker isolate's young generation. |
| `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`. |

A value that is not a number throws a `TypeError`; a non-finite one, one worth
less than a byte or one too large to hold in bytes throws a `RangeError`.
Node's `stackSizeMb` and `codeRangeSizeMb` are ignored, like any other key the
runtime does not know.

## Worker messages

The runtime's own `Worker` and the worker global scope are `EventTarget`s that
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"type": "git",
"url": "https://github.com/NativeScript/android.git"
},
"types": "./types/index.d.ts",
"files": [
"**/*"
],
Expand Down
2 changes: 2 additions & 0 deletions test-app/app/src/main/assets/app/mainpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ require('./tests/testNsUtil');
require('./tests/testNsRuntime');
require('./tests/testNsInterop');
require('./tests/testNsModule');
require('./tests/testNsUrl');
require('./tests/testNsWorkerThreads');
// Remote-module security gate (debug builds allow remote modules outright)
require('./tests/testRemoteModuleSecurity');
// The ES module loader: require(esm) interop and the createRequire factories
Expand Down
10 changes: 10 additions & 0 deletions test-app/app/src/main/assets/app/tests/nsUrlIdentityWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Reassigns the global before the module is first required in this realm, so
// a module that merely read `globalThis.URL` would report the impostor.
var original = globalThis.URL;
globalThis.URL = function Impostor() {};
var nsUrl = require("ns:url");
postMessage({
isOriginal: nsUrl.URL === original,
isImpostor: nsUrl.URL === globalThis.URL,
frozen: Object.isFrozen(nsUrl),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Reassigns the global before the module is first required in this realm, so
// a module that merely read `globalThis.Worker` would report the impostor.
var original = globalThis.Worker;
globalThis.Worker = function Impostor() {};
var nsWorkerThreads = require("ns:worker_threads");
postMessage({
isOriginal: nsWorkerThreads.Worker === original,
isImpostor: nsWorkerThreads.Worker === globalThis.Worker,
frozen: Object.isFrozen(nsWorkerThreads),
});
10 changes: 6 additions & 4 deletions test-app/app/src/main/assets/app/tests/testNodeUrlModule.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ describe("node:url", function () {
var required = require("node:url");

expect(Object.isFrozen(required)).toBe(true);
expect(Object.keys(required).sort()).toEqual(["fileURLToPath", "pathToFileURL"]);
// The shim converts between paths and file URLs; it is not a place to
// reach the URL intrinsic from.
expect(required.URL).toBeUndefined();
expect(Object.keys(required).sort()).toEqual([
"URL",
"URLSearchParams",
"fileURLToPath",
"pathToFileURL",
]);
expect(require("node:url")).toBe(required);

Promise.all([import("node:url"), import("node:url")]).then(function (results) {
Expand Down
Loading