|
| 1 | +// Flags: --experimental-web-worker |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +const common = require('../common'); |
| 5 | +if (!process.config.variables.node_use_amaro) { |
| 6 | + common.skip('Requires Amaro'); |
| 7 | +} |
| 8 | + |
| 9 | +// Strip file entry types without changing the worker's module semantics. |
| 10 | +const assert = require('node:assert'); |
| 11 | +const { mkdirSync, writeFileSync } = require('node:fs'); |
| 12 | +const { join } = require('node:path'); |
| 13 | +const { pathToFileURL } = require('node:url'); |
| 14 | +const fixtures = require('../common/fixtures'); |
| 15 | +const tmpdir = require('../common/tmpdir'); |
| 16 | + |
| 17 | +tmpdir.refresh(); |
| 18 | + |
| 19 | +function createEntry(name, source) { |
| 20 | + const path = join(tmpdir.path, name); |
| 21 | + writeFileSync(path, source); |
| 22 | + return pathToFileURL(path); |
| 23 | +} |
| 24 | + |
| 25 | +function expectMessage(url, expected) { |
| 26 | + const worker = new Worker(url, { type: 'module' }); |
| 27 | + worker.onerror = common.mustNotCall('worker failed'); |
| 28 | + worker.onmessage = common.mustCall(({ data }) => { |
| 29 | + assert.strictEqual(data, expected); |
| 30 | + worker.terminate(); |
| 31 | + }); |
| 32 | +} |
| 33 | + |
| 34 | +function expectError(url, code, type = 'module') { |
| 35 | + const worker = new Worker(url, { type }); |
| 36 | + worker.onmessage = common.mustNotCall('worker unexpectedly succeeded'); |
| 37 | + worker.onerror = common.mustCall(({ error }) => { |
| 38 | + assert.strictEqual(error.code ?? error.name, code); |
| 39 | + }); |
| 40 | +} |
| 41 | + |
| 42 | +// Worker type takes precedence over both the extension and package type. |
| 43 | +writeFileSync(join(tmpdir.path, 'package.json'), '{ "type": "commonjs" }'); |
| 44 | +for (const extension of ['ts', 'mts', 'cts']) { |
| 45 | + const url = createEntry(`entry.${extension}`, 'const type: string = typeof require; postMessage(type);'); |
| 46 | + expectMessage(url, 'undefined'); |
| 47 | +} |
| 48 | + |
| 49 | +// The entry can import TypeScript, and a query or hash does not affect detection. |
| 50 | +{ |
| 51 | + const url = fixtures.fileURL('web-worker', 'typescript', 'module.ts'); |
| 52 | + url.search = '?version=1'; |
| 53 | + url.hash = '#entry'; |
| 54 | + expectMessage(url, 42); |
| 55 | +} |
| 56 | + |
| 57 | +// Stripping errors reach the parent's error handler. |
| 58 | +mkdirSync(join(tmpdir.path, 'node_modules')); |
| 59 | +expectError(createEntry('node_modules/entry.ts', 'postMessage(1);'), |
| 60 | + 'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING'); |
| 61 | + |
| 62 | +// Classic workers and `.js` entries are not stripped. |
| 63 | +expectError(fixtures.fileURL('web-worker', 'typescript', 'entry.ts'), 'SyntaxError', 'classic'); |
| 64 | +expectError(createEntry('entry.js', 'const value: number = 1;'), 'SyntaxError'); |
0 commit comments