jest-environment-webgl-node 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [jest-environment-webgl-node-v0.1.2](https://github.com/bhouston/jest-gpu/compare/jest-environment-webgl-node-v0.1.1...jest-environment-webgl-node-v0.1.2) (2026-09-21)
2
+
3
+ ### Bug Fixes
4
+
5
+ * **webgl:** detect backend conflicts against the initialized display ([e68573d](https://github.com/bhouston/jest-gpu/commit/e68573d1f5cd20e571d4e313ad244f6a8a41d513)), closes [#21](https://github.com/bhouston/jest-gpu/issues/21)
package/README.md CHANGED
@@ -42,10 +42,20 @@ it('renders', () => {
42
42
  ```
43
43
 
44
44
  `testEnvironmentOptions` are those of node-webgl's `init()` (`backend`, `api`) and `installDOM()`
45
- (`baseDir`, `fetch`, `devicePixelRatio`, `innerWidth`, `innerHeight`, `frameInterval`). Because
46
- `installDOM()` writes to the host `globalThis` and is idempotent, only the **first** test file's
47
- options take effect for the underlying host install; every test file's sandbox still gets the
48
- same installed globals copied in.
45
+ (`baseDir`, `fetch`, `devicePixelRatio`, `innerWidth`, `innerHeight`, `frameInterval`). Each test
46
+ file receives a fresh document, DOM event state, viewport values, file-fetch base directory and
47
+ animation-frame queue. Animation frames use Jest's sandbox timers, so `jest.useFakeTimers()` and
48
+ `jest.advanceTimersByTime()` control them; pending frames are cancelled during environment
49
+ teardown.
50
+
51
+ File fetching is enabled by default. Relative paths resolve from that test file's `baseDir`
52
+ (default: `process.cwd()`), while HTTP, data and blob URLs use Node's native `fetch`. Set
53
+ `fetch: false` to use native fetch for every URL. The environment never replaces host globals.
54
+
55
+ The native WebGL display itself is process-wide and is created by the first context in a worker, so
56
+ set `backend` and `api` consistently across all projects that can share a Jest worker. The
57
+ environment throws if an explicit `backend` or `api` disagrees with the display already initialized
58
+ in that worker, including one initialized with platform defaults by a project that set no options.
49
59
 
50
60
  Types for the installed globals: add `import 'jest-environment-webgl-node/globals';` to a `.d.ts`
51
61
  file your tsconfig includes.
@@ -57,6 +67,12 @@ a test file itself imports an ESM-only library.
57
67
  On Linux CI install Mesa (`apt-get install libegl1 libgles2 libgl1-mesa-dri`) and set
58
68
  `LIBGL_ALWAYS_SOFTWARE=1`. macOS and Windows use prebuilt binaries.
59
69
 
70
+ ## Using Vitest?
71
+
72
+ The equivalent package for Vitest is
73
+ [`vitest-environment-webgl-node`](https://github.com/bhouston/vitest-gpu/tree/main/packages/vitest-environment-webgl-node)
74
+ from [vitest-gpu](https://github.com/bhouston/vitest-gpu).
75
+
60
76
  ## Author
61
77
 
62
78
  Created by [Ben Houston](https://ben3d.ca) and sponsored by [Land of Assets](https://landofassets.com).
package/dist/index.cjs CHANGED
@@ -2,48 +2,222 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let node_fs_promises = require("node:fs/promises");
28
+ let node_path = require("node:path");
29
+ let node_url = require("node:url");
5
30
  let _onirenaud_node_webgl = require("@onirenaud/node-webgl");
31
+ _onirenaud_node_webgl = __toESM(_onirenaud_node_webgl, 1);
6
32
  let jest_environment_node = require("jest-environment-node");
7
33
  //#region src/index.ts
8
- let domNames;
9
- function ensureHostDOM(options) {
10
- if (domNames) return domNames;
11
- const { backend, api, ...dom } = options;
12
- if (backend || api) (0, _onirenaud_node_webgl.init)({
13
- backend,
14
- api
34
+ const WEBGL_OPTION_NAMES = /* @__PURE__ */ new Set([
35
+ "api",
36
+ "backend",
37
+ "baseDir",
38
+ "devicePixelRatio",
39
+ "fetch",
40
+ "frameInterval",
41
+ "innerHeight",
42
+ "innerWidth"
43
+ ]);
44
+ const MIME = {
45
+ ".basis": "application/octet-stream",
46
+ ".bin": "application/octet-stream",
47
+ ".drc": "application/octet-stream",
48
+ ".exr": "image/x-exr",
49
+ ".fbx": "application/octet-stream",
50
+ ".gif": "image/gif",
51
+ ".glb": "model/gltf-binary",
52
+ ".gltf": "model/gltf+json",
53
+ ".hdr": "image/vnd.radiance",
54
+ ".jpeg": "image/jpeg",
55
+ ".jpg": "image/jpeg",
56
+ ".js": "text/javascript",
57
+ ".json": "application/json",
58
+ ".ktx": "image/ktx",
59
+ ".ktx2": "image/ktx2",
60
+ ".mjs": "text/javascript",
61
+ ".mtl": "text/plain",
62
+ ".obj": "text/plain",
63
+ ".png": "image/png",
64
+ ".svg": "image/svg+xml",
65
+ ".txt": "text/plain",
66
+ ".wasm": "application/wasm",
67
+ ".webp": "image/webp"
68
+ };
69
+ const DOM_NAMES = [
70
+ "window",
71
+ "self",
72
+ "HTMLCanvasElement",
73
+ "OffscreenCanvas",
74
+ "HTMLImageElement",
75
+ "Image",
76
+ "ImageData",
77
+ "ImageBitmap",
78
+ "createImageBitmap",
79
+ "FileReader",
80
+ "HTMLElement",
81
+ "Element",
82
+ "Node",
83
+ "devicePixelRatio",
84
+ "innerWidth",
85
+ "innerHeight",
86
+ "screen",
87
+ "requestAnimationFrame",
88
+ "cancelAnimationFrame",
89
+ "getComputedStyle",
90
+ "matchMedia",
91
+ "scrollTo",
92
+ "alert",
93
+ "location",
94
+ "document",
95
+ ...Object.keys(_onirenaud_node_webgl).filter((name) => name.startsWith("WebGL"))
96
+ ];
97
+ let initializedWith;
98
+ /**
99
+ * The native EGL display is process-wide and node-webgl's `init()` is a no-op once it exists (the first
100
+ * context creates it lazily), so compare explicit options against the live display rather than only
101
+ * against what this module itself initialized.
102
+ */
103
+ function initialize({ api, backend }) {
104
+ if (!api && !backend) return;
105
+ if (initializedWith && initializedWith.api === api && initializedWith.backend === backend) return;
106
+ const display = _onirenaud_node_webgl.getDisplayInfo();
107
+ if (display && (backend && backend !== "default" && backend !== display.backend || api && api !== "auto" && api !== display.api)) throw new Error(`node-webgl is already initialized with ${JSON.stringify({
108
+ api: display.api,
109
+ backend: display.backend
110
+ })}; cannot switch this Jest worker to ${JSON.stringify({
111
+ api,
112
+ backend
113
+ })}`);
114
+ _onirenaud_node_webgl.init({
115
+ api,
116
+ backend
15
117
  });
16
- const before = new Set(Object.getOwnPropertyNames(globalThis));
17
- (0, _onirenaud_node_webgl.installDOM)(dom);
18
- domNames = Object.getOwnPropertyNames(globalThis).filter((key) => !before.has(key));
19
- return domNames;
118
+ initializedWith = {
119
+ api,
120
+ backend
121
+ };
122
+ }
123
+ /** Capture a fresh node-webgl DOM while restoring every host descriptor after installation. */
124
+ function createDOM(options) {
125
+ const before = Object.getOwnPropertyDescriptors(globalThis);
126
+ for (const name of DOM_NAMES) Reflect.deleteProperty(globalThis, name);
127
+ try {
128
+ _onirenaud_node_webgl.installDOM({
129
+ ...options,
130
+ fetch: false
131
+ });
132
+ const after = Object.getOwnPropertyDescriptors(globalThis);
133
+ return new Map(DOM_NAMES.flatMap((name) => after[name] ? [[name, after[name]]] : []));
134
+ } finally {
135
+ for (const name of Object.getOwnPropertyNames(globalThis)) if (!(name in before)) Reflect.deleteProperty(globalThis, name);
136
+ Object.defineProperties(globalThis, before);
137
+ }
138
+ }
139
+ function environmentConfig(config) {
140
+ return {
141
+ ...config,
142
+ projectConfig: {
143
+ ...config.projectConfig,
144
+ testEnvironmentOptions: Object.fromEntries(Object.entries(config.projectConfig.testEnvironmentOptions).filter(([name]) => !WEBGL_OPTION_NAMES.has(name)))
145
+ }
146
+ };
147
+ }
148
+ function localFetch(baseDir, nativeFetch) {
149
+ return async (input, init) => {
150
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
151
+ if (/^(https?|data|blob):/i.test(url)) return nativeFetch(input, init);
152
+ const path = url.startsWith("file:") ? (0, node_url.fileURLToPath)(url) : (0, node_path.resolve)(baseDir, url.replace(/[?#].*$/, ""));
153
+ try {
154
+ const bytes = await (0, node_fs_promises.readFile)(path);
155
+ return new Response(bytes, {
156
+ status: 200,
157
+ headers: { "content-type": MIME[(0, node_path.extname)(path).toLowerCase()] ?? "application/octet-stream" }
158
+ });
159
+ } catch {
160
+ return new Response(null, {
161
+ status: 404,
162
+ statusText: "Not Found"
163
+ });
164
+ }
165
+ };
20
166
  }
21
167
  var WebglEnvironment = class extends jest_environment_node.TestEnvironment {
22
- added;
168
+ added = [];
169
+ animationFrames = /* @__PURE__ */ new Map();
23
170
  constructor(config, context) {
24
- super(config, context);
25
- const nativeAdded = !Object.getOwnPropertyNames(this.global).includes("_native");
26
- if (nativeAdded) Object.defineProperty(this.global, "_native", {
27
- value: void 0,
28
- writable: true,
29
- configurable: true,
30
- enumerable: false
31
- });
32
171
  const options = config.projectConfig.testEnvironmentOptions;
33
- const names = ensureHostDOM(options);
172
+ super(environmentConfig(config), context);
173
+ const { api, backend, ...domOptions } = options;
174
+ initialize({
175
+ api,
176
+ backend
177
+ });
34
178
  const g = this.global;
35
- this.added = names.filter((key) => !(key in g));
36
- for (const key of this.added) g[key] = globalThis[key];
37
- if (nativeAdded) this.added.push("_native");
179
+ if (!Object.getOwnPropertyNames(g).includes("_native")) {
180
+ Object.defineProperty(g, "_native", {
181
+ value: void 0,
182
+ writable: true,
183
+ configurable: true,
184
+ enumerable: false
185
+ });
186
+ this.added.push("_native");
187
+ }
188
+ for (const [name, descriptor] of createDOM(domOptions)) {
189
+ if (!(name in g)) this.added.push(name);
190
+ Object.defineProperty(g, name, descriptor);
191
+ }
38
192
  g.window = g;
39
193
  g.self = g;
40
- for (const target of [g.window, g.document]) {
41
- target.addEventListener ??= () => {};
42
- target.removeEventListener ??= () => {};
43
- }
194
+ g.document.defaultView = g;
195
+ const events = new EventTarget();
196
+ g.addEventListener = events.addEventListener.bind(events);
197
+ g.removeEventListener = events.removeEventListener.bind(events);
198
+ g.dispatchEvent = events.dispatchEvent.bind(events);
199
+ this.added.push("addEventListener", "removeEventListener", "dispatchEvent");
200
+ const interval = domOptions.frameInterval ?? 16;
201
+ g.requestAnimationFrame = (callback) => {
202
+ const id = g.setTimeout(() => {
203
+ this.animationFrames.delete(id);
204
+ callback(g.performance.now());
205
+ }, interval);
206
+ this.animationFrames.set(id, g.clearTimeout);
207
+ return id;
208
+ };
209
+ g.cancelAnimationFrame = (id) => {
210
+ const clear = this.animationFrames.get(id);
211
+ this.animationFrames.delete(id);
212
+ (clear ?? g.clearTimeout)(id);
213
+ };
214
+ const nativeFetch = globalThis.fetch.bind(globalThis);
215
+ g.fetch = domOptions.fetch === false ? nativeFetch : localFetch(domOptions.baseDir ?? process.cwd(), nativeFetch);
44
216
  }
45
217
  async teardown() {
46
218
  const g = this.global;
219
+ for (const [id, clear] of this.animationFrames) clear(id);
220
+ this.animationFrames.clear();
47
221
  for (const key of this.added) delete g[key];
48
222
  await super.teardown();
49
223
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TestEnvironment"],"sources":["../src/index.ts"],"sourcesContent":["import { init, installDOM, type InitOptions, type InstallDOMOptions } from '@onirenaud/node-webgl';\nimport { TestEnvironment } from 'jest-environment-node';\n\n/** Set under `testEnvironmentOptions` in your Jest config. */\nexport type WebglNodeOptions = InitOptions & InstallDOMOptions;\n\n// Typed from TestEnvironment's own constructor rather than importing `@jest/environment`\n// directly: that package is only a transitive dependency (of jest-environment-node), not\n// resolvable from this package's own node_modules under pnpm's strict layout.\ntype JestEnvironmentConfig = ConstructorParameters<typeof TestEnvironment>[0];\ntype EnvironmentContext = ConstructorParameters<typeof TestEnvironment>[1];\n\n// node-webgl's installDOM() writes to the HOST globalThis (not a target you pass in) and is\n// idempotent (it skips names already defined). So it can only usefully run once per process: on\n// the first WebglEnvironment constructed here, snapshot the host globals before/after the call and\n// remember which names it added. Every later environment (this test file or another one sharing\n// the worker) copies that same fixed list into its own sandbox global instead of calling\n// installDOM() again. This means only the FIRST test file's `testEnvironmentOptions` actually\n// affect the host install (backend/api selection, DOM option defaults); later test files'\n// options for those are ignored, matching how node-webgl itself behaves.\nlet domNames: readonly string[] | undefined;\n\nfunction ensureHostDOM(options: WebglNodeOptions): readonly string[] {\n if (domNames) return domNames;\n const { backend, api, ...dom } = options;\n if (backend || api) init({ backend, api });\n const before = new Set(Object.getOwnPropertyNames(globalThis));\n installDOM(dom);\n domNames = Object.getOwnPropertyNames(globalThis).filter((key) => !before.has(key));\n return domNames;\n}\n\nexport default class WebglEnvironment extends TestEnvironment {\n private readonly added: string[];\n\n constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {\n super(config, context);\n // @babylonjs/core defines a `_native` accessor on `self` at module load; on Jest's proxied\n // sandbox global that defineProperty violates a proxy invariant, so pre-seed the property to\n // satisfy Babylon's hasOwnProperty guard.\n // `Object.hasOwn`/`in` report false negatives here: jest-environment-node's sandbox global is\n // a Proxy over a vm context, and reads of freshly-added properties from outside the sandbox\n // (as this constructor runs) don't go through the fast path those use. getOwnPropertyNames is\n // unaffected, so use that instead.\n const nativeAdded = !Object.getOwnPropertyNames(this.global).includes('_native');\n if (nativeAdded) {\n Object.defineProperty(this.global, '_native', {\n value: undefined,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n }\n // Jest always populates `testEnvironmentOptions` (defaulting to `{}`) by the time a real\n // config reaches an environment; `super()` above already relies on that itself.\n const options = config.projectConfig.testEnvironmentOptions as WebglNodeOptions;\n const names = ensureHostDOM(options);\n const g = this.global as unknown as Record<string, unknown>;\n this.added = names.filter((key) => !(key in g));\n for (const key of this.added) g[key] = (globalThis as unknown as Record<string, unknown>)[key];\n if (nativeAdded) this.added.push('_native');\n g.window = g;\n g.self = g;\n // node-webgl's window/document have no event methods; engines like Babylon.js register\n // resize/blur listeners on them. installDOM() always installs both, so both are present here.\n for (const target of [g.window, g.document] as Record<string, unknown>[]) {\n target.addEventListener ??= () => {};\n target.removeEventListener ??= () => {};\n }\n }\n\n override async teardown(): Promise<void> {\n const g = this.global as unknown as Record<string, unknown>;\n for (const key of this.added) delete g[key];\n await super.teardown();\n }\n}\n"],"mappings":";;;;;;;AAoBA,IAAI;AAEJ,SAAS,cAAc,SAA8C;CACnE,IAAI,UAAU,OAAO;CACrB,MAAM,EAAE,SAAS,KAAK,GAAG,QAAQ;CACjC,IAAI,WAAW,KAAK,CAAA,GAAA,sBAAA,KAAA,CAAK;EAAE;EAAS;CAAI,CAAC;CACzC,MAAM,SAAS,IAAI,IAAI,OAAO,oBAAoB,UAAU,CAAC;CAC7D,CAAA,GAAA,sBAAA,WAAA,CAAW,GAAG;CACd,WAAW,OAAO,oBAAoB,UAAU,CAAC,CAAC,QAAQ,QAAQ,CAAC,OAAO,IAAI,GAAG,CAAC;CAClF,OAAO;AACT;AAEA,IAAqB,mBAArB,cAA8CA,sBAAAA,gBAAgB;CAC5D;CAEA,YAAY,QAA+B,SAA6B;EACtE,MAAM,QAAQ,OAAO;EAQrB,MAAM,cAAc,CAAC,OAAO,oBAAoB,KAAK,MAAM,CAAC,CAAC,SAAS,SAAS;EAC/E,IAAI,aACF,OAAO,eAAe,KAAK,QAAQ,WAAW;GAC5C,OAAO,KAAA;GACP,UAAU;GACV,cAAc;GACd,YAAY;EACd,CAAC;EAIH,MAAM,UAAU,OAAO,cAAc;EACrC,MAAM,QAAQ,cAAc,OAAO;EACnC,MAAM,IAAI,KAAK;EACf,KAAK,QAAQ,MAAM,QAAQ,QAAQ,EAAE,OAAO,EAAE;EAC9C,KAAK,MAAM,OAAO,KAAK,OAAO,EAAE,OAAQ,WAAkD;EAC1F,IAAI,aAAa,KAAK,MAAM,KAAK,SAAS;EAC1C,EAAE,SAAS;EACX,EAAE,OAAO;EAGT,KAAK,MAAM,UAAU,CAAC,EAAE,QAAQ,EAAE,QAAQ,GAAgC;GACxE,OAAO,2BAA2B,CAAC;GACnC,OAAO,8BAA8B,CAAC;EACxC;CACF;CAEA,MAAe,WAA0B;EACvC,MAAM,IAAI,KAAK;EACf,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,EAAE;EACvC,MAAM,MAAM,SAAS;CACvB;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["nodeWebGL","fileURLToPath","resolvePath","readFile","extname","TestEnvironment"],"sources":["../src/index.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { extname, resolve as resolvePath } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport * as nodeWebGL from '@onirenaud/node-webgl';\nimport type { InitOptions, InstallDOMOptions } from '@onirenaud/node-webgl';\nimport { TestEnvironment } from 'jest-environment-node';\n\n/** Set under `testEnvironmentOptions` in your Jest config. */\nexport type WebglNodeOptions = InitOptions & InstallDOMOptions;\n\ntype JestEnvironmentConfig = ConstructorParameters<typeof TestEnvironment>[0];\ntype EnvironmentContext = ConstructorParameters<typeof TestEnvironment>[1];\ntype Sandbox = Record<string, unknown>;\n\nconst WEBGL_OPTION_NAMES = new Set([\n 'api',\n 'backend',\n 'baseDir',\n 'devicePixelRatio',\n 'fetch',\n 'frameInterval',\n 'innerHeight',\n 'innerWidth',\n]);\n\nconst MIME: Record<string, string> = {\n '.basis': 'application/octet-stream',\n '.bin': 'application/octet-stream',\n '.drc': 'application/octet-stream',\n '.exr': 'image/x-exr',\n '.fbx': 'application/octet-stream',\n '.gif': 'image/gif',\n '.glb': 'model/gltf-binary',\n '.gltf': 'model/gltf+json',\n '.hdr': 'image/vnd.radiance',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.ktx': 'image/ktx',\n '.ktx2': 'image/ktx2',\n '.mjs': 'text/javascript',\n '.mtl': 'text/plain',\n '.obj': 'text/plain',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n};\n\nconst DOM_NAMES = [\n 'window',\n 'self',\n 'HTMLCanvasElement',\n 'OffscreenCanvas',\n 'HTMLImageElement',\n 'Image',\n 'ImageData',\n 'ImageBitmap',\n 'createImageBitmap',\n 'FileReader',\n 'HTMLElement',\n 'Element',\n 'Node',\n 'devicePixelRatio',\n 'innerWidth',\n 'innerHeight',\n 'screen',\n 'requestAnimationFrame',\n 'cancelAnimationFrame',\n 'getComputedStyle',\n 'matchMedia',\n 'scrollTo',\n 'alert',\n 'location',\n 'document',\n ...Object.keys(nodeWebGL).filter((name) => name.startsWith('WebGL')),\n] as const;\n\nlet initializedWith: InitOptions | undefined;\n\n/**\n * The native EGL display is process-wide and node-webgl's `init()` is a no-op once it exists (the first\n * context creates it lazily), so compare explicit options against the live display rather than only\n * against what this module itself initialized.\n */\nfunction initialize({ api, backend }: InitOptions): void {\n if (!api && !backend) return;\n if (initializedWith && initializedWith.api === api && initializedWith.backend === backend) return;\n const display = nodeWebGL.getDisplayInfo();\n const mismatch =\n display &&\n ((backend && backend !== 'default' && backend !== display.backend) ||\n (api && api !== 'auto' && api !== display.api));\n if (mismatch) {\n throw new Error(\n `node-webgl is already initialized with ${JSON.stringify({ api: display.api, backend: display.backend })}; ` +\n `cannot switch this Jest worker to ${JSON.stringify({ api, backend })}`,\n );\n }\n nodeWebGL.init({ api, backend });\n initializedWith = { api, backend };\n}\n\n/** Capture a fresh node-webgl DOM while restoring every host descriptor after installation. */\nfunction createDOM(options: InstallDOMOptions): Map<string, PropertyDescriptor> {\n const before = Object.getOwnPropertyDescriptors(globalThis);\n for (const name of DOM_NAMES) Reflect.deleteProperty(globalThis, name);\n\n try {\n nodeWebGL.installDOM({ ...options, fetch: false });\n const after = Object.getOwnPropertyDescriptors(globalThis);\n return new Map(\n DOM_NAMES.flatMap((name): [string, PropertyDescriptor][] => (after[name] ? [[name, after[name]]] : [])),\n );\n } finally {\n for (const name of Object.getOwnPropertyNames(globalThis)) {\n if (!(name in before)) Reflect.deleteProperty(globalThis, name);\n }\n Object.defineProperties(globalThis, before);\n }\n}\n\nfunction environmentConfig(config: JestEnvironmentConfig): JestEnvironmentConfig {\n return {\n ...config,\n projectConfig: {\n ...config.projectConfig,\n testEnvironmentOptions: Object.fromEntries(\n Object.entries(config.projectConfig.testEnvironmentOptions).filter(([name]) => !WEBGL_OPTION_NAMES.has(name)),\n ),\n },\n };\n}\n\nfunction localFetch(baseDir: string, nativeFetch: typeof fetch): typeof fetch {\n return async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n if (/^(https?|data|blob):/i.test(url)) return nativeFetch(input, init);\n const path = url.startsWith('file:') ? fileURLToPath(url) : resolvePath(baseDir, url.replace(/[?#].*$/, ''));\n try {\n const bytes = await readFile(path);\n return new Response(bytes, {\n status: 200,\n headers: { 'content-type': MIME[extname(path).toLowerCase()] ?? 'application/octet-stream' },\n });\n } catch {\n return new Response(null, { status: 404, statusText: 'Not Found' });\n }\n };\n}\n\nexport default class WebglEnvironment extends TestEnvironment {\n private readonly added: string[] = [];\n private readonly animationFrames = new Map<ReturnType<typeof setTimeout>, typeof clearTimeout>();\n\n constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {\n const options = config.projectConfig.testEnvironmentOptions as WebglNodeOptions;\n super(environmentConfig(config), context);\n\n const { api, backend, ...domOptions } = options;\n initialize({ api, backend });\n\n const g = this.global as unknown as Sandbox;\n const nativeAdded = !Object.getOwnPropertyNames(g).includes('_native');\n if (nativeAdded) {\n Object.defineProperty(g, '_native', {\n value: undefined,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n this.added.push('_native');\n }\n\n for (const [name, descriptor] of createDOM(domOptions)) {\n if (!(name in g)) this.added.push(name);\n Object.defineProperty(g, name, descriptor);\n }\n\n g.window = g;\n g.self = g;\n (g.document as Record<string, unknown>).defaultView = g;\n\n const events = new EventTarget();\n g.addEventListener = events.addEventListener.bind(events);\n g.removeEventListener = events.removeEventListener.bind(events);\n g.dispatchEvent = events.dispatchEvent.bind(events);\n this.added.push('addEventListener', 'removeEventListener', 'dispatchEvent');\n\n const interval = domOptions.frameInterval ?? 16;\n g.requestAnimationFrame = (callback: (time: number) => void) => {\n const id = (g.setTimeout as typeof setTimeout)(() => {\n this.animationFrames.delete(id);\n callback((g.performance as { now(): number }).now());\n }, interval);\n this.animationFrames.set(id, g.clearTimeout as typeof clearTimeout);\n return id;\n };\n g.cancelAnimationFrame = (id: ReturnType<typeof setTimeout>) => {\n const clear = this.animationFrames.get(id);\n this.animationFrames.delete(id);\n (clear ?? (g.clearTimeout as typeof clearTimeout))(id);\n };\n\n const nativeFetch = globalThis.fetch.bind(globalThis);\n g.fetch = domOptions.fetch === false ? nativeFetch : localFetch(domOptions.baseDir ?? process.cwd(), nativeFetch);\n }\n\n override async teardown(): Promise<void> {\n const g = this.global as unknown as Sandbox;\n for (const [id, clear] of this.animationFrames) clear(id);\n this.animationFrames.clear();\n for (const key of this.added) delete g[key];\n await super.teardown();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,OAA+B;CACnC,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ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UAAU;EACpD,EAAE,QAAQ,WAAW,UAAU,QAAQ,cAAc,WAAW,WAAW,WAAW,QAAQ,IAAI,GAAG,WAAW;CAClH;CAEA,MAAe,WAA0B;EACvC,MAAM,IAAI,KAAK;EACf,KAAK,MAAM,CAAC,IAAI,UAAU,KAAK,iBAAiB,MAAM,EAAE;EACxD,KAAK,gBAAgB,MAAM;EAC3B,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,EAAE;EACvC,MAAM,MAAM,SAAS;CACvB;AACF"}
package/dist/index.d.cts CHANGED
@@ -7,6 +7,7 @@ type JestEnvironmentConfig = ConstructorParameters<typeof TestEnvironment>[0];
7
7
  type EnvironmentContext = ConstructorParameters<typeof TestEnvironment>[1];
8
8
  export default class WebglEnvironment extends TestEnvironment {
9
9
  private readonly added;
10
+ private readonly animationFrames;
10
11
  constructor(config: JestEnvironmentConfig, context: EnvironmentContext);
11
12
  teardown(): Promise<void>;
12
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;YAIY,mBAAmB,cAAc;KAKxC,wBAAwB,6BAA6B;KACrD,qBAAqB,6BAA6B;qBAsBlC,yBAAyB;mBAC3B;EAEjB,YAAY,QAAQ,uBAAuB,SAAS;EAoCrC,YAAY"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;YAQY,mBAAmB,cAAc;KAExC,wBAAwB,6BAA6B;KACrD,qBAAqB,6BAA6B;qBA8IlC,yBAAyB;mBAC3B;mBACA;EAEjB,YAAY,QAAQ,uBAAuB,SAAS;EAqDrC,YAAY"}
package/dist/index.d.mts CHANGED
@@ -7,6 +7,7 @@ type JestEnvironmentConfig = ConstructorParameters<typeof TestEnvironment>[0];
7
7
  type EnvironmentContext = ConstructorParameters<typeof TestEnvironment>[1];
8
8
  export default class WebglEnvironment extends TestEnvironment {
9
9
  private readonly added;
10
+ private readonly animationFrames;
10
11
  constructor(config: JestEnvironmentConfig, context: EnvironmentContext);
11
12
  teardown(): Promise<void>;
12
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;YAIY,mBAAmB,cAAc;KAKxC,wBAAwB,6BAA6B;KACrD,qBAAqB,6BAA6B;qBAsBlC,yBAAyB;mBAC3B;EAEjB,YAAY,QAAQ,uBAAuB,SAAS;EAoCrC,YAAY"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;YAQY,mBAAmB,cAAc;KAExC,wBAAwB,6BAA6B;KACrD,qBAAqB,6BAA6B;qBA8IlC,yBAAyB;mBAC3B;mBACA;EAEjB,YAAY,QAAQ,uBAAuB,SAAS;EAqDrC,YAAY"}
package/dist/index.mjs CHANGED
@@ -1,45 +1,196 @@
1
- import { init, installDOM } from "@onirenaud/node-webgl";
1
+ import { readFile } from "node:fs/promises";
2
+ import { extname, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import * as nodeWebGL from "@onirenaud/node-webgl";
2
5
  import { TestEnvironment } from "jest-environment-node";
3
6
  //#region src/index.ts
4
- let domNames;
5
- function ensureHostDOM(options) {
6
- if (domNames) return domNames;
7
- const { backend, api, ...dom } = options;
8
- if (backend || api) init({
9
- backend,
10
- api
7
+ const WEBGL_OPTION_NAMES = /* @__PURE__ */ new Set([
8
+ "api",
9
+ "backend",
10
+ "baseDir",
11
+ "devicePixelRatio",
12
+ "fetch",
13
+ "frameInterval",
14
+ "innerHeight",
15
+ "innerWidth"
16
+ ]);
17
+ const MIME = {
18
+ ".basis": "application/octet-stream",
19
+ ".bin": "application/octet-stream",
20
+ ".drc": "application/octet-stream",
21
+ ".exr": "image/x-exr",
22
+ ".fbx": "application/octet-stream",
23
+ ".gif": "image/gif",
24
+ ".glb": "model/gltf-binary",
25
+ ".gltf": "model/gltf+json",
26
+ ".hdr": "image/vnd.radiance",
27
+ ".jpeg": "image/jpeg",
28
+ ".jpg": "image/jpeg",
29
+ ".js": "text/javascript",
30
+ ".json": "application/json",
31
+ ".ktx": "image/ktx",
32
+ ".ktx2": "image/ktx2",
33
+ ".mjs": "text/javascript",
34
+ ".mtl": "text/plain",
35
+ ".obj": "text/plain",
36
+ ".png": "image/png",
37
+ ".svg": "image/svg+xml",
38
+ ".txt": "text/plain",
39
+ ".wasm": "application/wasm",
40
+ ".webp": "image/webp"
41
+ };
42
+ const DOM_NAMES = [
43
+ "window",
44
+ "self",
45
+ "HTMLCanvasElement",
46
+ "OffscreenCanvas",
47
+ "HTMLImageElement",
48
+ "Image",
49
+ "ImageData",
50
+ "ImageBitmap",
51
+ "createImageBitmap",
52
+ "FileReader",
53
+ "HTMLElement",
54
+ "Element",
55
+ "Node",
56
+ "devicePixelRatio",
57
+ "innerWidth",
58
+ "innerHeight",
59
+ "screen",
60
+ "requestAnimationFrame",
61
+ "cancelAnimationFrame",
62
+ "getComputedStyle",
63
+ "matchMedia",
64
+ "scrollTo",
65
+ "alert",
66
+ "location",
67
+ "document",
68
+ ...Object.keys(nodeWebGL).filter((name) => name.startsWith("WebGL"))
69
+ ];
70
+ let initializedWith;
71
+ /**
72
+ * The native EGL display is process-wide and node-webgl's `init()` is a no-op once it exists (the first
73
+ * context creates it lazily), so compare explicit options against the live display rather than only
74
+ * against what this module itself initialized.
75
+ */
76
+ function initialize({ api, backend }) {
77
+ if (!api && !backend) return;
78
+ if (initializedWith && initializedWith.api === api && initializedWith.backend === backend) return;
79
+ const display = nodeWebGL.getDisplayInfo();
80
+ if (display && (backend && backend !== "default" && backend !== display.backend || api && api !== "auto" && api !== display.api)) throw new Error(`node-webgl is already initialized with ${JSON.stringify({
81
+ api: display.api,
82
+ backend: display.backend
83
+ })}; cannot switch this Jest worker to ${JSON.stringify({
84
+ api,
85
+ backend
86
+ })}`);
87
+ nodeWebGL.init({
88
+ api,
89
+ backend
11
90
  });
12
- const before = new Set(Object.getOwnPropertyNames(globalThis));
13
- installDOM(dom);
14
- domNames = Object.getOwnPropertyNames(globalThis).filter((key) => !before.has(key));
15
- return domNames;
91
+ initializedWith = {
92
+ api,
93
+ backend
94
+ };
95
+ }
96
+ /** Capture a fresh node-webgl DOM while restoring every host descriptor after installation. */
97
+ function createDOM(options) {
98
+ const before = Object.getOwnPropertyDescriptors(globalThis);
99
+ for (const name of DOM_NAMES) Reflect.deleteProperty(globalThis, name);
100
+ try {
101
+ nodeWebGL.installDOM({
102
+ ...options,
103
+ fetch: false
104
+ });
105
+ const after = Object.getOwnPropertyDescriptors(globalThis);
106
+ return new Map(DOM_NAMES.flatMap((name) => after[name] ? [[name, after[name]]] : []));
107
+ } finally {
108
+ for (const name of Object.getOwnPropertyNames(globalThis)) if (!(name in before)) Reflect.deleteProperty(globalThis, name);
109
+ Object.defineProperties(globalThis, before);
110
+ }
111
+ }
112
+ function environmentConfig(config) {
113
+ return {
114
+ ...config,
115
+ projectConfig: {
116
+ ...config.projectConfig,
117
+ testEnvironmentOptions: Object.fromEntries(Object.entries(config.projectConfig.testEnvironmentOptions).filter(([name]) => !WEBGL_OPTION_NAMES.has(name)))
118
+ }
119
+ };
120
+ }
121
+ function localFetch(baseDir, nativeFetch) {
122
+ return async (input, init) => {
123
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
124
+ if (/^(https?|data|blob):/i.test(url)) return nativeFetch(input, init);
125
+ const path = url.startsWith("file:") ? fileURLToPath(url) : resolve(baseDir, url.replace(/[?#].*$/, ""));
126
+ try {
127
+ const bytes = await readFile(path);
128
+ return new Response(bytes, {
129
+ status: 200,
130
+ headers: { "content-type": MIME[extname(path).toLowerCase()] ?? "application/octet-stream" }
131
+ });
132
+ } catch {
133
+ return new Response(null, {
134
+ status: 404,
135
+ statusText: "Not Found"
136
+ });
137
+ }
138
+ };
16
139
  }
17
140
  var WebglEnvironment = class extends TestEnvironment {
18
- added;
141
+ added = [];
142
+ animationFrames = /* @__PURE__ */ new Map();
19
143
  constructor(config, context) {
20
- super(config, context);
21
- const nativeAdded = !Object.getOwnPropertyNames(this.global).includes("_native");
22
- if (nativeAdded) Object.defineProperty(this.global, "_native", {
23
- value: void 0,
24
- writable: true,
25
- configurable: true,
26
- enumerable: false
27
- });
28
144
  const options = config.projectConfig.testEnvironmentOptions;
29
- const names = ensureHostDOM(options);
145
+ super(environmentConfig(config), context);
146
+ const { api, backend, ...domOptions } = options;
147
+ initialize({
148
+ api,
149
+ backend
150
+ });
30
151
  const g = this.global;
31
- this.added = names.filter((key) => !(key in g));
32
- for (const key of this.added) g[key] = globalThis[key];
33
- if (nativeAdded) this.added.push("_native");
152
+ if (!Object.getOwnPropertyNames(g).includes("_native")) {
153
+ Object.defineProperty(g, "_native", {
154
+ value: void 0,
155
+ writable: true,
156
+ configurable: true,
157
+ enumerable: false
158
+ });
159
+ this.added.push("_native");
160
+ }
161
+ for (const [name, descriptor] of createDOM(domOptions)) {
162
+ if (!(name in g)) this.added.push(name);
163
+ Object.defineProperty(g, name, descriptor);
164
+ }
34
165
  g.window = g;
35
166
  g.self = g;
36
- for (const target of [g.window, g.document]) {
37
- target.addEventListener ??= () => {};
38
- target.removeEventListener ??= () => {};
39
- }
167
+ g.document.defaultView = g;
168
+ const events = new EventTarget();
169
+ g.addEventListener = events.addEventListener.bind(events);
170
+ g.removeEventListener = events.removeEventListener.bind(events);
171
+ g.dispatchEvent = events.dispatchEvent.bind(events);
172
+ this.added.push("addEventListener", "removeEventListener", "dispatchEvent");
173
+ const interval = domOptions.frameInterval ?? 16;
174
+ g.requestAnimationFrame = (callback) => {
175
+ const id = g.setTimeout(() => {
176
+ this.animationFrames.delete(id);
177
+ callback(g.performance.now());
178
+ }, interval);
179
+ this.animationFrames.set(id, g.clearTimeout);
180
+ return id;
181
+ };
182
+ g.cancelAnimationFrame = (id) => {
183
+ const clear = this.animationFrames.get(id);
184
+ this.animationFrames.delete(id);
185
+ (clear ?? g.clearTimeout)(id);
186
+ };
187
+ const nativeFetch = globalThis.fetch.bind(globalThis);
188
+ g.fetch = domOptions.fetch === false ? nativeFetch : localFetch(domOptions.baseDir ?? process.cwd(), nativeFetch);
40
189
  }
41
190
  async teardown() {
42
191
  const g = this.global;
192
+ for (const [id, clear] of this.animationFrames) clear(id);
193
+ this.animationFrames.clear();
43
194
  for (const key of this.added) delete g[key];
44
195
  await super.teardown();
45
196
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { init, installDOM, type InitOptions, type InstallDOMOptions } from '@onirenaud/node-webgl';\nimport { TestEnvironment } from 'jest-environment-node';\n\n/** Set under `testEnvironmentOptions` in your Jest config. */\nexport type WebglNodeOptions = InitOptions & InstallDOMOptions;\n\n// Typed from TestEnvironment's own constructor rather than importing `@jest/environment`\n// directly: that package is only a transitive dependency (of jest-environment-node), not\n// resolvable from this package's own node_modules under pnpm's strict layout.\ntype JestEnvironmentConfig = ConstructorParameters<typeof TestEnvironment>[0];\ntype EnvironmentContext = ConstructorParameters<typeof TestEnvironment>[1];\n\n// node-webgl's installDOM() writes to the HOST globalThis (not a target you pass in) and is\n// idempotent (it skips names already defined). So it can only usefully run once per process: on\n// the first WebglEnvironment constructed here, snapshot the host globals before/after the call and\n// remember which names it added. Every later environment (this test file or another one sharing\n// the worker) copies that same fixed list into its own sandbox global instead of calling\n// installDOM() again. This means only the FIRST test file's `testEnvironmentOptions` actually\n// affect the host install (backend/api selection, DOM option defaults); later test files'\n// options for those are ignored, matching how node-webgl itself behaves.\nlet domNames: readonly string[] | undefined;\n\nfunction ensureHostDOM(options: WebglNodeOptions): readonly string[] {\n if (domNames) return domNames;\n const { backend, api, ...dom } = options;\n if (backend || api) init({ backend, api });\n const before = new Set(Object.getOwnPropertyNames(globalThis));\n installDOM(dom);\n domNames = Object.getOwnPropertyNames(globalThis).filter((key) => !before.has(key));\n return domNames;\n}\n\nexport default class WebglEnvironment extends TestEnvironment {\n private readonly added: string[];\n\n constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {\n super(config, context);\n // @babylonjs/core defines a `_native` accessor on `self` at module load; on Jest's proxied\n // sandbox global that defineProperty violates a proxy invariant, so pre-seed the property to\n // satisfy Babylon's hasOwnProperty guard.\n // `Object.hasOwn`/`in` report false negatives here: jest-environment-node's sandbox global is\n // a Proxy over a vm context, and reads of freshly-added properties from outside the sandbox\n // (as this constructor runs) don't go through the fast path those use. getOwnPropertyNames is\n // unaffected, so use that instead.\n const nativeAdded = !Object.getOwnPropertyNames(this.global).includes('_native');\n if (nativeAdded) {\n Object.defineProperty(this.global, '_native', {\n value: undefined,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n }\n // Jest always populates `testEnvironmentOptions` (defaulting to `{}`) by the time a real\n // config reaches an environment; `super()` above already relies on that itself.\n const options = config.projectConfig.testEnvironmentOptions as WebglNodeOptions;\n const names = ensureHostDOM(options);\n const g = this.global as unknown as Record<string, unknown>;\n this.added = names.filter((key) => !(key in g));\n for (const key of this.added) g[key] = (globalThis as unknown as Record<string, unknown>)[key];\n if (nativeAdded) this.added.push('_native');\n g.window = g;\n g.self = g;\n // node-webgl's window/document have no event methods; engines like Babylon.js register\n // resize/blur listeners on them. installDOM() always installs both, so both are present here.\n for (const target of [g.window, g.document] as Record<string, unknown>[]) {\n target.addEventListener ??= () => {};\n target.removeEventListener ??= () => {};\n }\n }\n\n override async teardown(): Promise<void> {\n const g = this.global as unknown as Record<string, unknown>;\n for (const key of this.added) delete g[key];\n await super.teardown();\n }\n}\n"],"mappings":";;;AAoBA,IAAI;AAEJ,SAAS,cAAc,SAA8C;CACnE,IAAI,UAAU,OAAO;CACrB,MAAM,EAAE,SAAS,KAAK,GAAG,QAAQ;CACjC,IAAI,WAAW,KAAK,KAAK;EAAE;EAAS;CAAI,CAAC;CACzC,MAAM,SAAS,IAAI,IAAI,OAAO,oBAAoB,UAAU,CAAC;CAC7D,WAAW,GAAG;CACd,WAAW,OAAO,oBAAoB,UAAU,CAAC,CAAC,QAAQ,QAAQ,CAAC,OAAO,IAAI,GAAG,CAAC;CAClF,OAAO;AACT;AAEA,IAAqB,mBAArB,cAA8C,gBAAgB;CAC5D;CAEA,YAAY,QAA+B,SAA6B;EACtE,MAAM,QAAQ,OAAO;EAQrB,MAAM,cAAc,CAAC,OAAO,oBAAoB,KAAK,MAAM,CAAC,CAAC,SAAS,SAAS;EAC/E,IAAI,aACF,OAAO,eAAe,KAAK,QAAQ,WAAW;GAC5C,OAAO,KAAA;GACP,UAAU;GACV,cAAc;GACd,YAAY;EACd,CAAC;EAIH,MAAM,UAAU,OAAO,cAAc;EACrC,MAAM,QAAQ,cAAc,OAAO;EACnC,MAAM,IAAI,KAAK;EACf,KAAK,QAAQ,MAAM,QAAQ,QAAQ,EAAE,OAAO,EAAE;EAC9C,KAAK,MAAM,OAAO,KAAK,OAAO,EAAE,OAAQ,WAAkD;EAC1F,IAAI,aAAa,KAAK,MAAM,KAAK,SAAS;EAC1C,EAAE,SAAS;EACX,EAAE,OAAO;EAGT,KAAK,MAAM,UAAU,CAAC,EAAE,QAAQ,EAAE,QAAQ,GAAgC;GACxE,OAAO,2BAA2B,CAAC;GACnC,OAAO,8BAA8B,CAAC;EACxC;CACF;CAEA,MAAe,WAA0B;EACvC,MAAM,IAAI,KAAK;EACf,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,EAAE;EACvC,MAAM,MAAM,SAAS;CACvB;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["resolvePath"],"sources":["../src/index.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { extname, resolve as resolvePath } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport * as nodeWebGL from '@onirenaud/node-webgl';\nimport type { InitOptions, InstallDOMOptions } from '@onirenaud/node-webgl';\nimport { TestEnvironment } from 'jest-environment-node';\n\n/** Set under `testEnvironmentOptions` in your Jest config. */\nexport type WebglNodeOptions = InitOptions & InstallDOMOptions;\n\ntype JestEnvironmentConfig = ConstructorParameters<typeof TestEnvironment>[0];\ntype EnvironmentContext = ConstructorParameters<typeof TestEnvironment>[1];\ntype Sandbox = Record<string, unknown>;\n\nconst WEBGL_OPTION_NAMES = new Set([\n 'api',\n 'backend',\n 'baseDir',\n 'devicePixelRatio',\n 'fetch',\n 'frameInterval',\n 'innerHeight',\n 'innerWidth',\n]);\n\nconst MIME: Record<string, string> = {\n '.basis': 'application/octet-stream',\n '.bin': 'application/octet-stream',\n '.drc': 'application/octet-stream',\n '.exr': 'image/x-exr',\n '.fbx': 'application/octet-stream',\n '.gif': 'image/gif',\n '.glb': 'model/gltf-binary',\n '.gltf': 'model/gltf+json',\n '.hdr': 'image/vnd.radiance',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.ktx': 'image/ktx',\n '.ktx2': 'image/ktx2',\n '.mjs': 'text/javascript',\n '.mtl': 'text/plain',\n '.obj': 'text/plain',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n};\n\nconst DOM_NAMES = [\n 'window',\n 'self',\n 'HTMLCanvasElement',\n 'OffscreenCanvas',\n 'HTMLImageElement',\n 'Image',\n 'ImageData',\n 'ImageBitmap',\n 'createImageBitmap',\n 'FileReader',\n 'HTMLElement',\n 'Element',\n 'Node',\n 'devicePixelRatio',\n 'innerWidth',\n 'innerHeight',\n 'screen',\n 'requestAnimationFrame',\n 'cancelAnimationFrame',\n 'getComputedStyle',\n 'matchMedia',\n 'scrollTo',\n 'alert',\n 'location',\n 'document',\n ...Object.keys(nodeWebGL).filter((name) => name.startsWith('WebGL')),\n] as const;\n\nlet initializedWith: InitOptions | undefined;\n\n/**\n * The native EGL display is process-wide and node-webgl's `init()` is a no-op once it exists (the first\n * context creates it lazily), so compare explicit options against the live display rather than only\n * against what this module itself initialized.\n */\nfunction initialize({ api, backend }: InitOptions): void {\n if (!api && !backend) return;\n if (initializedWith && initializedWith.api === api && initializedWith.backend === backend) return;\n const display = nodeWebGL.getDisplayInfo();\n const mismatch =\n display &&\n ((backend && backend !== 'default' && backend !== display.backend) ||\n (api && api !== 'auto' && api !== display.api));\n if (mismatch) {\n throw new Error(\n `node-webgl is already initialized with ${JSON.stringify({ api: display.api, backend: display.backend })}; ` +\n `cannot switch this Jest worker to ${JSON.stringify({ api, backend })}`,\n );\n }\n nodeWebGL.init({ api, backend });\n initializedWith = { api, backend };\n}\n\n/** Capture a fresh node-webgl DOM while restoring every host descriptor after installation. */\nfunction createDOM(options: InstallDOMOptions): Map<string, PropertyDescriptor> {\n const before = Object.getOwnPropertyDescriptors(globalThis);\n for (const name of DOM_NAMES) Reflect.deleteProperty(globalThis, name);\n\n try {\n nodeWebGL.installDOM({ ...options, fetch: false });\n const after = Object.getOwnPropertyDescriptors(globalThis);\n return new Map(\n DOM_NAMES.flatMap((name): [string, PropertyDescriptor][] => (after[name] ? [[name, after[name]]] : [])),\n );\n } finally {\n for (const name of Object.getOwnPropertyNames(globalThis)) {\n if (!(name in before)) Reflect.deleteProperty(globalThis, name);\n }\n Object.defineProperties(globalThis, before);\n }\n}\n\nfunction environmentConfig(config: JestEnvironmentConfig): JestEnvironmentConfig {\n return {\n ...config,\n projectConfig: {\n ...config.projectConfig,\n testEnvironmentOptions: Object.fromEntries(\n Object.entries(config.projectConfig.testEnvironmentOptions).filter(([name]) => !WEBGL_OPTION_NAMES.has(name)),\n ),\n },\n };\n}\n\nfunction localFetch(baseDir: string, nativeFetch: typeof fetch): typeof fetch {\n return async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n if (/^(https?|data|blob):/i.test(url)) return nativeFetch(input, init);\n const path = url.startsWith('file:') ? fileURLToPath(url) : resolvePath(baseDir, url.replace(/[?#].*$/, ''));\n try {\n const bytes = await readFile(path);\n return new Response(bytes, {\n status: 200,\n headers: { 'content-type': MIME[extname(path).toLowerCase()] ?? 'application/octet-stream' },\n });\n } catch {\n return new Response(null, { status: 404, statusText: 'Not Found' });\n }\n };\n}\n\nexport default class WebglEnvironment extends TestEnvironment {\n private readonly added: string[] = [];\n private readonly animationFrames = new Map<ReturnType<typeof setTimeout>, typeof clearTimeout>();\n\n constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {\n const options = config.projectConfig.testEnvironmentOptions as WebglNodeOptions;\n super(environmentConfig(config), context);\n\n const { api, backend, ...domOptions } = options;\n initialize({ api, backend });\n\n const g = this.global as unknown as Sandbox;\n const nativeAdded = !Object.getOwnPropertyNames(g).includes('_native');\n if (nativeAdded) {\n Object.defineProperty(g, '_native', {\n value: undefined,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n this.added.push('_native');\n }\n\n for (const [name, descriptor] of createDOM(domOptions)) {\n if (!(name in g)) this.added.push(name);\n Object.defineProperty(g, name, descriptor);\n }\n\n g.window = g;\n g.self = g;\n (g.document as Record<string, unknown>).defaultView = g;\n\n const events = new EventTarget();\n g.addEventListener = events.addEventListener.bind(events);\n g.removeEventListener = events.removeEventListener.bind(events);\n g.dispatchEvent = events.dispatchEvent.bind(events);\n this.added.push('addEventListener', 'removeEventListener', 'dispatchEvent');\n\n const interval = domOptions.frameInterval ?? 16;\n g.requestAnimationFrame = (callback: (time: number) => void) => {\n const id = (g.setTimeout as typeof setTimeout)(() => {\n this.animationFrames.delete(id);\n callback((g.performance as { now(): number }).now());\n }, interval);\n this.animationFrames.set(id, g.clearTimeout as typeof clearTimeout);\n return id;\n };\n g.cancelAnimationFrame = (id: ReturnType<typeof setTimeout>) => {\n const clear = this.animationFrames.get(id);\n this.animationFrames.delete(id);\n (clear ?? (g.clearTimeout as typeof clearTimeout))(id);\n };\n\n const nativeFetch = globalThis.fetch.bind(globalThis);\n g.fetch = domOptions.fetch === false ? nativeFetch : localFetch(domOptions.baseDir ?? process.cwd(), nativeFetch);\n }\n\n override async teardown(): Promise<void> {\n const g = this.global as unknown as Sandbox;\n for (const [id, clear] of this.animationFrames) clear(id);\n this.animationFrames.clear();\n for (const key of this.added) delete g[key];\n await super.teard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gBAAgB,OAAO,EAAE;GAC9B,CAAC,SAAU,EAAE,aAAA,CAAsC,EAAE;EACvD;EAEA,MAAM,cAAc,WAAW,MAAM,KAAK,UAAU;EACpD,EAAE,QAAQ,WAAW,UAAU,QAAQ,cAAc,WAAW,WAAW,WAAW,QAAQ,IAAI,GAAG,WAAW;CAClH;CAEA,MAAe,WAA0B;EACvC,MAAM,IAAI,KAAK;EACf,KAAK,MAAM,CAAC,IAAI,UAAU,KAAK,iBAAiB,MAAM,EAAE;EACxD,KAAK,gBAAgB,MAAM;EAC3B,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,EAAE;EACvC,MAAM,MAAM,SAAS;CACvB;AACF"}
package/globals.d.ts CHANGED
@@ -48,6 +48,6 @@ declare global {
48
48
  var createImageBitmap: typeof nodeCreateImageBitmap;
49
49
  var WebGLRenderingContext: typeof NodeWebGLRenderingContext;
50
50
  var WebGL2RenderingContext: typeof NodeWebGL2RenderingContext;
51
- function requestAnimationFrame(callback: (time: number) => void): number;
52
- function cancelAnimationFrame(handle: number): void;
51
+ function requestAnimationFrame(callback: (time: number) => void): ReturnType<typeof setTimeout>;
52
+ function cancelAnimationFrame(handle: ReturnType<typeof setTimeout>): void;
53
53
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jest-environment-webgl-node",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Jest environment that provides real headless WebGL 1/2 (ANGLE via @onirenaud/node-webgl) in Node",
5
5
  "keywords": [
6
6
  "headless",