CodeSampleX

Beispiel

jsdom 26.1.0: Intercept and customize subresource loading in JSDOM using ResourceLoader

Verifiziertes Beispiel für npm jsdom 26.1.0: Intercept and customize subresource loading in JSDOM using ResourceLoader. Der Vertrag lief auf node 22 · linux…

sha256:729cd83d1c1f9d920bc16f81b26620669e5f6eb3dd0f9c878ce052f183c7f713

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

Fall

HOW
Ziel
Intercept and customize subresource loading in JSDOM using ResourceLoader
Pakete
Symbole
  • JSDOM
  • ResourceLoader
Umgebung
node 22.23.2
Erstellt
2026-08-28T06:56:19Z

Contract

  1. ResourceLoader constructor accepts configuration options including userAgent, proxy, and strictSSL.
  2. Instantiating JSDOM without configuring resources suppresses all external subresource fetching for scripts and stylesheets.
  3. Attaching a custom ResourceLoader subclass intercepts subresource fetch requests and passes the requesting element reference in fetch options.
  4. Returning a Buffer promise from ResourceLoader fetch resolves synthetic external script content and executes it within the JSDOM window context under runScripts dangerously.
  5. Returning a Buffer promise from ResourceLoader fetch parses external stylesheets into document.styleSheets rules.
  6. Returning null from ResourceLoader fetch silently blocks subresource fetching without throwing exceptions, emitting jsdomError, or firing element event handlers.
  7. Rejecting the promise returned from ResourceLoader fetch triggers element onerror handlers and emits a jsdomError event to VirtualConsole.

Dateien

  • NOTES.md
  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Quellartefakt herunterladen (tar.gz)

Quelltext

NOTES.md
# JSDOM Subresource Interception and Customization using ResourceLoader

## Search Findings
An initial search for `pkg:npm/jsdom@26.1.0` behaviors identified existing public samples for script execution scoping (`sha256:25b9a38825174ba5a14d0ac2113dc8725a5d805f5e75e487a2d3e0f235436362`) and web storage URL configuration (`sha256:7cea419813dc1b9e63d00f9950fbc33987bd649531dcdd1f00dab447feb94f8f`). A query targeting `ResourceLoader` and subresource interception returned `NO_SAFE_MATCH`.

## Pinned Version
- Package: `jsdom`
- Version: `26.1.0`

## Observed Behaviour and Contract Details

### 1. Default Subresource Handling
Instantiating `JSDOM` with default options suppresses all external subresource fetching (such as `<script src="...">` and `<link rel="stylesheet">`). The document does not initiate network requests or load external scripts/stylesheets.

### 2. ResourceLoader Subclassing and Fetch Interception
Subclassing `ResourceLoader` and passing an instance via the `resources` option in the `JSDOM` constructor directs all subresource fetches through the loader's `.fetch(url, options)` method:
- The `options` parameter contains `element`, providing a direct reference to the initiating DOM element (e.g. `HTMLScriptElement`, `HTMLLinkElement`).
- Returning a `Promise<Buffer>` resolves external subresources with synthetic content. When `runScripts: "dangerously"` is enabled, resolved script buffers execute within the `window` context and trigger the element's `onload` handler.
- Resolved stylesheet buffers are parsed directly into `document.styleSheets`.

### 3. Blocking Subresources
Returning `null` from `.fetch(url, options)` silently blocks the subresource request. JSDOM cancels the fetch without throwing exceptions, emitting `jsdomError` events to `VirtualConsole`, or triggering `onload`/`onerror` handlers on the element.

### 4. Error Handling and VirtualConsole Routing
When `.fetch(url, options)` returns a rejected Promise (e.g. simulating a network failure), JSDOM triggers the element's `onerror` event listener and emits a `jsdomError` event containing the failure details to the attached `VirtualConsole`.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Intercept and customize subresource loading in JSDOM using ResourceLoader
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jsdom@26.1.0
Demonstrate these symbols/APIs:
  - JSDOM
  - ResourceLoader
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:0798fb7206acbc31d1a8efc143e598760b31c7e404cd375dc67b076044c69ce4","constraints":{"executionContext":"node"},"contract":["ResourceLoader constructor accepts configuration options including userAgent, proxy, and strictSSL.","Instantiating JSDOM without configuring resources suppresses all external subresource fetching for scripts and stylesheets.","Attaching a custom ResourceLoader subclass intercepts subresource fetch requests and passes the requesting element reference in fetch options.","Returning a Buffer promise from ResourceLoader fetch resolves synthetic external script content and executes it within the JSDOM window context under runScripts dangerously.","Returning a Buffer promise from ResourceLoader fetch parses external stylesheets into document.styleSheets rules.","Returning null from ResourceLoader fetch silently blocks subresource fetching without throwing exceptions, emitting jsdomError, or firing element event handlers.","Rejecting the promise returned from ResourceLoader fetch triggers element onerror handlers and emits a jsdomError event to VirtualConsole."],"goal":"Intercept and customize subresource loading in JSDOM using ResourceLoader","kind":"HOW","packages":["pkg:npm/jsdom@26.1.0"],"schemaVersion":1,"symbols":["JSDOM","ResourceLoader"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jsdom@26.1.0"],"schemaVersion":1,"subject":"pkg:npm/jsdom@26.1.0","symbols":["JSDOM","ResourceLoader"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { JSDOM, ResourceLoader } from 'jsdom';

/**
 * Custom ResourceLoader implementation that logs requests and serves
 * mock responses or blocks subresource fetches based on route definitions.
 */
export class InterceptingResourceLoader extends ResourceLoader {
  /**
   * @param {object} [options={}] - ResourceLoader options (userAgent, strictSSL, proxy).
   * @param {Map<string, string|Buffer|Function|null>|Record<string, string|Buffer|Function|null>} [routes={}] - Route mapping.
   */
  constructor(options = {}, routes = {}) {
    super(options);
    this.routes = routes instanceof Map ? routes : new Map(Object.entries(routes));
    this.requests = [];
  }

  /**
   * Intercepts subresource fetch requests.
   * @param {string} url - Target URL.
   * @param {object} [options] - Fetch options including initiating DOM element.
   * @returns {Promise<Buffer>|null}
   */
  fetch(url, options) {
    const element = options?.element || null;
    const tagName = element ? element.tagName : null;
    this.requests.push({ url, tagName, element });

    if (this.routes.has(url)) {
      const handler = this.routes.get(url);
      if (typeof handler === 'function') {
        return handler(url, options);
      }
      if (handler === null) {
        // returning null aborts/blocks the request silently
        return null;
      }
      return Promise.resolve(Buffer.isBuffer(handler) ? handler : Buffer.from(handler));
    }

    return super.fetch(url, options);
  }
}

/**
 * Creates a JSDOM instance configured with an optional ResourceLoader.
 * @param {string} [html=''] - Initial HTML content.
 * @param {object} [options={}] - JSDOM options.
 * @param {ResourceLoader} [resourceLoader] - Custom ResourceLoader instance.
 * @returns {JSDOM}
 */
export function createCustomDOM(html = '', options = {}, resourceLoader = undefined) {
  const domOptions = { ...options };
  if (resourceLoader) {
    domOptions.resources = resourceLoader;
  }
  return new JSDOM(html, domOptions);
}
package-lock.json
{
  "name": "sample-jsdom-resourceloader",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jsdom-resourceloader",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "jsdom": "26.1.0"
      }
    },
    "node_modules/@asamuzakjp/css-color": {
      "version": "3.2.0",
      "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
      "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
      "license": "MIT",
      "dependencies": {
        "@csstools/css-calc": "^2.1.3",
        "@csstools/css-color-parser": "^3.0.9",
        "@csstools/css-parser-algorithms": "^3.0.4",
        "@csstools/css-tokenizer": "^3.0.3",
        "lru-cache": "^10.4.3"
      }
    },
    "node_modules/@csstools/color-helpers": {
      "version": "5.1.0",
      "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
      "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/csstools"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/csstools"
        }
      ],
      "license": "MIT-0",
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@csstools/css-calc": {
      "version": "2.1.4",
      "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
      "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/csstools"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/csstools"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=18"
      },
      "peerDependencies": {
        "@csstools/css-parser-algorithms": "^3.0.5",
        "@csstools/css-tokenizer": "^3.0.4"
      }
    },
    "node_modules/@csstools/css-color-parser": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz",
      "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/csstools"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/csstools"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "@csstools/color-helpers": "^5.1.0",
        "@csstools/css-calc": "^2.1.4"
      },
      "engines": {
        "node": ">=18"
      },
      "peerDependencies": {
        "@csstools/css-parser-algorithms": "^3.0.5",
        "@csstools/css-tokenizer": "^3.0.4"
      }
    },
    "node_modules/@csstools/css-parser-algorithms": {
      "version": "3.0.5",
      "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
      "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/csstools"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/csstools"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=18"
      },
      "peerDependencies": {
        "@csstools/css-tokenizer": "^3.0.4"
      }
    },
    "node_modules/@csstools/css-tokenizer": {
      "version": "3.0.4",
      "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
      "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/csstools"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/csstools"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/agent-base": {
      "version": "7.1.4",
      "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
      "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 14"
      }
    },
    "node_modules/cssstyle": {
      "version": "4.6.0",
      "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
      "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",
      "license": "MIT",
      "dependencies": {
        "@asamuzakjp/css-color": "^3.2.0",
        "rrweb-cssom": "^0.8.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/data-urls": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
      "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
      "license": "MIT",
      "dependencies": {
        "whatwg-mimetype": "^4.0.0",
        "whatwg-url": "^14.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/debug": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
      "license": "MIT",
      "dependencies": {
        "ms": "^2.1.3"
      },
      "engines": {
        "node": ">=6.0"
      },
      "peerDependenciesMeta": {
        "supports-color": {
          "optional": true
        }
      }
    },
    "node_modules/decimal.js": {
      "version": "10.6.0",
      "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
      "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
      "license": "MIT"
    },
    "node_modules/entities": {
      "version": "6.0.1",
      "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
      "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=0.12"
      },
      "funding": {
        "url": "https://github.com/fb55/entities?sponsor=1"
      }
    },
    "node_modules/html-encoding-sniffer": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
      "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
      "license": "MIT",
      "dependencies": {
        "whatwg-encoding": "^3.1.1"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/http-proxy-agent": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
      "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
      "license": "MIT",
      "dependencies": {
        "agent-base": "^7.1.0",
        "debug": "^4.3.4"
      },
      "engines": {
        "node": ">= 14"
      }
    },
    "node_modules/https-proxy-agent": {
      "version": "7.0.6",
      "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
      "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
      "license": "MIT",
      "dependencies": {
        "agent-base": "^7.1.2",
        "debug": "4"
      },
      "engines": {
        "node": ">= 14"
      }
    },
    "node_modules/iconv-lite": {
      "version": "0.6.3",
      "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
      "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
      "license": "MIT",
      "dependencies": {
        "safer-buffer": ">= 2.1.2 < 3.0.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/is-potential-custom-element-name": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
      "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
      "license": "MIT"
    },
    "node_modules/jsdom": {
      "version": "26.1.0",
      "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",
      "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
      "license": "MIT",
      "dependencies": {
        "cssstyle": "^4.2.1",
        "data-urls": "^5.0.0",
        "decimal.js": "^10.5.0",
        "html-encoding-sniffer": "^4.0.0",
        "http-proxy-agent": "^7.0.2",
        "https-proxy-agent": "^7.0.6",
        "is-potential-custom-element-name": "^1.0.1",
        "nwsapi": "^2.2.16",
        "parse5": "^7.2.1",
        "rrweb-cssom": "^0.8.0",
        "saxes": "^6.0.0",
        "symbol-tree": "^3.2.4",
        "tough-cookie": "^5.1.1",
        "w3c-xmlserializer": "^5.0.0",
        "webidl-conversions": "^7.0.0",
        "whatwg-encoding": "^3.1.1",
        "whatwg-mimetype": "^4.0.0",
        "whatwg-url": "^14.1.1",
        "ws": "^8.18.0",
        "xml-name-validator": "^5.0.0"
      },
      "engines": {
        "node": ">=18"
      },
      "peerDependencies": {
        "canvas": "^3.0.0"
      },
      "peerDependenciesMeta": {
        "canvas": {
          "optional": true
        }
      }
    },
    "node_modules/lru-cache": {
      "version": "10.4.3",
      "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
      "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
      "license": "ISC"
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    },
    "node_modules/nwsapi": {
      "version": "2.2.24",
      "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.24.tgz",
      "integrity": "sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==",
      "license": "MIT"
    },
    "node_modules/parse5": {
      "version": "7.3.0",
      "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
      "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
      "license": "MIT",
      "dependencies": {
        "entities": "^6.0.0"
      },
      "funding": {
        "url": "https://github.com/inikulin/parse5?sponsor=1"
      }
    },
    "node_modules/punycode": {
      "version": "2.3.1",
      "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
      "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/rrweb-cssom": {
      "version": "0.8.0",
      "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
      "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
      "license": "MIT"
    },
    "node_modules/safer-buffer": {
      "version": "2.1.2",
      "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
      "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
      "license": "MIT"
    },
    "node_modules/saxes": {
      "version": "6.0.0",
      "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
      "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
      "license": "ISC",
      "dependencies": {
        "xmlchars": "^2.2.0"
      },
      "engines": {
        "node": ">=v12.22.7"
      }
    },
    "node_modules/symbol-tree": {
      "version": "3.2.4",
      "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
      "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
      "license": "MIT"
    },
    "node_modules/tldts": {
      "version": "6.1.86",
      "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
      "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
      "license": "MIT",
      "dependencies": {
        "tldts-core": "^6.1.86"
      },
      "bin": {
        "tldts": "bin/cli.js"
      }
    },
    "node_modules/tldts-core": {
      "version": "6.1.86",
      "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
      "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
      "license": "MIT"
    },
    "node_modules/tough-cookie": {
      "version": "5.1.2",
      "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
      "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "tldts": "^6.1.32"
      },
      "engines": {
        "node": ">=16"
      }
    },
    "node_modules/tr46": {
      "version": "5.1.1",
      "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
      "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
      "license": "MIT",
      "dependencies": {
        "punycode": "^2.3.1"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/w3c-xmlserializer": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
      "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
      "license": "MIT",
      "dependencies": {
        "xml-name-validator": "^5.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/webidl-conversions": {
      "version": "7.0.0",
      "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
      "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/whatwg-encoding": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
      "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
      "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",
      "license": "MIT",
      "dependencies": {
        "iconv-lite": "0.6.3"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/whatwg-mimetype": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
      "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
      "license": "MIT",
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/whatwg-url": {
      "version": "14.2.0",
      "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
      "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
      "license": "MIT",
      "dependencies": {
        "tr46": "^5.1.0",
        "webidl-conversions": "^7.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/ws": {
      "version": "8.21.3",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
      "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
      "license": "MIT",
      "engines": {
        "node": ">=10.0.0"
      },
      "peerDependencies": {
        "bufferutil": "^4.0.1",
        "utf-8-validate": ">=5.0.2"
      },
      "peerDependenciesMeta": {
        "bufferutil": {
          "optional": true
        },
        "utf-8-validate": {
          "optional": true
        }
      }
    },
    "node_modules/xml-name-validator": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
      "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
      "license": "Apache-2.0",
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/xmlchars": {
      "version": "2.2.0",
      "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
      "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-jsdom-resourceloader",
  "version": "1.0.0",
  "description": "Clean-room verification sample for JSDOM ResourceLoader subresource customization",
  "type": "module",
  "private": true,
  "dependencies": {
    "jsdom": "26.1.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Intercept and customize subresource loading in JSDOM using ResourceLoader",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jsdom@26.1.0"
  ],
  "symbols": [
    "JSDOM",
    "ResourceLoader"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import { JSDOM, ResourceLoader, VirtualConsole } from 'jsdom';
import { InterceptingResourceLoader, createCustomDOM } from '../index.mjs';

// 1. ResourceLoader constructor accepts configuration options including userAgent, proxy, and strictSSL.
{
  const defaultLoader = new ResourceLoader();
  assert.ok(defaultLoader instanceof ResourceLoader);

  const configuredLoader = new ResourceLoader({
    strictSSL: false,
    proxy: 'http://127.0.0.1:8080',
    userAgent: 'CustomBrowser/1.0',
  });
  assert.ok(configuredLoader instanceof ResourceLoader);
}

// 2. Instantiating JSDOM without configuring resources suppresses all external subresource fetching for scripts and stylesheets.
{
  const defaultDom = new JSDOM(`
    <!DOCTYPE html>
    <html>
      <head>
        <script src="https://example.com/unfetched.js"></script>
        <link rel="stylesheet" href="https://example.com/unfetched.css">
      </head>
      <body>
        <p>Default resource loading test</p>
      </body>
    </html>
  `, {
    url: 'https://example.com/',
    runScripts: 'dangerously',
  });

  assert.strictEqual(defaultDom.window.unfetchedRan, undefined);
  assert.strictEqual(defaultDom.window.document.styleSheets.length, 0);
}

// 3. Attaching a custom ResourceLoader subclass intercepts subresource fetch requests and passes the requesting element reference in fetch options.
{
  const scriptUrl = 'https://example.com/assets/sample.js';
  const styleUrl = 'https://example.com/assets/sample.css';

  const loader = new InterceptingResourceLoader({}, {
    [scriptUrl]: 'window.sampleLoaded = true;',
    [styleUrl]: 'body { color: red; }',
  });

  const dom = createCustomDOM(`
    <!DOCTYPE html>
    <html>
      <head></head>
      <body></body>
    </html>
  `, {
    url: 'https://example.com/',
    runScripts: 'dangerously',
  }, loader);

  const { document } = dom.window;

  await new Promise((resolve) => {
    let pending = 2;
    const checkDone = () => {
      pending--;
      if (pending === 0) resolve();
    };

    const script = document.createElement('script');
    script.src = scriptUrl;
    script.onload = checkDone;
    document.head.appendChild(script);

    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = styleUrl;
    link.onload = checkDone;
    document.head.appendChild(link);
  });

  assert.strictEqual(loader.requests.length, 2);
  assert.strictEqual(loader.requests[0].url, scriptUrl);
  assert.strictEqual(loader.requests[0].tagName, 'SCRIPT');
  assert.ok(loader.requests[0].element);

  assert.strictEqual(loader.requests[1].url, styleUrl);
  assert.strictEqual(loader.requests[1].tagName, 'LINK');
  assert.ok(loader.requests[1].element);
}

// 4. Returning a Buffer promise from ResourceLoader fetch resolves synthetic external script content and executes it within the JSDOM window context under runScripts dangerously.
{
  const scriptUrl = 'https://example.com/app/main.js';
  const loader = new InterceptingResourceLoader({ userAgent: 'CustomAgent/1.0' }, {
    [scriptUrl]: 'window.appRan = true; window.appValue = 100; const div = document.createElement("div"); div.id = "app-root"; div.textContent = "Initialized"; document.body.appendChild(div);',
  });

  const dom = createCustomDOM(`
    <!DOCTYPE html>
    <html>
      <head></head>
      <body></body>
    </html>
  `, {
    url: 'https://example.com/app/',
    runScripts: 'dangerously',
  }, loader);

  const { window } = dom;
  const { document } = window;

  let scriptLoaded = false;
  await new Promise((resolve) => {
    const script = document.createElement('script');
    script.src = scriptUrl;
    script.onload = () => {
      scriptLoaded = true;
      resolve();
    };
    document.head.appendChild(script);
  });

  assert.strictEqual(scriptLoaded, true);
  assert.strictEqual(window.appRan, true);
  assert.strictEqual(window.appValue, 100);
  const rootEl = document.getElementById('app-root');
  assert.ok(rootEl);
  assert.strictEqual(rootEl.textContent, 'Initialized');
}

// 5. Returning a Buffer promise from ResourceLoader fetch parses external stylesheets into document.styleSheets rules.
{
  const cssUrl = 'https://example.com/styles/theme.css';
  const loader = new InterceptingResourceLoader({}, {
    [cssUrl]: 'body { margin: 0; } .active-panel { display: flex; opacity: 1; }',
  });

  const dom = createCustomDOM(`
    <!DOCTYPE html>
    <html>
      <head></head>
      <body></body>
    </html>
  `, {
    url: 'https://example.com/',
  }, loader);

  const { document } = dom.window;

  let cssLoaded = false;
  await new Promise((resolve) => {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = cssUrl;
    link.onload = () => {
      cssLoaded = true;
      resolve();
    };
    document.head.appendChild(link);
  });

  assert.strictEqual(cssLoaded, true);
  assert.strictEqual(document.styleSheets.length, 1);
  const styleSheet = document.styleSheets[0];
  assert.strictEqual(styleSheet.cssRules.length, 2);
  assert.strictEqual(styleSheet.cssRules[0].selectorText, 'body');
  assert.strictEqual(styleSheet.cssRules[1].selectorText, '.active-panel');
}

// 6. Returning null from ResourceLoader fetch silently blocks subresource fetching without throwing exceptions, emitting jsdomError, or firing element event handlers.
{
  const blockedUrl = 'https://example.com/assets/blocked.js';
  const loader = new InterceptingResourceLoader({}, {
    [blockedUrl]: null,
  });

  const virtualConsole = new VirtualConsole();
  const errors = [];
  virtualConsole.on('jsdomError', (err) => {
    errors.push(err);
  });

  const dom = createCustomDOM(`
    <!DOCTYPE html>
    <html>
      <head></head>
      <body></body>
    </html>
  `, {
    url: 'https://example.com/',
    runScripts: 'dangerously',
    virtualConsole,
  }, loader);

  const { document } = dom.window;
  let loadFired = false;
  let errorFired = false;

  const script = document.createElement('script');
  script.src = blockedUrl;
  script.onload = () => { loadFired = true; };
  script.onerror = () => { errorFired = true; };
  document.head.appendChild(script);

  await new Promise((r) => setTimeout(r, 60));

  assert.strictEqual(loadFired, false);
  assert.strictEqual(errorFired, false);
  assert.strictEqual(errors.length, 0);
}

// 7. Rejecting the promise returned from ResourceLoader fetch triggers element onerror handlers and emits a jsdomError event to VirtualConsole.
{
  const failUrl = 'https://example.com/assets/failing-script.js';
  const loader = new InterceptingResourceLoader({}, {
    [failUrl]: () => Promise.reject(new Error('Simulated network timeout')),
  });

  const virtualConsole = new VirtualConsole();
  const capturedJsdomErrors = [];
  virtualConsole.on('jsdomError', (err) => {
    capturedJsdomErrors.push(err);
  });

  const dom = createCustomDOM(`
    <!DOCTYPE html>
    <html>
      <head></head>
      <body></body>
    </html>
  `, {
    url: 'https://example.com/',
    runScripts: 'dangerously',
    virtualConsole,
  }, loader);

  const { document } = dom.window;
  let errorFired = false;

  await new Promise((resolve) => {
    const script = document.createElement('script');
    script.src = failUrl;
    script.onerror = () => {
      errorFired = true;
      resolve();
    };
    document.head.appendChild(script);
  });

  assert.strictEqual(errorFired, true);
  assert.ok(capturedJsdomErrors.length >= 1);
  assert.match(capturedJsdomErrors[0].message, /Could not load script/);
  assert.match(capturedJsdomErrors[0].detail?.message || '', /Simulated network timeout/);
}

console.log('All JSDOM ResourceLoader contract assertions passed successfully.');

Ursprungs-Seeder

anonym