Repository navigation
feat(runtime): ns:worker_threads builtin module with typed iOS worker options - #494
Conversation
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 31 minutes. View limit detailsLimit details: You’ve used all 2 included reviews currently available. Review configuration: ⚙️ Run configuration
📒 Files selected for processing (13)
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (13)
Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe runtime adds the ChangesWorker threads builtin
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Feature Sequence Diagram(s)sequenceDiagram
participant WorkerInit
participant NsWorkerThreadsBinding
participant NsWorkerThreadsModule
participant NodeWorkerThreadsShim
WorkerInit->>NsWorkerThreadsBinding: store and retrieve context Worker constructor
NsWorkerThreadsBinding->>NsWorkerThreadsModule: provide binding.Worker
NsWorkerThreadsModule->>NodeWorkerThreadsShim: export Worker for shim import
Suggested reviewers: Merge Risk: ⚪ Minimal · up to This PR adds the experimental ns:worker_threads module and typed worker options. No concrete defect was found in the supplied context, so it is low risk to merge after the usual iOS build and test run. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 9 files. (4 skipped: 4 unsupported.) ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. A rabbit finds a Worker bright, Comment |
31753d7 to
a858caf
Compare
… options
Adds `ns:worker_threads`, exporting the runtime's own Worker constructor, so
typed code can name the constructor and its iOS options (`ios.priority`,
Node's `resourceLimits`) by specifier instead of through whatever
`globalThis.Worker` resolves to in the program's type environment. The name
pairs with the `node:worker_threads` shim the way `ns:util`/`node:util` and
`ns:module`/`node:module` do, and the shim now takes the constructor from the
module. The binding takes it from the template Worker::Init installed, which
V8 instantiates once per context, so the module hands out the very function
the global was created with even after an app reassigns the global.
types/ns-worker-threads.d.ts declares the module and, at script level,
merges the two options into the global WorkerOptions and declares the global
Worker the way @types/node declares its own globals: a program with a DOM lib
keeps the lib's declaration, so `new Worker(path, { ios })` type-checks
either way without a conflicting redeclaration. Verified with tsc against a
DOM and a non-DOM program.
Experimental, iOS-only until the Android runtime ships the module.
a858caf to
a38ff54
Compare
### 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 -->
Stacked on #493 (base branch
fix/worker-terminate-during-entry); only the last commit is this PR.What
A new
ns:worker_threadsbuiltin exporting the runtime's ownWorkerconstructor, plus type declarations for the iOS constructor options that #470 (ios.priority) and #471 (resourceLimits) added but never typed. The name pairs with thenode:worker_threadsshim the wayns:util/node:utilandns:module/node:moduledo, and the shim now takes its constructor from the module instead of readingglobalThis.Worker.Why a module
The options live on the global
Worker, whose type comes from whichever lib a program includes. A specifier gives typed code one fixed place to name the constructor and its options. The binding takes the constructor from the templateWorker::Initinstalled, which V8 instantiates once per context, so the module hands out the very function the global was created with even after an app reassignsglobalThis.Worker.The export set is
Workeronly for now. The channel half (MessageChannel,MessagePort,BroadcastChannel) can join later the wayns:utilgrewTextEncoder; the shim already hands out the global objects for those.Types
types/ns-worker-threads.d.tsdeclares the module (Worker,WorkerOptions,WorkerIosOptions,WorkerResourceLimits,WorkerPriority, and the event shapes a standalone declaration needs). At script level it does what@types/nodedoes for its own globals:WorkerOptions, sonew Worker(path, { ios })on the DOM constructor type-checks;declare var Workeruses thetypeof globalThis extends { onmessage: any; Worker: infer T }probe, so a program with a DOM lib keeps the lib's own declaration (the twodeclare vars agree) and a program without one gets the module's constructor as the global.Verified with
tsc --strictagainst a DOM program and a non-DOM program: the DOM one is clean, including@ts-expect-errorchecks on a bad priority name and a string megabyte count; the non-DOM one reports only the pre-existingURLreferences inns-module.d.ts.Docs and tests
docs/ns-builtin-modules.mdgains the module's reference section (marked experimental, iOS-only until Android ships it), the public-row count, and a correctednode:worker_threadsrow;docs/worker-threads.mdpoints at it from "Worker options".NsWorkerThreadsTests.jspins the frozen export set, identity with the global, the per-realm singleton, distinctness from the shim's module object, construction with both options, and, through a worker fixture that reassignsglobalThis.Workerbefore its firstrequire("ns:worker_threads"), that the module still exports the original constructor.Summary by CodeRabbit
New Features
ns:worker_threadsmodule, exposing the runtime’sWorkerconstructor with support for iOS priority and resource limit options.Documentation
node:worker_threadsbridge.