@exodus/test 1.0.0-rc.10 → 1.0.0-rc.101

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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -50
  3. package/bin/browsers.js +137 -0
  4. package/bin/color.js +14 -0
  5. package/bin/electron.js +71 -0
  6. package/bin/electron.preload.cjs +2 -0
  7. package/bin/find-binary.js +102 -0
  8. package/bin/inband.js +14 -0
  9. package/bin/index.js +638 -92
  10. package/bin/reporter.js +194 -0
  11. package/expect.cjs +1 -0
  12. package/jest.js +1 -0
  13. package/{bin → loader}/babel.cjs +0 -2
  14. package/loader/deno-import-map.json +9 -0
  15. package/loader/esbuild.js +1 -0
  16. package/loader/esbuild.optional.js +6 -0
  17. package/loader/flow.js +27 -0
  18. package/loader/jest.js +2 -0
  19. package/loader/node-test.js +14 -0
  20. package/loader/typescript.js +3 -0
  21. package/loader/typescript.loader.js +36 -0
  22. package/node.js +1 -0
  23. package/package.json +130 -17
  24. package/src/dark.cjs +129 -27
  25. package/src/engine.js +22 -0
  26. package/src/engine.node.cjs +46 -0
  27. package/src/engine.pure.cjs +592 -0
  28. package/src/engine.pure.snapshot.cjs +37 -0
  29. package/src/engine.select.cjs +5 -0
  30. package/src/exodus.js +51 -0
  31. package/src/expect.cjs +180 -0
  32. package/src/glob.cjs +13 -0
  33. package/src/jest.config.fs.js +55 -0
  34. package/src/jest.config.js +233 -0
  35. package/src/jest.environment.js +34 -0
  36. package/src/jest.fn.js +23 -21
  37. package/src/jest.js +252 -52
  38. package/src/jest.mock.js +385 -67
  39. package/src/jest.setup.js +7 -0
  40. package/src/jest.snapshot.js +104 -40
  41. package/src/jest.timers.js +101 -20
  42. package/src/node.js +10 -0
  43. package/src/pretty-format.cjs +25 -0
  44. package/src/replay.js +106 -0
  45. package/src/tape.cjs +15 -0
  46. package/src/tape.js +11 -8
  47. package/src/timers-track.js +89 -0
  48. package/src/version.js +21 -0
  49. package/tape.js +1 -0
  50. package/bin/jest.js +0 -13
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Exodus Movement, Inc
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/README.md CHANGED
@@ -1,79 +1,200 @@
1
1
  # @exodus/test
2
2
 
3
- A runner for `node:test`, `jest`, and `tape` test suites on top of `node:test`
4
-
5
- Most likely it will just work on your simple jest tests as as drop-in replacement
6
-
7
- Comes with typescript support, optional esm/cjs interop, and also loading babel transforms!
8
-
9
- Use `--coverage` to generate coverage output
3
+ A runner for `node:test`, `jest`, and `tape` test suites on top of `node:test` (and any runtime).
4
+
5
+ It can run your existing tests on [all runtimes and also browsers](#engines), with snapshots and module mocks.
6
+
7
+ ## Features
8
+
9
+ - Native ESM, including in Jest tests
10
+ - Esbuild on the fly for babelified ESM interop (enable via `--esbuild`)
11
+ - TypeScript support in both transform (through [tsx](https://tsx.is/), enable via `--esbuild`)
12
+ and typestrip (via `--typescript`) modes
13
+ - Runs on Node.js [node:test](https://nodejs.org/api/test.html), Bun, Deno, Electron,
14
+ [v8 CLI](https://v8.dev/docs/d8), JSC, [Hermes](https://hermesengine.dev), [SpiderMonkey](https://spidermonkey.dev/),
15
+ Chrome, Firefox, WebKit, Brave, Microsoft Edge,
16
+ [QuickJS](https://github.com/quickjs-ng/quickjs), [XS](https://github.com/Moddable-OpenSource/moddable-xst),
17
+ [GraalJS](https://github.com/oracle/graaljs), [Escargot](https://github.com/Samsung/escargot),
18
+ [Boa](https://github.com/boa-dev/boa), and even [engine262](https://github.com/engine262/engine262).
19
+ - Testsuite-agnostic — can run any file as long as it sets exit code based on test results
20
+ - Built-in [Jest](https://jestjs.io) compatibility (with `--jest`), including `jest.*` global
21
+ - Up to ~10x faster depending on the original setup
22
+ - Actual `expect` module, also `jest-extended` and `jest-when` just work on top
23
+ - Snapshots, including snapshot matchers
24
+ - Function and timer mocks
25
+ - [test.concurrent](https://jestjs.io/docs/api#testconcurrentname-fn-timeout)
26
+ - Module mocks, including for ESM modules (already loaded ESM modules can be mocked only on `node:test`)
27
+ - Loads Jest configuration
28
+ - Built-in network record/replay for offline tests, mocking `fetch` and `WebSocket` sessions
29
+ - `--drop-network` support for guaranteed offline testing
30
+ - Native code coverage via v8 (Node.js or [c8](https://github.com/bcoe/c8)), with istanbul reporters
31
+ - GitHub reporter (auto-enabled by default)
32
+ - JSDOM env support
33
+ - Hanging tests error by default (unlike `jest`)
34
+ - Babel support, picks up your Babel config (enable via `--babel`)
35
+ - Unlike `bun:test`, it runs test files in isolated contexts \
36
+ Bun leaks globals / side effects between test files ([ref](https://github.com/oven-sh/bun/issues/6024)),
37
+ and has incompatible `test()` lifecycle / order
38
+ - Also features a tape API for drop-in replacement
39
+
40
+ ## Engines
41
+
42
+ Use `--engine` (or `EXODUS_TEST_ENGINE=`) to specify one of:
43
+
44
+ - `node:test` — the default one, runs on top of modern Node.js [test runner API](https://nodejs.org/api/test.html)
45
+ - `node:pure` — implementation in pure JS, runs on Node.js
46
+ - `node:bundle` — same as `node:pure`, but bundles everything into a single file before launching
47
+ - Other runtimes:
48
+ - `deno:pure` — Deno (requires Deno v2.4.0 or later, expects `deno` to be available)
49
+ - `deno:bundle` — Deno (v1 or v2, whichever `deno` is)
50
+ - `deno:test` — incomplete, lacks `--jest` support due to missing `afterEach` / `beforeEach` in Deno
51
+ - `bun:pure` / `bun:bundle` — Bun, expects `bun` to be available
52
+ - `electron-as-node:test` / `electron-as-node:pure` / `electron-as-node:bundle`\
53
+ Same as `node:*`, but uses `electron` binary.\
54
+ The usecase is mostly to test on BoringSSL instead of OpenSSL.
55
+ - `electron:bundle` — run tests in Electron [BrowserWindow](https://www.electronjs.org/docs/latest/api/browser-window)
56
+ without Node.js integration.
57
+ - Browsers:
58
+ - Playwright builds (install Playwright-built engines with `exodus-test --playwright install`)
59
+ - `chromium:playwright` — Playwright-built Chromium
60
+ - `firefox:playwright` — Playwright-built Firefox
61
+ - `webkit:playwright` — Playwright-built WebKit, close to Safari
62
+ - `chrome:playwright` — Chrome (system-installed)
63
+ - `msedge:playwright` — Microsoft Edge (system-installed)
64
+ - Puppeteer (system-provided or upstream builds)
65
+ - `chrome:puppeteer` — Chrome
66
+ - `firefox:puppeteer` — Firefox
67
+ - `brave:puppeteer` — Brave
68
+ - `msedge:puppeteer` — Microsoft Edge
69
+ - Barebone engines (system-provided or installed with `npx jsvu` / `npx esvu`):
70
+ - `d8:bundle` — [v8 CLI](https://v8.dev/docs/d8) (Chrome/Blink/Node.js JavaScript engine)
71
+ - `jsc:bundle` — [JavaScriptCore](https://docs.webkit.org/Deep%20Dive/JSC/JavaScriptCore.html) (Safari/WebKit JavaScript engine)
72
+ - `hermes:bundle` — [Hermes](https://hermesengine.dev) (React Native JavaScript engine)
73
+ - `spidermonkey:bundle` — [SpiderMonkey](https://spidermonkey.dev/) (Firefox/Gecko JavaScript engine)
74
+ - `quickjs:bundle` — [QuickJS](https://github.com/quickjs-ng/quickjs)
75
+ - `xs:bundle` — [XS](https://github.com/Moddable-OpenSource/moddable-xst)
76
+ - `graaljs:bundle` — [GraalJS](https://github.com/oracle/graaljs)
77
+ - `escargot:bundle` — [Escargot](https://github.com/Samsung/escargot)
78
+ - `boa:bundle` — [Boa](https://github.com/boa-dev/boa)
79
+ - `engine262:bundle` - [engine262](https://github.com/engine262/engine262), the per-spec implementation of ECMA-262
80
+ (install with [esvu](https://npmjs.com/package/esvu))
81
+
82
+ ## Reporter samples
83
+
84
+ #### CLI (but uses colors when output supports them, e.g. in terminal):
85
+
86
+ ```console
87
+ # tests/jest/expect.mock.test.js
88
+ ✔ PASS drinkAll > drinks something lemon-flavoured (1.300417ms)
89
+ ✔ PASS drinkAll > does not drink something octopus-flavoured (0.191791ms)
90
+ ✔ PASS drinkAll (1.842959ms)
91
+ ✔ PASS drinkEach > drinkEach drinks each drink (0.360625ms)
92
+ ✔ PASS drinkEach (0.463416ms)
93
+ ✔ PASS toHaveBeenCalledWith > registration applies correctly to orange La Croix (0.53325ms)
94
+ ✔ PASS toHaveBeenCalledWith (0.564166ms)
95
+ ✔ PASS toHaveBeenLastCalledWith > applying to all flavors does mango last (0.380375ms)
96
+ ✔ PASS toHaveBeenLastCalledWith (0.473417ms)
97
+ # tests/jest/fn.invocationCallOrder.test.js
98
+ ✔ PASS mock.invocationCallOrder (4.221042ms)
99
+ ```
10
100
 
11
- Default `NODE_ENV` value is "test", use `NODE_ENV=` to override (e.g. to empty)
101
+ #### GitHub Actions collapses test results per-file, like this:
102
+
103
+ <details>
104
+ <summary>✅ <strong>tests/jest/lifecycle.test.js</strong></summary>
105
+ <pre>
106
+ ✔ PASS A > B > C (3.26166ms)
107
+ ✔ PASS A > B > D (1.699463ms)
108
+ ✔ PASS A > B (6.72719ms)
109
+ ✔ PASS A > E > F (1.117997ms)
110
+ ✔ PASS A > E > G > H (1.330904ms)
111
+ ✔ PASS A > E > G (1.94971ms)
112
+ ✔ PASS A > E (3.821825ms)
113
+ ✔ PASS A > I (0.533096ms)
114
+ ✔ PASS A (13.887889ms)
115
+ ✔ PASS J (0.373187ms)
116
+ ✔ PASS K > L (0.659852ms)
117
+ ✔ PASS K (1.143195ms)
118
+ </pre>
119
+ </details><details>
120
+ <summary>✅ <strong>tests/jest/timers.async.test.js</strong></summary>
121
+ <pre>
122
+ ✔ PASS advanceTimersByTime() does not let microtasks to pass (5.326604ms)
123
+ ✔ PASS advanceTimersByTime() does not let microtasks to pass even with await (1.336064ms)
124
+ ✔ PASS advanceTimersByTimeAsync() lets microtasks to pass (6.99526ms)
125
+ ✔ PASS advanceTimersByTimeAsync() lets microtasks to pass, chained (10.131664ms)
126
+ ✔ PASS advanceTimersByTimeAsync() lets microtasks to pass, longer chained (8.635472ms)
127
+ ✔ PASS advanceTimersByTimeAsync() lets microtasks to pass, async chain (56.937983ms)
128
+ </pre>
129
+ </details>
130
+
131
+ See live output in [CI](https://github.com/ExodusMovement/test/actions/workflows/checks.yaml)
12
132
 
13
133
  ## Library
14
134
 
15
- ### Using with `node:test` natively
16
-
17
- You can just use pure [`node:test`](https://nodejs.org/api/test.html) in your tests,
18
- this runner is fully compatible with that (and will set version-specific options for you)!
135
+ ### List of exports
19
136
 
20
- ### Moving from jest
137
+ - `@exodus/test/node` `node:test` API, working under non-Node.js platforms
21
138
 
22
- ```js
23
- import {
24
- jest,
25
- expect,
26
- describe,
27
- it,
28
- beforeEach,
29
- afterEach,
30
- beforeAll,
31
- afterAll,
32
- } from '@exodus/test/jest'
33
- ```
139
+ - `@exodus/test/jest` — `jest` implementation
34
140
 
35
- Or, run with [`--jest` option](#options) to register jest globals
141
+ - `@exodus/test/tape` `tape` mock (can also be helpful when moving from `tap`)
36
142
 
37
- ### Moving from tap/tape
38
-
39
- ```js
40
- import test from '@exodus/test/tap'
41
- ```
143
+ ## Binary
42
144
 
43
- ### Running tests asynchronously
145
+ Just use `"test": "exodus-test"`
44
146
 
45
- Add `{ concurrency: true }`, like this: `describe('my testsuite', { concurrency: true }, () => {`
147
+ ### Options
46
148
 
47
- ### List of exports
149
+ - `--jest` register jest test helpers as global variables, also load `jest.config.*` configuration options
48
150
 
49
- - `@exodus/test/jest` -- `jest` mock
151
+ - `--esbuild` use esbuild loader, also enables Typescript support
50
152
 
51
- - `@exodus/test/tape` -- `tape` mock (can also be helpful when moving from `tap`)
153
+ - `--babel` use babel loader (slower than `--esbuild`, makes sense if you have a special config)
52
154
 
53
- ## Binary
155
+ - `--coverage` — enable coverage, prints coverage output (varies by coverage engine)
54
156
 
55
- Just use `"test": "exodus-test"`
157
+ - `--coverage-engine c8` — use c8 coverage engine (default), also generates `./coverage/` dirs
56
158
 
57
- ### Options
159
+ - `--coverage-engine node` — use Node.js builtint coverage engine
58
160
 
59
- - `--jest` -- register jest test helpers as global variables
161
+ - `--watch` operate in watch mode and re-run tests on file changes
60
162
 
61
- - `--typescript` -- use typescript loader (which also compiles esm to cjs where needed)
163
+ - `--only` only run the tests marked with `test.only`
62
164
 
63
- - `--esbuild` -- use esbuild loader (currently an alias for `--typescript`)
165
+ - `--passWithNoTests` do not error when no test files were found
64
166
 
65
- - `--babel` -- use babel loader (slower than `--esbuild`, makes sense if you have a special config)
167
+ - `--write-snapshots` write snapshots instead of verifying them (has `--test-update-snapshots` alias)
66
168
 
67
- - `--coverage` -- enable coverage, prints coverage output (varies by coverage engine)
169
+ - `--test-force-exit` force exit after tests are done
68
170
 
69
- - `--coverage-engine c8` -- use c8 coverage engine (default), also generates `./coverage/` dirs
171
+ ## Jest compatibility
70
172
 
71
- - `--coverage-engine node` -- use Node.js builtint coverage engine
173
+ The `--jest` mode is mostly compatible with Jest. There are some noteworthy differences though.
174
+ This tool does not hoist mocks, so it is important that a mock is defined before the module that uses it is imported.
175
+ In ESM, this can be achieved with dynamic imports:
72
176
 
73
- - `--watch` -- operate in watch mode and re-run tests on file changes
177
+ ```js
178
+ jest.doMock('./hogwarts.js', () => ({
179
+ __esModule: true,
180
+ default: jest.fn(),
181
+ }))
182
+
183
+ const { default: getEntryQualification } = await import('./hogwarts.js')
184
+ const { qualifiesForHogwarts } = await import('./wizard.js') // module importing ./hogwarts.js
185
+
186
+ test('qualifies for Hogwarts', () => {
187
+ // doSomething is a mock function
188
+ getEntryQualification.mockReturnValue(['lumos'])
189
+
190
+ expect(qualifiesForHogwarts('potter')).toBe(false)
191
+ getEntryQualification.mockReturnValue([])
192
+ expect(qualifiesForHogwarts('potter')).toBe(true)
193
+ })
194
+ ```
74
195
 
75
- - `--passWithNoTests` -- do not error when no test files were found
196
+ Note that all modules that transitively import `hogwarts.js` will have to be imported after the mock is defined.
76
197
 
77
- - `--write-snapshots` -- write snapshots instead of verifying them (has `--test-update-snapshots` alias)
198
+ ## License
78
199
 
79
- - `--test-force-exit` -- force exit after tests are done (useful in integration tests where it could be unfeasible to resolve all open handles)
200
+ [MIT](./LICENSE)
@@ -0,0 +1,137 @@
1
+ import assert from 'node:assert/strict'
2
+ import { spawnSync } from 'node:child_process'
3
+ import { readFile } from 'node:fs/promises'
4
+ import { dirname, resolve } from 'node:path'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { findBinary } from './find-binary.js'
7
+
8
+ // See https://playwright.dev/docs/browsers
9
+ // > Playwright doesn't work with the branded version of Firefox since it relies on patches.
10
+ // > Playwright doesn't work with the branded version of Safari since it relies on patches.
11
+
12
+ let puppeteer
13
+ let playwright
14
+
15
+ const puppeteerBrowsers = { brave: 'chrome', msedge: 'chrome' }
16
+ const playwrightBrowsers = { chrome: 'chromium', msedge: 'chromium' }
17
+
18
+ const launched = Object.create(null)
19
+ const launchers = {
20
+ async puppeteer({ binary, devtools }) {
21
+ if (!puppeteer) puppeteer = await import('puppeteer-core')
22
+ const browser = Object.hasOwn(puppeteerBrowsers, binary) ? puppeteerBrowsers[binary] : binary
23
+ assert(['chrome', 'firefox'].includes(browser))
24
+ return puppeteer.launch({ executablePath: findBinary(binary), browser, devtools })
25
+ },
26
+ async playwright({ binary: channel, devtools }) {
27
+ if (!playwright) playwright = await import('playwright-core')
28
+ const type = Object.hasOwn(playwrightBrowsers, channel) ? playwrightBrowsers[channel] : channel
29
+ assert(['chromium', 'firefox', 'webkit'].includes(type) && Object.hasOwn(playwright, type))
30
+ return playwright[type].launch({ devtools, channel })
31
+ },
32
+ }
33
+
34
+ export const close = () => Promise.all(Object.values(launched).map((p) => p.then((b) => b.close())))
35
+
36
+ async function newPage(runner, browser, { binary, dropNetwork }) {
37
+ const context = await (browser.newContext ? browser.newContext() : browser.createBrowserContext())
38
+ if (dropNetwork && context.setOffline && binary !== 'webkit') await context.setOffline(true) // WebKit crashes if this is done prior to navigation to /dev/null
39
+ let page
40
+ try {
41
+ page = await context.newPage()
42
+ } catch (err) {
43
+ // Puppeteer has a bug with Firefox, we expect that and just retry
44
+ if (runner !== 'puppeteer' || binary !== 'firefox' || err.name !== 'ProtocolError') throw err
45
+ await context.close()
46
+ return newPage(runner, browser, { binary, dropNetwork })
47
+ }
48
+
49
+ // Need to load a secure origin for e.g. crypto.subtle to be available
50
+ if (runner === 'playwright' && binary === 'webkit') {
51
+ // Can attempt to download /dev/null, so we apply a work-around
52
+ await page.route('https://www.secure-context-top-level-domain-for-tests/*', (route) =>
53
+ route.fulfill({
54
+ status: 200,
55
+ contentType: 'text/html; charset=utf-8',
56
+ body: '<!doctype html><html><body></body></html>',
57
+ })
58
+ )
59
+ await page.goto('https://www.secure-context-top-level-domain-for-tests/')
60
+ } else {
61
+ await page.goto('file:///dev/null')
62
+ }
63
+
64
+ if (dropNetwork && context.setOffline) await context.setOffline(true)
65
+ if (dropNetwork && page.setOfflineMode) await page.setOfflineMode(true)
66
+ assert(!dropNetwork || context.setOffline || page.setOfflineMode)
67
+ return { context, page }
68
+ }
69
+
70
+ export async function run(runner, args, { binary, devtools, dropNetwork, timeout, throttle }) {
71
+ assert(args.length === 1, 'Unexpected args to browser runner')
72
+
73
+ const bundle = await readFile(args[0], 'utf8')
74
+ let code = 0
75
+ const [stdout, stderr] = [[], []]
76
+
77
+ assert(Object.hasOwn(launchers, runner), 'Unexpected runner')
78
+ if (!launched[runner]) launched[runner] = launchers[runner]({ binary, devtools: !!devtools })
79
+ const { page, context } = await newPage(runner, await launched[runner], { binary, dropNetwork })
80
+
81
+ if (throttle) {
82
+ try {
83
+ const cdp = await (page.createCDPSession
84
+ ? page.createCDPSession()
85
+ : context.newCDPSession(page))
86
+ await cdp.send('Emulation.setCPUThrottlingRate', { rate: throttle })
87
+ } catch (cause) {
88
+ throw new Error(`${binary}:${runner} engine does not support --throttle-cpu`, { cause })
89
+ }
90
+ }
91
+
92
+ page.on('console', (message) => {
93
+ const type = message.type()
94
+ const target = type === 'error' ? stderr : stdout
95
+ target.push(message.text())
96
+ })
97
+ page.on('pageerror', (error) => {
98
+ if (!code) code = 1
99
+ stderr.push(`${error}`)
100
+ })
101
+
102
+ let timer
103
+ const promise = new Promise((resolve) => {
104
+ timer = setTimeout(() => {
105
+ stderr.push('timeout reached')
106
+ resolve(1) // Error code
107
+ }, timeout)
108
+ })
109
+
110
+ const wait = async () => {
111
+ await page.evaluate(bundle)
112
+ return page.evaluate('globalThis.EXODUS_TEST_PROMISE')
113
+ }
114
+
115
+ try {
116
+ // exitCode might be undefined if we failed before EXODUS_TEST_PROMISE was set, but we will have code then
117
+ const exitCode = await Promise.race([wait(), promise])
118
+ code = code || exitCode
119
+ if (!Number.isInteger(code)) {
120
+ stderr.push('Browser test did not indicate completion. Terminating with a failure...')
121
+ code = 1
122
+ }
123
+
124
+ return { code, stdout: stdout.join('\n'), stderr: stderr.join('\n') }
125
+ } catch (error) {
126
+ return { code: 1, stdout: '', stderr: `${error}` }
127
+ } finally {
128
+ clearTimeout(timer)
129
+ await context.close()
130
+ }
131
+ }
132
+
133
+ export function runPlaywrightCommand(args) {
134
+ const playwright = dirname(fileURLToPath(import.meta.resolve('playwright-core/package.json')))
135
+ const cli = resolve(playwright, 'cli.js')
136
+ return spawnSync(cli, args, { stdio: 'inherit' })
137
+ }
package/bin/color.js ADDED
@@ -0,0 +1,14 @@
1
+ import { inspect } from 'node:util'
2
+
3
+ const colors = new Map(Object.entries(inspect.colors))
4
+ const { CI, FORCE_COLOR } = process.env
5
+ const CI_COLORS = CI && !FORCE_COLOR /// when not overriden via FORCE_COLOR, assume CI has colors even though not a tty
6
+ export const haveColors = CI_COLORS || process.stdout.hasColors?.() || FORCE_COLOR === '1' // 0 is already handled by hasColors()
7
+ export const dim = CI ? 'gray' : 'dim'
8
+
9
+ export const color = (text, color) => {
10
+ if (!haveColors || text === '') return text
11
+ if (!colors.has(color)) throw new Error(`Unknown color: ${color}`)
12
+ const [start, end] = colors.get(color)
13
+ return `\x1B[${start}m${text}\x1B[${end}m`
14
+ }
@@ -0,0 +1,71 @@
1
+ import { app, ipcMain, protocol, session, BrowserWindow } from 'electron'
2
+ import { readFile } from 'node:fs/promises'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const abort = (message) => {
6
+ if (message) console.error(message)
7
+ app.exit(1)
8
+ }
9
+
10
+ if (process.argv[1] !== import.meta.filename) abort('Unexpected launcher script')
11
+ const files = process.argv.slice(2).map((f) => readFile(f, 'utf8'))
12
+
13
+ // synchronous to ensure we don't miss anything
14
+ ipcMain.on('print', (event, args) => {
15
+ console.log(...args)
16
+ event.returnValue = undefined // eslint-disable-line @exodus/mutable/no-param-reassign-prop-only
17
+ })
18
+
19
+ process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = true // we don't want Electron CSP warnings
20
+ process.on('unhandledRejection', (e) => abort(e))
21
+ app.on('window-all-closed', () => abort('Window got closed'))
22
+
23
+ protocol.registerSchemesAsPrivileged([
24
+ {
25
+ scheme: 'exodustest',
26
+ privileges: { standard: true, secure: true, supportFetchAPI: true }, // has to be standard + secure for crypto
27
+ },
28
+ ])
29
+
30
+ const enableIntegration = process.env.EXODUS_TEST_ENGINE === 'electron:pure'
31
+ const devtools = process.env.EXODUS_TEST_DEVTOOLS === '1'
32
+ const preload = fileURLToPath(import.meta.resolve('./electron.preload.cjs'))
33
+ const partition = 'tmp' // not persistent
34
+ const securityPreferences = enableIntegration
35
+ ? { sandbox: false, contextIsolation: false, nodeIntegration: true }
36
+ : { sandbox: true, contextIsolation: true, preload }
37
+ const webPreferences = { ...securityPreferences, partition, spellcheck: false }
38
+ const html = '<!doctype html><html><body></body></html>'
39
+ const headers = { 'content-type': 'text/html' }
40
+
41
+ // eslint-disable-next-line unicorn/prefer-top-level-await
42
+ app.whenReady().then(async () => {
43
+ const ses = session.fromPartition(partition)
44
+ ses.protocol.handle('exodustest', () => new Response(html, { headers }))
45
+ const win = new BrowserWindow({ show: devtools, webPreferences })
46
+ if (devtools) win.openDevTools()
47
+
48
+ await win.loadURL('exodustest://bundle/')
49
+ await win.webContents.executeJavaScript(`
50
+ const consoleKeys = ['log', 'error', 'warn', 'info', 'debug', 'trace']
51
+ for (const k of consoleKeys) {
52
+ if (!Object.hasOwn(console, k)) continue
53
+ const orig = console[k].bind(console)
54
+ const value = (...args) => { __test_print(...args); orig(...args) }
55
+ Object.defineProperty(console, k, { value })
56
+ }
57
+ ;0
58
+ `)
59
+
60
+ try {
61
+ for (const file of files) {
62
+ await win.webContents.executeJavaScript(`${await file};0`)
63
+ const code = await win.webContents.executeJavaScript('globalThis.EXODUS_TEST_PROMISE')
64
+ if (code !== 0) app.exit(typeof code === 'number' ? code : 1)
65
+ }
66
+ } catch (err) {
67
+ abort(err)
68
+ }
69
+
70
+ app.quit()
71
+ })
@@ -0,0 +1,2 @@
1
+ const { contextBridge, ipcRenderer } = require('electron')
2
+ contextBridge.exposeInMainWorld('__test_print', (...args) => ipcRenderer.sendSync('print', args))
@@ -0,0 +1,102 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { createRequire } from 'node:module'
5
+
6
+ const require = createRequire(import.meta.url)
7
+ const nvm = process.env.NVM_BIN ? (x) => join(process.env.NVM_BIN, '../lib/node_modules', x) : null
8
+ const jsvu = (x) => join(homedir(), '.jsvu/bin', x)
9
+ const esvu = (x) => join(homedir(), '.esvu/bin', x)
10
+
11
+ // Can modify PATH to add the binary to it!
12
+ function findBinaryOnce(name) {
13
+ // For browsers where full path is needed
14
+ const paths = []
15
+ const addPaths = (platform, ...args) => process.platform === platform && paths.push(...args)
16
+
17
+ // For js engines where we can fall back to the command name
18
+ const findFile = (methods, allowGlobal = true) => {
19
+ for (const x of methods) {
20
+ try {
21
+ const file = x(process.platform === 'win32' ? `${name}.exe` : name)
22
+ if (file && existsSync(file)) return file
23
+ } catch {}
24
+ }
25
+
26
+ if (!allowGlobal) {
27
+ console.error(`Local ${name} not installed, refusing to run`)
28
+ process.exit(1)
29
+ }
30
+
31
+ console.warn(`Local ${name} not installed, attempting to load global ${name}...`)
32
+ return name
33
+ }
34
+
35
+ switch (name) {
36
+ case 'hermes': {
37
+ const flavors = { darwin: 'osx-bin', linux: 'linux64-bin', win32: 'win64-bin' }
38
+ const flavor = Object.hasOwn(flavors, process.platform) ? flavors[process.platform] : null
39
+ return findFile([
40
+ (bin) => flavor && require.resolve(`react-native/sdks/hermesc/${flavor}/${bin}`), // 1. Locally installed react-native dep (works only for osx)
41
+ (bin) => flavor && require.resolve(`hermes-engine-cli/${flavor}/${bin}`), // 2. Locally installed hermes-engine-cli
42
+ (bin) => jsvu(bin), // 3. jsvu
43
+ (bin) => nvm(`hermes-engine-cli/${flavor}/${bin}`), // 4. hermes-engine-cli installed in .nvm dir with npm i -g
44
+ ]) // 5. hermes installed in the system
45
+ }
46
+
47
+ case 'jsc':
48
+ return findFile([
49
+ (bin) => jsvu(bin), // prefer jsvu
50
+ (bin) => esvu(bin),
51
+ (bin) => `/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Helpers/${bin}`,
52
+ (bin) => `/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/${bin}`,
53
+ ])
54
+ case 'd8':
55
+ return findFile([() => jsvu('v8'), () => esvu('v8')]) // jsvu/esvu name it v8
56
+ case 'spidermonkey':
57
+ case 'quickjs':
58
+ case 'graaljs':
59
+ case 'escargot':
60
+ case 'boa': // not present in jsvu, esvu lacks aarch64-apple-darwin platform (as it's only in nightly)
61
+ case 'ladybird-js': // naming by esvu
62
+ case 'engine262':
63
+ return findFile([jsvu, esvu])
64
+ case 'xs':
65
+ return findFile([jsvu, esvu], false)
66
+ case 'electron':
67
+ return require('electron')
68
+ case 'c8':
69
+ return require.resolve('c8/bin/c8.js')
70
+ case 'chrome':
71
+ addPaths('darwin', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
72
+ addPaths('linux', '/usr/bin/chromium', '/snap/bin/chromium', '/usr/bin/google-chrome')
73
+ break
74
+ case 'firefox':
75
+ addPaths('darwin', '/Applications/Firefox.app/Contents/MacOS/firefox')
76
+ addPaths('linux', '/usr/bin/firefox')
77
+ break
78
+ case 'brave':
79
+ addPaths('darwin', '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser')
80
+ addPaths('linux', '/usr/bin/brave', '/snap/bin/brave', '/opt/brave-bin/brave')
81
+ break
82
+ case 'msedge':
83
+ addPaths('darwin', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge')
84
+ addPaths('linux', '/usr/bin/msedge', '/snap/bin/msedge', '/opt/microsoft/msedge/msedge')
85
+ break
86
+ case 'safari':
87
+ addPaths('darwin', '/Applications/Safari.app/Contents/MacOS/Safari')
88
+ break
89
+ default:
90
+ throw new Error('Trying to find an unexpected executable name')
91
+ }
92
+
93
+ for (const path of paths) if (existsSync(path)) return path
94
+ throw new Error(`Failed to find ${name} executable`)
95
+ }
96
+
97
+ const binaries = new Map()
98
+
99
+ export function findBinary(name) {
100
+ if (!binaries.has(name)) binaries.set(name, findBinaryOnce(name))
101
+ return binaries.get(name)
102
+ }
package/bin/inband.js ADDED
@@ -0,0 +1,14 @@
1
+ import { resolve } from 'node:path'
2
+ import { pathToFileURL } from 'node:url'
3
+ import { describe, after } from '../src/engine.js'
4
+
5
+ const files = JSON.parse(process.env.EXODUS_TEST_INBAND)
6
+ if (!Array.isArray(files)) throw new Error('Unexpected')
7
+
8
+ for (const file of files.sort()) {
9
+ await describe(`EXODUS_TEST_INBAND:${file}`, async () => {
10
+ await import(pathToFileURL(resolve(file)))
11
+ })
12
+ }
13
+
14
+ if (globalThis.EXODUS_TEST_AFTER_INBAND) after(globalThis.EXODUS_TEST_AFTER_INBAND)