Skip to content

feat(runtime): warn in debug when an ES module passes a relative specifier to the global require - #610

Draft
edusperoni wants to merge 18 commits into
mainfrom
feat/global-require-esm-diagnostic
Draft

edusperoni wants to merge 18 commits into
mainfrom
feat/global-require-esm-diagnostic

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #609 (it uses the ReportedModuleUrl helper that PR adds); the base branch is #609's and this retargets to main once that merges.

What

  • Docs: the global require is available in ES modules for compatibility and resolves a relative specifier (./x, ../x) against the app root, whichever module calls it. An ES module that needs module-relative resolution uses createRequire(import.meta.url), or, when it was loaded over http(s), createRequire with an app file path.

  • Debug-build warning: when the global require is called from an ES module with a relative specifier, the runtime logs once per module (per isolate):

    NativeScript: require("./x.js") in ES module file:///app/features/a/index.mjs resolves against the app root, not the module's folder. Use createRequire(import.meta.url) from "ns:module" (from a module loaded over http(s): createRequire with an app file path).
    

require itself does not change in any build: same resolution, same errors, same return values.

Why

A CommonJS module gets a require bound to its own folder through the module wrapper. An ES module cannot be wrapped, so require(...) inside one is the global function, which is bound to the app root. require("./sibling") from an ES module in a subfolder therefore loads <app>/sibling, or fails, and nothing says why. The module-relative require for ES modules is createRequire(import.meta.url), as in Node; the global one stays because the unwrapped main bundle, classic scripts and existing ES-module code use it.

How

  • In debug builds the global require gets a native half of its own (DebugGlobalRequireCallback), which checks the call and then runs the unchanged RequireCallback. The bound directory cannot identify the global require (a CommonJS module in the app root is bound to the same directory), and release builds never create the debug variant, so the global require there is exactly what it was.
  • The check runs only for a string specifier that is ., .., ./… (other than exactly ./, which every require resolves to the app's main entry) or ../…. It takes the first stack frame outside the require factory script and looks its script id up among the registered ES modules (LookupModuleKeyForScriptId), so classic scripts, new Function/eval code and CommonJS modules never match, and file and http(s) ES modules both do.
  • Warned modules are remembered per isolate, by registry key, so a module recompiled during development does not warn again and each worker has its own set.
  • The warning code runs no JavaScript and cannot throw.

How it was verified

  • New specs pin the behaviour that does not change: from an ES module in a subfolder, the global require("./sibling") still resolves against the app root (twice, and with ../), ~/… and ns: specifiers load, createRequire(import.meta.url)("./sibling") loads the sibling, and classic-script and CommonJS callers of the global require resolve against the app root; the same from a module served over HTTP.
  • The suite cannot observe log output and no test-only hook was added. The warning was checked by capturing the simulator log of each full run: exactly two lines per run, one for the file ES module fixture and one for the HTTP one, and none for the repeat call, another relative specifier from the same module, non-relative specifiers, the CommonJS caller, the createRequire require or the classic-script caller. No existing spec triggers the warning.
  • Full suite on an iOS simulator on top of refactor(runtime): one URL parse for every http(s) module entry point #609: 2344 test cases, 0 failures. Under AddressSanitizer it last ran before refactor(runtime): one URL parse for every http(s) module entry point #609's final two commits were merged in (2338 test cases, 0 failures at that point). Debug and Release builds with -Werror.

Not covered by a spec or a captured line: ./.. as whole specifiers warning, exactly ./ and .x not warning; a release build was compiled but the suite was not run against it.

Records what the loader does today for the URL shapes dev servers emit, both as registry keys (with and without a tooling-shaped canonicalization vocabulary) and as loaded modules reached from a file module directly and through an import-map entry: import.meta.url, getLoadedModuleUrls(), the request target the server saw, and eviction by invalidateModules.
IsHttpRegistryKey, ParseModuleUrl and the written-authority rule move out of ModuleInternalCallbacks.mm into ModuleUrl, which also gains NormalizeHttpModuleUrl: the spelling the loader gives an absolute http(s) module URL, falling back to the input itself for an HTTP-prefixed string the URL parser rejects.

ParseModuleUrl now rebuilds the written-authority href by replacing only the authority inside the parser's href. Rebuilding from the pathname, search and hash getters lost a bare trailing '?' or '#', so the re-parse check failed and the parser's lowercased host replaced the written one.
…rser

Every route by which an absolute http(s) URL enters the loader now classifies and spells it with NormalizeHttpModuleUrl: the registry key (CanonicalizeHttpUrlKey and CanonicalizeRegistryKey, hence invalidateModules, import.meta.url and getLoadedModuleUrls), a specifier or import-map target from any importer, a dynamic import()'s query handling and HTTP branch, the graph-walk root, the synchronous fallback fetch, LoadESModule/RunModule roots and the require() URL guard. The fetched URL and the registry key derive from the same string.

From a file module, HTTP://h/x and http:/h/x are now http URLs as they already were from an HTTP module, dot segments resolve before the fetch, and characters the parser percent-encodes are encoded in the key. The authority keeps its written spelling. An HTTP-prefixed string the parser rejects stays an HTTP URL in its raw spelling.
Nothing in the runtime feeds the loader a file://http(s):// wrapper, a collapsed http:/ scheme or a URL embedded in a joined path any more, so the unwraps in CanonicalizeHttpUrlKey, CanonicalizeRegistryKey and ModuleInternal, HttpUrlEmbeddedInPath and RepairCollapsedUrlScheme go. A collapsed http:/host still keys as http://host because the URL parser reads it that way; a wrapped file://http://… is a file: URL that names no file, so import() of it rejects without fetching.

A dynamic import() from an HTTP module that the resolver left unresolved now rejects instead of re-resolving in the tail, which path-joined an http referrer the URL parser rejects (an IPv6 zone id) into a collapsed URL. An http(s) worker script is labelled with its own URL in the inspector. The unused adjustedRegistryKey is gone.
…y gate

The allowlist compares fetched URLs, which the loader now spells with the URL parser (dot segments resolved, characters such as non-ASCII percent-encoded). Each security.remoteModuleAllowlist entry is spelled the same way once, when the allowlist is loaded, with the written authority kept; an entry that is not an http(s) URL stays verbatim. The prefix-and-boundary rule is unchanged.

The rule is factored into RemoteUrlMatchesAllowlist, which IsRemoteUrlAllowed applies, and debug builds expose it on ns:module as remoteUrlMatchesAllowlist(url, entries) so it can be tested; release builds omit the member.
…eys they match

A scope key matches the importing module's registry key by plain prefix, and http(s) registry keys are spelled by the URL parser, so a scope written with dot segments or a non-ASCII segment matched nothing. An http(s) scope key is now spelled the same way when the map is installed, ending in '/' exactly when it was written so; other scope keys (app paths) and imports keys stay as written.
NormalizeHttpModuleUrl rejects a string that cannot be an http(s) URL from its first character instead of attempting a parse, so file paths pay nothing for it. ParseModuleUrl returns the parser's href unchanged when the written authority already matches it, skipping the rebuild and its re-parse.

CanonicalizeHttpUrlKey splits into the spelling step and CanonicalizeNormalizedHttpUrlKey, which applies the vocabulary to an already spelled URL. CanonicalizeRegistryKey, the graph walk (enqueue, fetch completion, root), the dynamic-import HTTP branch, LoadESModule and LoadHttpModuleForUrl, whose callers pass resolved URLs, spell a URL at most once.
Script origins of classic scripts, file ES modules and JSON modules, import.meta.url and the worker inspector URL each built their own file:// URL from a path. ReportedModuleUrl in ModuleUrl now does it for all of them: an http(s) URL in the loader's spelling, any other string that carries a scheme unchanged, and otherwise file:// plus the path with the base directory removed (file:///app/ when empty). The outputs are unchanged except the worker inspector URL, which for an http(s) script is now the normalized URL and for any other scheme-carrying script is the script string itself rather than a file:// prefix glued onto it.

The docs no longer describe the file://http… string, which is not a form the loader accepts.
ReportedModuleUrl tested for a URL scheme before asking whether the string is an http(s) URL, so one the loader accepts with leading whitespace or C0 controls failed the scheme test and was prefixed with file://. It now spells http(s) URLs first; other inputs are reported as before.
…' into feat/global-require-esm-diagnostic

# Conflicts:
#	NativeScript/runtime/Runtime.mm
@coderabbitai

coderabbitai Bot commented Nov 26, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@edusperoni
edusperoni added this pull request to stack #611 November 27, 2026 00:19
…read it exactly

A security.remoteModuleAllowlist array with at least one item is now in force: every URL is allowed only when the key is absent, not an array, or an empty array. An item that is not a string, is empty, or has no exact UTF-8 form matches nothing instead of being dropped, so a list of unusable items no longer becomes allow-all.

Items are converted to UTF-8 by length through the new tns::ToExactUtf8, so an embedded U+0000 no longer truncates an entry to a broader prefix, and a string with a lone surrogate is reported as unconvertible instead of being read through a NULL -UTF8String.

RemoteModuleAllowlistFromConfig and RemoteUrlAllowedByAllowlist hold the policy; the release gate and the debug remoteUrlMatchesAllowlist member both use them, so the member answers what the gate would for a list of entries, including true for [].
The import-map parser read keys, targets, scope keys and section names through -UTF8String, so an embedded U+0000 cut them short, and a cut-short target or scope key is broader than written. They now go through tns::ToExactUtf8 and are kept whole: a specifier key or scope key containing U+0000 matches only those exact bytes. A target containing U+0000 is rejected with a TypeError when the map is validated, since resolving it as a path or fetching it as a URL would end it there.
Base automatically changed from refactor/loader-url-entry-points to main December 1, 2026 21:33

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant