@ctrl/dom-jest-environment 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Scott Cooper
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,338 @@
1
+ @ctrl/dom
2
+ Copyright (c) 2026 Scott Cooper
3
+ Licensed under the MIT License (see LICENSE).
4
+
5
+ @ctrl/dom includes code ported from the third-party projects listed below. Every source file
6
+ with ported code names the upstream file it came from in a comment ("Port of ...", "Ported
7
+ from ..."), and those files have been modified from the originals. Each project's copyright
8
+ notice is listed with its entry; the license texts are at the end of this file.
9
+
10
+ ==================================================================================================
11
+ Included in the published packages
12
+ ==================================================================================================
13
+
14
+ @testing-library/dom 10.4.2 (MIT)
15
+ Copyright (c) 2017 Kent C. Dodds
16
+ https://github.com/testing-library/dom-testing-library
17
+ In @ctrl/dom/testing-library (source and public types) and parts of @ctrl/dom/aria
18
+
19
+ @testing-library/react 16.3.3 (MIT)
20
+ Copyright (c) 2017-Present Kent C. Dodds
21
+ https://github.com/testing-library/react-testing-library
22
+ In @ctrl/dom/react (source and public types)
23
+
24
+ @testing-library/user-event 14.6.8 (MIT)
25
+ Copyright (c) 2020 Giorgio Polvara
26
+ https://github.com/testing-library/user-event
27
+ In @ctrl/dom/user-event
28
+
29
+ @testing-library/jest-dom 7.0.1 (MIT)
30
+ Copyright (c) 2017 Kent C. Dodds
31
+ https://github.com/testing-library/jest-dom
32
+ In @ctrl/dom/jest-dom (source and public types)
33
+
34
+ dom-accessibility-api 0.5.16 / 0.6.3 (MIT)
35
+ Copyright (c) 2020 Sebastian Silbermann
36
+ https://github.com/eps1lon/dom-accessibility-api
37
+ In @ctrl/dom/aria (accessible name and description computation)
38
+
39
+ aria-query 5.3.0 / 5.3.2 (Apache-2.0)
40
+ Copyright 2020 A11yance
41
+ https://github.com/A11yance/aria-query
42
+ In @ctrl/dom/aria (role data) and @ctrl/dom/jest-dom (element roles)
43
+
44
+ @types/aria-query 5.0.4 (MIT)
45
+ Copyright (c) Microsoft Corporation
46
+ https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/aria-query
47
+ In @ctrl/dom/testing-library's public types (ARIA role names)
48
+
49
+ Playwright 1.56 (Apache-2.0)
50
+ Copyright (c) Microsoft Corporation
51
+ https://github.com/microsoft/playwright
52
+ In @ctrl/dom/testing-library (aria snapshot templates and matching, toMatchAriaSnapshot)
53
+ Playwright's NOTICE file:
54
+
55
+ Playwright
56
+ Copyright (c) Microsoft Corporation
57
+
58
+ This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer),
59
+ available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE).
60
+
61
+ jsdom 30.1.3 (MIT)
62
+ Copyright (c) 2010 Elijah Insua
63
+ https://github.com/jsdom/jsdom
64
+ In @ctrl/dom (date, time and number microsyntaxes, from lib/jsdom/living/helpers/)
65
+
66
+ lz-string 1.5.0 (MIT)
67
+ Copyright (c) 2013 pieroxy
68
+ https://github.com/pieroxy/lz-string
69
+ In @ctrl/dom/testing-library (compressToEncodedURIComponent)
70
+
71
+ picocolors 1.1.1 (ISC)
72
+ Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
73
+ https://github.com/alexeyraspopov/picocolors
74
+ In @ctrl/dom/jest-dom (terminal color detection)
75
+
76
+ HTML Standard (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/)
77
+ © WHATWG (Apple, Google, Mozilla, Microsoft)
78
+ https://html.spec.whatwg.org/
79
+ In @ctrl/dom: the named character references table, converted from
80
+ https://html.spec.whatwg.org/entities.json, and user-agent style sheet rules adapted from
81
+ https://html.spec.whatwg.org/#rendering
82
+
83
+ Source comments throughout quote the specifications they implement (WHATWG, W3C, CSSWG and
84
+ others), with a link to each section. Quoted text is © its authors; WHATWG specifications are
85
+ licensed under CC BY 4.0, W3C specifications under the W3C Software and Document License.
86
+
87
+ ==================================================================================================
88
+ Tests and test data (in the repository only, not in the published packages)
89
+ ==================================================================================================
90
+
91
+ web-platform-tests (BSD-3-Clause)
92
+ Copyright © web-platform-tests contributors
93
+ https://github.com/web-platform-tests/wpt
94
+ Ported dom, html, selectors, css and accname tests (packages/*/test/wpt)
95
+
96
+ html5lib-tests (MIT)
97
+ Copyright (c) 2006-2013 James Graham, Geoffrey Sneddon, and other contributors
98
+ https://github.com/html5lib/html5lib-tests
99
+ Tokenizer and tree construction suites (packages/dom/test/parser/fixtures/html5lib)
100
+
101
+ css-tokenizer-tests 1.4.0 (MIT, as its npm package @rmenke/css-tokenizer-tests declares)
102
+ Copyright (c) Romain Menke
103
+ https://github.com/romainmenke/css-tokenizer-tests
104
+ packages/dom/test/css/fixtures/css-tokenizer-tests.json
105
+
106
+ The test suites of @testing-library/dom, /react, /user-event and /jest-dom, dom-accessibility-api
107
+ and aria-query (copyrights and licenses as above) are ported under packages/*/test/upstream.
108
+
109
+ ==================================================================================================
110
+ License texts
111
+ ==================================================================================================
112
+
113
+ MIT License (the MIT entries above, each under its own copyright notice)
114
+ ------------------------------------------------------------------------
115
+
116
+ Permission is hereby granted, free of charge, to any person obtaining a copy
117
+ of this software and associated documentation files (the "Software"), to deal
118
+ in the Software without restriction, including without limitation the rights
119
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
120
+ copies of the Software, and to permit persons to whom the Software is
121
+ furnished to do so, subject to the following conditions:
122
+
123
+ The above copyright notice and this permission notice shall be included in all
124
+ copies or substantial portions of the Software.
125
+
126
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
127
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
128
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
129
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
130
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
131
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
132
+ SOFTWARE.
133
+
134
+ ISC License (picocolors)
135
+ ------------------------
136
+
137
+ Permission to use, copy, modify, and/or distribute this software for any
138
+ purpose with or without fee is hereby granted, provided that the above
139
+ copyright notice and this permission notice appear in all copies.
140
+
141
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
142
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
143
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
144
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
145
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
146
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
147
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
148
+
149
+ BSD 3-Clause License (web-platform-tests)
150
+ -----------------------------------------
151
+
152
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
153
+
154
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
155
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
156
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
157
+
158
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
159
+
160
+ Apache License 2.0 (aria-query, Playwright)
161
+ -------------------------------------------
162
+
163
+ Apache License
164
+ Version 2.0, January 2004
165
+ http://www.apache.org/licenses/
166
+
167
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
168
+
169
+ 1. Definitions.
170
+
171
+ "License" shall mean the terms and conditions for use, reproduction,
172
+ and distribution as defined by Sections 1 through 9 of this document.
173
+
174
+ "Licensor" shall mean the copyright owner or entity authorized by
175
+ the copyright owner that is granting the License.
176
+
177
+ "Legal Entity" shall mean the union of the acting entity and all
178
+ other entities that control, are controlled by, or are under common
179
+ control with that entity. For the purposes of this definition,
180
+ "control" means (i) the power, direct or indirect, to cause the
181
+ direction or management of such entity, whether by contract or
182
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
183
+ outstanding shares, or (iii) beneficial ownership of such entity.
184
+
185
+ "You" (or "Your") shall mean an individual or Legal Entity
186
+ exercising permissions granted by this License.
187
+
188
+ "Source" form shall mean the preferred form for making modifications,
189
+ including but not limited to software source code, documentation
190
+ source, and configuration files.
191
+
192
+ "Object" form shall mean any form resulting from mechanical
193
+ transformation or translation of a Source form, including but
194
+ not limited to compiled object code, generated documentation,
195
+ and conversions to other media types.
196
+
197
+ "Work" shall mean the work of authorship, whether in Source or
198
+ Object form, made available under the License, as indicated by a
199
+ copyright notice that is included in or attached to the work
200
+ (an example is provided in the Appendix below).
201
+
202
+ "Derivative Works" shall mean any work, whether in Source or Object
203
+ form, that is based on (or derived from) the Work and for which the
204
+ editorial revisions, annotations, elaborations, or other modifications
205
+ represent, as a whole, an original work of authorship. For the purposes
206
+ of this License, Derivative Works shall not include works that remain
207
+ separable from, or merely link (or bind by name) to the interfaces of,
208
+ the Work and Derivative Works thereof.
209
+
210
+ "Contribution" shall mean any work of authorship, including
211
+ the original version of the Work and any modifications or additions
212
+ to that Work or Derivative Works thereof, that is intentionally
213
+ submitted to Licensor for inclusion in the Work by the copyright owner
214
+ or by an individual or Legal Entity authorized to submit on behalf of
215
+ the copyright owner. For the purposes of this definition, "submitted"
216
+ means any form of electronic, verbal, or written communication sent
217
+ to the Licensor or its representatives, including but not limited to
218
+ communication on electronic mailing lists, source code control systems,
219
+ and issue tracking systems that are managed by, or on behalf of, the
220
+ Licensor for the purpose of discussing and improving the Work, but
221
+ excluding communication that is conspicuously marked or otherwise
222
+ designated in writing by the copyright owner as "Not a Contribution."
223
+
224
+ "Contributor" shall mean Licensor and any individual or Legal Entity
225
+ on behalf of whom a Contribution has been received by Licensor and
226
+ subsequently incorporated within the Work.
227
+
228
+ 2. Grant of Copyright License. Subject to the terms and conditions of
229
+ this License, each Contributor hereby grants to You a perpetual,
230
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
231
+ copyright license to reproduce, prepare Derivative Works of,
232
+ publicly display, publicly perform, sublicense, and distribute the
233
+ Work and such Derivative Works in Source or Object form.
234
+
235
+ 3. Grant of Patent License. Subject to the terms and conditions of
236
+ this License, each Contributor hereby grants to You a perpetual,
237
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
238
+ (except as stated in this section) patent license to make, have made,
239
+ use, offer to sell, sell, import, and otherwise transfer the Work,
240
+ where such license applies only to those patent claims licensable
241
+ by such Contributor that are necessarily infringed by their
242
+ Contribution(s) alone or by combination of their Contribution(s)
243
+ with the Work to which such Contribution(s) was submitted. If You
244
+ institute patent litigation against any entity (including a
245
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
246
+ or a Contribution incorporated within the Work constitutes direct
247
+ or contributory patent infringement, then any patent licenses
248
+ granted to You under this License for that Work shall terminate
249
+ as of the date such litigation is filed.
250
+
251
+ 4. Redistribution. You may reproduce and distribute copies of the
252
+ Work or Derivative Works thereof in any medium, with or without
253
+ modifications, and in Source or Object form, provided that You
254
+ meet the following conditions:
255
+
256
+ (a) You must give any other recipients of the Work or
257
+ Derivative Works a copy of this License; and
258
+
259
+ (b) You must cause any modified files to carry prominent notices
260
+ stating that You changed the files; and
261
+
262
+ (c) You must retain, in the Source form of any Derivative Works
263
+ that You distribute, all copyright, patent, trademark, and
264
+ attribution notices from the Source form of the Work,
265
+ excluding those notices that do not pertain to any part of
266
+ the Derivative Works; and
267
+
268
+ (d) If the Work includes a "NOTICE" text file as part of its
269
+ distribution, then any Derivative Works that You distribute must
270
+ include a readable copy of the attribution notices contained
271
+ within such NOTICE file, excluding those notices that do not
272
+ pertain to any part of the Derivative Works, in at least one
273
+ of the following places: within a NOTICE text file distributed
274
+ as part of the Derivative Works; within the Source form or
275
+ documentation, if provided along with the Derivative Works; or,
276
+ within a display generated by the Derivative Works, if and
277
+ wherever such third-party notices normally appear. The contents
278
+ of the NOTICE file are for informational purposes only and
279
+ do not modify the License. You may add Your own attribution
280
+ notices within Derivative Works that You distribute, alongside
281
+ or as an addendum to the NOTICE text from the Work, provided
282
+ that such additional attribution notices cannot be construed
283
+ as modifying the License.
284
+
285
+ You may add Your own copyright statement to Your modifications and
286
+ may provide additional or different license terms and conditions
287
+ for use, reproduction, or distribution of Your modifications, or
288
+ for any such Derivative Works as a whole, provided Your use,
289
+ reproduction, and distribution of the Work otherwise complies with
290
+ the conditions stated in this License.
291
+
292
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
293
+ any Contribution intentionally submitted for inclusion in the Work
294
+ by You to the Licensor shall be under the terms and conditions of
295
+ this License, without any additional terms or conditions.
296
+ Notwithstanding the above, nothing herein shall supersede or modify
297
+ the terms of any separate license agreement you may have executed
298
+ with Licensor regarding such Contributions.
299
+
300
+ 6. Trademarks. This License does not grant permission to use the trade
301
+ names, trademarks, service marks, or product names of the Licensor,
302
+ except as required for reasonable and customary use in describing the
303
+ origin of the Work and reproducing the content of the NOTICE file.
304
+
305
+ 7. Disclaimer of Warranty. Unless required by applicable law or
306
+ agreed to in writing, Licensor provides the Work (and each
307
+ Contributor provides its Contributions) on an "AS IS" BASIS,
308
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
309
+ implied, including, without limitation, any warranties or conditions
310
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
311
+ PARTICULAR PURPOSE. You are solely responsible for determining the
312
+ appropriateness of using or redistributing the Work and assume any
313
+ risks associated with Your exercise of permissions under this License.
314
+
315
+ 8. Limitation of Liability. In no event and under no legal theory,
316
+ whether in tort (including negligence), contract, or otherwise,
317
+ unless required by applicable law (such as deliberate and grossly
318
+ negligent acts) or agreed to in writing, shall any Contributor be
319
+ liable to You for damages, including any direct, indirect, special,
320
+ incidental, or consequential damages of any character arising as a
321
+ result of this License or out of the use or inability to use the
322
+ Work (including but not limited to damages for loss of goodwill,
323
+ work stoppage, computer failure or malfunction, or any and all
324
+ other commercial damages or losses), even if such Contributor
325
+ has been advised of the possibility of such damages.
326
+
327
+ 9. Accepting Warranty or Additional Liability. While redistributing
328
+ the Work or Derivative Works thereof, You may choose to offer,
329
+ and charge a fee for, acceptance of support, warranty, indemnity,
330
+ or other liability obligations and/or rights consistent with this
331
+ License. However, in accepting such obligations, You may act only
332
+ on Your own behalf and on Your sole responsibility, not on behalf
333
+ of any other Contributor, and only if You agree to indemnify,
334
+ defend, and hold each Contributor harmless for any liability
335
+ incurred by, or claims asserted against, such Contributor by reason
336
+ of your accepting any such warranty or additional liability.
337
+
338
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # @ctrl/dom-jest-environment
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Jest environment for [@ctrl/dom](https://www.npmjs.com/package/@ctrl/dom), the DOM for testing
4
+ React components: a faster, leaner drop-in for `jest-environment-jsdom`.
5
+
6
+ ```sh
7
+ pnpm add -D @ctrl/dom @ctrl/dom-jest-environment
8
+ ```
9
+
10
+ The whole stack, with your `@testing-library/*` imports routed to @ctrl/dom:
11
+
12
+ ```js
13
+ // jest.config.js
14
+ module.exports = {
15
+ preset: "@ctrl/dom",
16
+ setupFilesAfterEnv: ["@ctrl/dom/jest-dom"], // instead of "@testing-library/jest-dom"
17
+ };
18
+ ```
19
+
20
+ The DOM only, with stock Testing Library:
21
+
22
+ ```js
23
+ module.exports = { testEnvironment: "@ctrl/dom-jest-environment" };
24
+ ```
25
+
26
+ Per file: `/** @jest-environment @ctrl/dom-jest-environment */`. Options
27
+ (`testEnvironmentOptions`) and the differences from jsdom are documented in
28
+ [@ctrl/dom's README](https://www.npmjs.com/package/@ctrl/dom). Requires Jest 30+ and Node 26+.
29
+ Test code that imports `@ctrl/dom` (or its subpaths) gets the environment's own instance.
30
+
31
+ ## License
32
+
33
+ MIT. Third-party notices are in the package's `NOTICE` file.
package/dist/index.js ADDED
@@ -0,0 +1,276 @@
1
+ import { constants, createContext } from "node:vm";
2
+ import { LegacyFakeTimers, ModernFakeTimers } from "@jest/fake-timers";
3
+ import { ModuleMocker } from "jest-mock";
4
+ import { installCommonGlobals } from "jest-util";
5
+ import * as dom from "@ctrl/dom";
6
+ import * as internal from "@ctrl/dom/internal";
7
+
8
+ // src/failure-snapshot.ts
9
+ /** The values of CTRL_DOM_DEBUG that turn agent mode on (agent-debug.ts, envDebugFormat). */
10
+ function debugEnabled() {
11
+ const value = process.env.CTRL_DOM_DEBUG?.trim().toLowerCase();
12
+ return value === "aria" || value === "compact" || value === "html";
13
+ }
14
+ /** A `handleTestEvent` for the environment, or undefined when CTRL_DOM_DEBUG is off. */
15
+ function failureSnapshotHandler(getDocument) {
16
+ if (!debugEnabled()) return void 0;
17
+ let agent = null;
18
+ return async (event) => {
19
+ if (event.name !== "test_start" && event.name !== "test_fn_failure") return;
20
+ agent ??= await import("@ctrl/dom/testing-library/agent");
21
+ const document = getDocument();
22
+ if (document == null) return;
23
+ if (event.name === "test_start") {
24
+ agent.resetFailureSnapshot(document);
25
+ return;
26
+ }
27
+ const error = event.error;
28
+ const message = error !== null && typeof error === "object" && typeof error.message === "string" ? error.message : "";
29
+ const snapshot = agent.captureFailureSnapshot(document);
30
+ if (snapshot !== null) agent.appendToErrorMessage(error, agent.formatFailureSnapshot(snapshot, message));
31
+ };
32
+ }
33
+
34
+ // src/index.ts
35
+ /** The vm-global key the bridges and shims read. */
36
+ const CTRL_DOM_MODULES = Symbol.for("ctrl-dom.dom.modules");
37
+ const JSDOM_ABSENT_GLOBALS = /* @__PURE__ */ new Set([
38
+ "fetch",
39
+ "Request",
40
+ "Response"
41
+ ]);
42
+ const NODE_GLOBAL_DENY = /* @__PURE__ */ new Set([
43
+ "GLOBAL",
44
+ "root",
45
+ "global",
46
+ "globalThis",
47
+ "Buffer",
48
+ "ArrayBuffer",
49
+ "Uint8Array",
50
+ "jest-symbol-do-not-touch",
51
+ "localStorage",
52
+ "sessionStorage"
53
+ ]);
54
+ const LAZY_NODE_GLOBALS = /* @__PURE__ */ new Map([
55
+ ["fetch", true],
56
+ ["Request", false],
57
+ ["Response", false],
58
+ ["Headers", false],
59
+ ["FormData", false],
60
+ ["WebSocket", false],
61
+ ["EventSource", false],
62
+ ["MessageEvent", false],
63
+ ["CloseEvent", false]
64
+ ]);
65
+ let nodeGlobals = null;
66
+ /** [name, descriptor] for Node's globals (descriptor null: lazy, see LAZY_NODE_GLOBALS). */
67
+ function nodeGlobalDescriptors() {
68
+ return nodeGlobals ??= Object.getOwnPropertyNames(globalThis).filter((name) => !NODE_GLOBAL_DENY.has(name)).map((name) => [name, LAZY_NODE_GLOBALS.has(name) ? null : Object.getOwnPropertyDescriptor(globalThis, name)]);
69
+ }
70
+ /**
71
+ * Copy Node's globals onto the test global the way jest-environment-node does: configurable ones
72
+ * as getters that read the outer value on first use and replace themselves with a data property;
73
+ * names the new realm already defines (Object, Array, ...) keep the realm's own.
74
+ */
75
+ function installNodeGlobals(global, skip) {
76
+ const realmOwn = new Set(Object.getOwnPropertyNames(global));
77
+ const host = globalThis;
78
+ for (const [name, descriptor] of nodeGlobalDescriptors()) {
79
+ if (realmOwn.has(name) || skip.has(name)) continue;
80
+ const enumerable = descriptor === null ? LAZY_NODE_GLOBALS.get(name) : descriptor.enumerable;
81
+ if (descriptor === null || descriptor.configurable) {
82
+ const settle = (value) => Object.defineProperty(global, name, {
83
+ value,
84
+ writable: true,
85
+ enumerable,
86
+ configurable: true
87
+ });
88
+ Object.defineProperty(global, name, {
89
+ get() {
90
+ const value = host[name];
91
+ settle(value);
92
+ return value;
93
+ },
94
+ set: settle,
95
+ enumerable,
96
+ configurable: true
97
+ });
98
+ } else Object.defineProperty(global, name, descriptor);
99
+ }
100
+ global.global = global;
101
+ global.Buffer = Buffer;
102
+ global.ArrayBuffer = ArrayBuffer;
103
+ global.Uint8Array = Uint8Array;
104
+ }
105
+ /** Same default URL as jest-environment-jsdom. */
106
+ const DEFAULT_URL = "http://localhost/";
107
+ /**
108
+ * Exceptions nobody handled (listener exceptions, reportError(), React's uncaught errors) are
109
+ * re-emitted on the worker process, which jest-circus turns into a test failure — what
110
+ * jest-environment-jsdom does with its window "error" listener.
111
+ * https://html.spec.whatwg.org/#report-an-exception
112
+ */
113
+ function reportToHost(error) {
114
+ process.emit("uncaughtException", error, "uncaughtException");
115
+ }
116
+ /**
117
+ * jsdom's "Not implemented" diagnostics (navigation, window.alert, form submission, ...; only
118
+ * under the jsdom profiles, @ctrl/dom window/not-implemented.ts), forwarded to the test file's
119
+ * console as jest-environment-jsdom does: with jsdom 26 (`sendTo` omitting jsdom errors, then
120
+ * its "jsdomError" listener) once, as the Error; with jsdom 27+ (`forwardTo`, then the same
121
+ * listener) as `error.stack`, then as the Error.
122
+ * https://github.com/jestjs/jest/blob/v30.4.1/packages/jest-environment-jsdom-abstract/src/index.ts
123
+ */
124
+ function forwardNotImplemented(global) {
125
+ return (error, compat) => {
126
+ const console = global.console;
127
+ if (compat !== "jsdom-26") console.error(error.stack, error.detail);
128
+ console.error(error);
129
+ };
130
+ }
131
+ const ERROR_CONSTRUCTORS = [
132
+ "Error",
133
+ "TypeError",
134
+ "RangeError",
135
+ "SyntaxError",
136
+ "ReferenceError",
137
+ "EvalError",
138
+ "URIError"
139
+ ];
140
+ /**
141
+ * Our DOM runs in the worker's realm while test code runs in the vm context, so a TypeError
142
+ * thrown by @ctrl/dom is not `instanceof` the test realm's TypeError (`expect(fn).toThrow(TypeError)`
143
+ * would fail). Give the context's error constructors a Symbol.hasInstance that also accepts the
144
+ * outer realm's instances; errors created in the context keep working as before.
145
+ */
146
+ function bridgeErrorRealms(global) {
147
+ for (const name of ERROR_CONSTRUCTORS) {
148
+ const inner = global[name];
149
+ const outer = globalThis[name];
150
+ if (typeof inner !== "function" || inner === outer) continue;
151
+ Object.defineProperty(inner, Symbol.hasInstance, {
152
+ value: (value) => Function.prototype[Symbol.hasInstance].call(inner, value) || value instanceof outer,
153
+ configurable: true
154
+ });
155
+ }
156
+ }
157
+ function createDom(window) {
158
+ return {
159
+ window,
160
+ reconfigure(settings) {
161
+ if (settings.windowTop !== void 0) throw new TypeError("@ctrl/dom-jest-environment: dom.reconfigure() does not support windowTop");
162
+ if (settings.url === void 0) return;
163
+ const url = URL.parse(String(settings.url));
164
+ if (url === null) throw new TypeError(`Could not parse "${settings.url}" as a URL`);
165
+ window._setURL(url);
166
+ }
167
+ };
168
+ }
169
+ var CtrlDomEnvironment = class {
170
+ context;
171
+ global;
172
+ fakeTimers;
173
+ fakeTimersModern;
174
+ moduleMocker;
175
+ customExportConditions;
176
+ ctrlDomWindow;
177
+ /** jest-environment-jsdom's `dom`, reduced to what suites use (see CtrlDomDom). */
178
+ dom;
179
+ /** The file's timers (see CtrlDomTestEnvironmentOptions.timeSkip). */
180
+ clock;
181
+ /** Stops adding the page and the clock to @ctrl/sentry-tests' failure reports. */
182
+ #unsubscribeFailures = null;
183
+ constructor(config, _environmentContext) {
184
+ const { projectConfig } = config;
185
+ const { customExportConditions, nodeFetch, timeSkip, ...windowOptions } = projectConfig.testEnvironmentOptions ?? {};
186
+ this.customExportConditions = customExportConditions ?? ["browser"];
187
+ const context = createContext(constants.DONT_CONTEXTIFY);
188
+ this.context = context;
189
+ const global = context;
190
+ this.global = global;
191
+ installNodeGlobals(global, nodeFetch === true ? /* @__PURE__ */ new Set() : JSDOM_ABSENT_GLOBALS);
192
+ installCommonGlobals(this.global, projectConfig.globals);
193
+ const realmSymbol = global.Symbol;
194
+ if (!("asyncDispose" in realmSymbol)) {
195
+ Object.defineProperty(realmSymbol, "asyncDispose", { value: Symbol.for("nodejs.asyncDispose") });
196
+ Object.defineProperty(realmSymbol, "dispose", { value: Symbol.for("nodejs.dispose") });
197
+ }
198
+ global.Error.stackTraceLimit = 100;
199
+ const window = dom.createWindow({
200
+ ...windowOptions,
201
+ compat: windowOptions.compat ?? "jsdom-26",
202
+ url: windowOptions.url ?? DEFAULT_URL
203
+ });
204
+ this.ctrlDomWindow = window;
205
+ this.dom = createDom(window);
206
+ internal.captureInterfaceBaseline();
207
+ dom.installGlobals(window, global);
208
+ Object.defineProperty(global, CTRL_DOM_MODULES, {
209
+ value: {
210
+ dom,
211
+ internal
212
+ },
213
+ configurable: true,
214
+ enumerable: false,
215
+ writable: false
216
+ });
217
+ bridgeErrorRealms(global);
218
+ const envSkip = process.env.CTRL_DOM_TIME_SKIP;
219
+ const skip = envSkip === "1" ? true : envSkip === "0" ? false : timeSkip !== false;
220
+ this.clock = internal.installClock(new internal.VirtualClock({ skip }), global).clock;
221
+ this.moduleMocker = new ModuleMocker(this.global);
222
+ this.fakeTimers = new LegacyFakeTimers({
223
+ config: projectConfig,
224
+ global: this.global,
225
+ moduleMocker: this.moduleMocker,
226
+ timerConfig: {
227
+ idToRef: (id) => id,
228
+ refToId: (ref) => ref
229
+ }
230
+ });
231
+ this.fakeTimersModern = new ModernFakeTimers({
232
+ config: projectConfig,
233
+ global: this.global
234
+ });
235
+ internal.guardInterfaceDefinitions(global);
236
+ internal.setUncaughtExceptionHandler(reportToHost);
237
+ internal.setNotImplementedHandler(forwardNotImplemented(global));
238
+ const onTestEvent = failureSnapshotHandler(() => this.ctrlDomWindow?.document);
239
+ if (onTestEvent !== void 0) this.handleTestEvent = onTestEvent;
240
+ this.#unsubscribeFailures = internal.subscribeTestFailures(() => this.ctrlDomWindow?.document);
241
+ }
242
+ async setup() {}
243
+ exportConditions() {
244
+ return this.customExportConditions;
245
+ }
246
+ getVmContext() {
247
+ return this.context;
248
+ }
249
+ /**
250
+ * Closes the window (cancelling its timers, frames, idle callbacks and tasks) and undoes the file's
251
+ * patches to the shared interface prototypes. The globals stay installed, like under
252
+ * jest-environment-jsdom where the global *is* the window: work a test file left behind (React's
253
+ * scheduler runs on Node's setImmediate) can still read `window`/`document` instead of
254
+ * crashing the worker with a ReferenceError. The vm context is discarded with the file.
255
+ */
256
+ async teardown() {
257
+ this.#unsubscribeFailures?.();
258
+ this.#unsubscribeFailures = null;
259
+ internal.setUncaughtExceptionHandler(null);
260
+ internal.setNotImplementedHandler(null);
261
+ this.fakeTimers?.dispose();
262
+ this.fakeTimersModern?.dispose();
263
+ this.ctrlDomWindow?.close();
264
+ this.ctrlDomWindow = null;
265
+ this.clock?.dispose();
266
+ this.clock = null;
267
+ this.dom = null;
268
+ internal.restoreInterfaces();
269
+ this.context = null;
270
+ this.fakeTimers = null;
271
+ this.fakeTimersModern = null;
272
+ }
273
+ };
274
+ const TestEnvironment = CtrlDomEnvironment;
275
+
276
+ export { CTRL_DOM_MODULES, TestEnvironment, CtrlDomEnvironment as default };
@@ -0,0 +1,3 @@
1
+ import type { Circus } from "@jest/types";
2
+ /** A `handleTestEvent` for the environment, or undefined when CTRL_DOM_DEBUG is off. */
3
+ export declare function failureSnapshotHandler(getDocument: () => unknown): ((event: Circus.Event) => Promise<void> | void) | undefined;
@@ -0,0 +1,77 @@
1
+ import { type Context } from "node:vm";
2
+ import type { EnvironmentContext, JestEnvironment, JestEnvironmentConfig } from "@jest/environment";
3
+ import { LegacyFakeTimers, ModernFakeTimers } from "@jest/fake-timers";
4
+ import type { Circus, Global } from "@jest/types";
5
+ import { ModuleMocker } from "jest-mock";
6
+ import * as internal from "@ctrl/dom/internal";
7
+ import type { CompatProfile, Window, WindowOptions } from "@ctrl/dom";
8
+ /** The vm-global key the bridges and shims read. */
9
+ export declare const CTRL_DOM_MODULES: unique symbol;
10
+ export interface CtrlDomTestEnvironmentOptions extends Omit<WindowOptions, "shareStorageWith"> {
11
+ customExportConditions?: string[];
12
+ /**
13
+ * Keep Node's `fetch`, `Request` and `Response` on the test global. Off by default:
14
+ * jest-environment-jsdom has none of them, and fetch mocks (jest-fetch-mock) pick a different
15
+ * implementation when they exist (docs/deviations.md).
16
+ */
17
+ nodeFetch?: boolean;
18
+ /**
19
+ * Skip idle time (default true): timers live on a virtual clock, and whenever the event loop
20
+ * has nothing to do but wait for one (no pending immediates, no I/O), the clock jumps to it,
21
+ * with Date and performance.now() advancing by the same amount. findBy/waitFor, user-event
22
+ * delays, debounces and timeouts stop costing wall time; ordering and app-visible time are
23
+ * unchanged. `false` keeps real-time timers (waitFor polls in real time). The CTRL_DOM_TIME_SKIP
24
+ * environment variable ("0"/"1"; also CTRL_DOM_TIME_SKIP) overrides it. See
25
+ * packages/dom/src/window/clock.ts.
26
+ */
27
+ timeSkip?: boolean;
28
+ /**
29
+ * APIs beyond jsdom's (@ctrl/dom window/compat.ts): "jsdom-26" (default: jest-environment-jsdom
30
+ * 30 ships jsdom 26, so no PointerEvent), "jsdom-30" (for suites written for an environment built
31
+ * on jsdom >= 27, which has PointerEvent) or "modern" (everything, including matchMedia,
32
+ * ResizeObserver and the `inert` IDL attribute).
33
+ */
34
+ compat?: CompatProfile;
35
+ }
36
+ /**
37
+ * The subset of jsdom's `JSDOM` object jest-environment-jsdom exposes as `environment.dom`
38
+ * that suites actually use: custom environments and @sentry/jest-environment (which copies it to
39
+ * `global.jsdom`) call `reconfigure({ url })` to change the URL without navigating.
40
+ */
41
+ export interface CtrlDomDom {
42
+ readonly window: Window;
43
+ /** https://github.com/jsdom/jsdom#reconfiguring-the-jsdom-with-reconfiguresettings */
44
+ reconfigure(settings: {
45
+ url?: string;
46
+ windowTop?: unknown;
47
+ }): void;
48
+ }
49
+ export default class CtrlDomEnvironment implements JestEnvironment<number> {
50
+ #private;
51
+ context: Context | null;
52
+ global: Global.Global;
53
+ fakeTimers: LegacyFakeTimers<number> | null;
54
+ fakeTimersModern: ModernFakeTimers | null;
55
+ moduleMocker: ModuleMocker | null;
56
+ customExportConditions: string[];
57
+ ctrlDomWindow: Window | null;
58
+ /** jest-environment-jsdom's `dom`, reduced to what suites use (see CtrlDomDom). */
59
+ dom: CtrlDomDom | null;
60
+ /** The file's timers (see CtrlDomTestEnvironmentOptions.timeSkip). */
61
+ clock: InstanceType<typeof internal.VirtualClock> | null;
62
+ /** Only with CTRL_DOM_DEBUG set: failure snapshots (./failure-snapshot.ts). */
63
+ handleTestEvent?: (event: Circus.Event, state: Circus.State) => Promise<void> | void;
64
+ constructor(config: JestEnvironmentConfig, _environmentContext: EnvironmentContext);
65
+ setup(): Promise<void>;
66
+ exportConditions(): string[];
67
+ getVmContext(): Context | null;
68
+ /**
69
+ * Closes the window (cancelling its timers, frames, idle callbacks and tasks) and undoes the file's
70
+ * patches to the shared interface prototypes. The globals stay installed, like under
71
+ * jest-environment-jsdom where the global *is* the window: work a test file left behind (React's
72
+ * scheduler runs on Node's setImmediate) can still read `window`/`document` instead of
73
+ * crashing the worker with a ReferenceError. The vm context is discarded with the file.
74
+ */
75
+ teardown(): Promise<void>;
76
+ }
77
+ export declare const TestEnvironment: typeof CtrlDomEnvironment;
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@ctrl/dom-jest-environment",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Jest environment for @ctrl/dom, the fast DOM for testing React components (testEnvironment: \"@ctrl/dom-jest-environment\", or preset: \"@ctrl/dom\").",
5
+ "keywords": [
6
+ "jest",
7
+ "jest-environment",
8
+ "dom",
9
+ "jsdom",
10
+ "happy-dom",
11
+ "testing",
12
+ "react"
13
+ ],
14
+ "license": "MIT",
15
+ "homepage": "https://github.com/scttcper/dom#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/scttcper/dom/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/scttcper/dom.git",
22
+ "directory": "publish/dom-jest-environment"
23
+ },
24
+ "author": "Scott Cooper <scttcper@gmail.com>",
25
+ "type": "module",
26
+ "engines": {
27
+ "node": ">=26"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "main": "./dist/index.js",
33
+ "types": "./dist/types/index.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/types/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "README.md",
44
+ "NOTICE",
45
+ "LICENSE"
46
+ ],
47
+ "dependencies": {
48
+ "@jest/environment": "30.4.1",
49
+ "@jest/fake-timers": "30.4.1",
50
+ "jest-mock": "30.4.1",
51
+ "jest-util": "30.4.1"
52
+ },
53
+ "peerDependencies": {
54
+ "@ctrl/dom": "^0.1.0",
55
+ "jest": ">=30.0.0"
56
+ }
6
57
  }