← Back to Pull requests

Drop TypeScript's __esModule marker from the bootstrap scripts #8833

Merged
nathanwhit merged 2 files (46 lines) on Nov 25, 2026 18:43 UTC
View on GitHub
nathanwhit nathanwhit commented on Nov 23, 2026 16:52 UTC
Author

Fixes a bug where lazily loaded per-isolate bootstrap scripts can throw on first use if user code has polluted Object.prototype or replaced Object.defineProperty, by stripping TypeScript's emitted __esModule marker in wd_ts_script_bundle.

## Problem

Because src/per_isolate compiles with "module": "commonjs" (with "moduleDetection": "force" and import type/export type), TypeScript prepends this line to every emitted script:

   Object.defineProperty(exports, "__esModule", { value: true });
   

For scripts loaded eagerly during isolate creation, this runs before user code. For scripts loaded lazily on first use, it runs after user code, where it can fail in two ways:

- It calls the global Object.defineProperty(), which user code may have replaced (causing a throw or intercepting exports).
- Its descriptor inherits from Object.prototype, so defining get or set on Object.prototype makes the descriptor invalid.

MessageChannel and MessagePort already load on first use (#8458)—through either the globals (expose_global_message_channel, default since 2025-08-15) or cloudflare-internal:messagechannel (node:worker_threads)—so this throws today:

   Object.prototype.get = undefined;
   new MessageChannel();
   // TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object>
   

## Change

Replace the copy_file step in wd_ts_script_bundle (build/wd_ts_script_bundle.bzl) with a genrule that drops the Object.defineProperty(exports, "__esModule", { value: true }); line before V8 compile caches and the Cap'n Proto bundle are
generated.

- Why in the build rule: TypeScript has no tsconfig option to suppress __esModule emission for CommonJS modules. Stripping it in wd_ts_script_bundle's existing copy step covers both src/per_isolate and embedder bundles, and ensures compile
caches are built from the stripped source.
- Why it is safe: The bootstrap require() (src/workerd/api/per-isolate-bootstrap.c++) never reads __esModule, and the scripts themselves already use primordials and null-prototype descriptors.

#8529 also depends on this for lazily loading TextEncoder and carries this commit until this PR lands.

## Compatibility

No change to the Workers API surface. First access to lazily loaded bootstrap globals (MessageChannel, MessagePort) no longer throws when a Worker has replaced Object.defineProperty or added get/set to Object.prototype.

## Testing

Added a test case to src/workerd/api/messagechannel-bootstrap-test.c++ that defines all property descriptor fields (get, set, value, writable, enumerable, configurable) on Object.prototype, replaces Object.defineProperty with a throwing
function, and verifies MessagePort still loads. Fails without this change.

Diff: 46 lines (+45 / -1) across 2 files Reviewer: jasnell Review duration: 2990m
All Vouch review confidence checks passed
Residual risk 0.03 = Change Risk (0.27) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.27 · 46 lines diff across 2 files
0.27
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 1 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.230
Real PR Conversation Timeline
6 items
clanky-the-clanker[bot] clanky-the-clanker[bot] commented on code on Nov 23, 2026 17:14 UTC
Code Review
build/wd_ts_script_bundle.bzl:1
@@ -195,13 +195,23 @@ def wd_ts_script_bundle(
     #    capnp compiler cannot embed files outside the rule's directory subtree,
     #    so we copy JS outputs into the current package with flattened names.
     #    e.g., main.js -> main, utils/helpers.js -> utils_helpers
+    #
+    #    The copy drops the `__esModule` marker TypeScript emits at the top of a CommonJS
+    #    module. The bootstrap's require() has no use for it, and a script that loads on
+    #    first use runs after user code, which can have replaced Object.defineProperty() or
+    #    given Object.prototype a `get`, which makes the marker's descriptor invalid.
     js_files = [_to_js(s) for s in non_dts]
 
     scripts_dict = {}
     for js in js_files:
         sname = _script_name(js)
         flat = _flat_name(sname)
-        copy_file(name = flat + "@copy", src = js, out = flat)
+        native.genrule(
+            name = flat + "@copy",
+            srcs = [js],
+            outs = [flat],
+            cmd = "sed '/^Object\\.defineProperty(exports, \"__esModule\", { value: true });/d' $< > $@",

<!-- durable-reviewer:finding -->
💬 SUGGESTION · Code Quality

The sed filter fails silently if TypeScript's emitted __esModule marker stops matching the exact pattern

This sed expression deletes only one exact line. If a TypeScript upgrade or a tsconfig change emits the marker differently (other spacing, or exports.__esModule = true), the genrule still succeeds and the marker comes back without warning. The only coverage is the MessagePort test, and other bundles built with this rule have none. You could add a check after the sed, e.g. && ! grep -q '__esModule' $@, so a pattern mismatch fails the build.

clanky-the-clanker[bot] clanky-the-clanker[bot] commented on Nov 23, 2026 17:14 UTC
Reviewer

<!-- durable-reviewer:review run=49221446-2db2-40f6-b830-fcc1e33e2b6a -->

Superseded by the review of 5e0d661f.

<details>
<summary>This review, of <code>6e220527</code></summary>

💬 Approved with comments — Correct, well-tested fix; one optional suggestion to make the sed strip fail loudly if TypeScript's emitted marker changes.

Findings: 1 suggestion (1 is an inline comment on the diff)

<sub>The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.</sub>

---

📋 Code Quality: 💬 1 suggestion

Sound change with good test coverage; one optional hardening suggestion for the sed filter.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] The sed filter fails silently if TypeScript's emitted __esModule marker stops matching the exact pattern (build/wd_ts_script_bundle.bzl:213)
  • <details>
    <summary>View full review</summary>

    The genrule strips the exact marker line TypeScript emits, and the new test covers both failure modes (descriptor fields on Object.prototype, and a replaced Object.defineProperty()). It restores global state in finally. $< is valid because each genrule has a single source, and the escaping works out to \. in the shell.

    build/wd_ts_script_bundle.bzl:213: the sed expression matches one exact line. If a TypeScript upgrade or a tsconfig change alters the emitted text (spacing, or exports.__esModule = true), the genrule still succeeds and the marker comes back. The only thing that would catch it is the MessagePort test, and the other bundles that go through this rule have no such test. A post-sed check such as ! grep -q __esModule $@ would turn that into a build error.

    </details>

    ---

    <details>
    <summary>✅ All other checks passed</summary>

    📝 Documentation: ✅ LGTM

    The new comment in wd_ts_script_bundle.bzl describes the current behaviour and explains why the marker is dropped.

    </details>

    ---
    <sub>Reviewed commit: 6e220527</sub>

    </details>

    clanky-the-clanker[bot] clanky-the-clanker[bot] commented on Nov 23, 2026 18:23 UTC
    Reviewer

    <!-- durable-reviewer:review run=2e9e351c-ef92-4f68-9fd3-b6c1fa159de1 -->

    Superseded by the review of 22f2a4cb.

    <details>
    <summary>This review, of <code>5e0d661f</code></summary>

    ✅ Approved — The fix is correct and tested, and the build check added since the last review fixes the one earlier suggestion. No open findings remain.

    <sub>The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.</sub>

    ---

    <details>
    <summary>✅ All checks passed</summary>

    📋 Code Quality: ✅ LGTM

    The earlier suggestion about the sed filter failing silently is fixed. build/wd_ts_script_bundle.bzl:214-216 now runs grep -n '__esModule' $@ after the strip and exits 1 on a match, so a change in TypeScript's emitted marker text stops the build. copy_file is still used elsewhere in the file, so its load is still needed. The new test in src/workerd/api/messagechannel-bootstrap-test.c++ covers both failure modes and restores the global state in finally.

    ---

    📝 Documentation: ✅ LGTM

    The comment in wd_ts_script_bundle.bzl describes the current behaviour and explains why the marker is dropped.

    </details>

    ---
    <sub>Reviewed commit: 5e0d661f</sub>

    </details>

    clanky-the-clanker[bot] clanky-the-clanker[bot] commented on Nov 23, 2026 19:37 UTC
    Reviewer

    <!-- durable-reviewer:review run=88786df8-b758-496f-9330-101c14f82e1c -->

    ✅ Approved — The fix is correct and tested, and the build check added since the last review fixes the one earlier suggestion. No open findings remain.

    <sub>The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.</sub>

    ---

    <details>
    <summary>✅ All checks passed</summary>

    📋 Code Quality: ✅ LGTM

    The earlier suggestion about the sed filter failing silently is fixed. build/wd_ts_script_bundle.bzl:214-216 now runs grep -n '__esModule' $@ after the strip and exits 1 on a match, so a change in TypeScript's emitted marker text stops the build. copy_file is still used elsewhere in the file, so its load is still needed. The new test in src/workerd/api/messagechannel-bootstrap-test.c++ covers both failure modes and restores the global state in finally.

    ---

    📝 Documentation: ✅ LGTM

    The comment in wd_ts_script_bundle.bzl describes the current behaviour and explains why the marker is dropped.

    </details>

    ---
    <sub>Reviewed commit: 22f2a4cb — same changes as 5e0d661f, so this is that commit's review (no new review was run; line numbers are as of 5e0d661f)</sub>

    jasnell jasnell approved these changes on Nov 25, 2026 05:26 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    nathanwhit nathanwhit
    Labels
    risk: low confidence: 89.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 27.5% (LOW) · Higher = larger blast radius
    27.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.5% · Lower = rushed or shallow review
    89.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.9% · Safe to merge
    2.9%