@ms-cloudpack/esm-stub-utilities 0.9.2 → 0.10.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.
@@ -1,42 +1,23 @@
1
- import { isMainThread, parentPort } from 'worker_threads';
2
1
  import { initBrowserEnvironment } from './initBrowserEnvironment.js';
3
2
  import { cleanUpGlobals, getGlobalProperties } from './globals.js';
4
- import { writeESMStubsInternal } from '../writeESMStubsInternal.js';
5
- if (isMainThread || !parentPort) {
6
- throw new Error('This file should only be loaded in a worker thread');
7
- }
3
+ import { writeESMStubs } from '../writeESMStubs.js';
4
+ import { initializeWorker } from '@ms-cloudpack/worker-pool';
5
+ // Load any environmental side effects here.
8
6
  await initBrowserEnvironment();
9
7
  // TODO should the globals be marked as readonly if possible?
10
8
  const initialGlobalProperties = getGlobalProperties();
11
- // eslint-disable-next-line @typescript-eslint/unbound-method
12
- const originalExit = process.exit;
13
- function emitMessage(message) {
14
- parentPort?.postMessage(message);
15
- }
16
- parentPort.on('message', (options) => {
17
- const { id } = options;
18
- function onExit() {
19
- throw new Error('process.exit() was unexpectedly called');
20
- }
21
- // Overwrite process.exit to throw an error, and also add an exit handler just in case.
22
- // This makes it easier to handle if one of the files being processed calls process.exit().
23
- process.exit = onExit;
24
- process.on('exit', onExit);
25
- writeESMStubsInternal(options)
26
- .then((result) => {
27
- emitMessage({ id, ...result });
28
- })
29
- .catch((error) => {
30
- emitMessage({
31
- id,
32
- newEntries: {},
33
- errors: [{ text: error.stack || String(error) }],
34
- });
35
- })
36
- .finally(() => {
9
+ // Override process.exit calls to throw rather than exit the process, in the case that
10
+ // we load some CJS code that calls process.exit on parse.
11
+ process.exit = (code) => {
12
+ throw new Error(`process.exit called with code ${code}`);
13
+ };
14
+ // Then initialize the worker with the appropriate listeners and api dictionary.
15
+ initializeWorker({
16
+ methods: {
17
+ writeESMStubs,
18
+ },
19
+ afterEach: () => {
37
20
  cleanUpGlobals(initialGlobalProperties);
38
- process.off('exit', onExit);
39
- process.exit = originalExit;
40
- });
21
+ },
41
22
  });
42
23
  //# sourceMappingURL=workerEntry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workerEntry.js","sourceRoot":"","sources":["../../src/worker/workerEntry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAGpE,IAAI,YAAY,IAAI,CAAC,UAAU,EAAE,CAAC;IAChC,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,sBAAsB,EAAE,CAAC;AAE/B,6DAA6D;AAC7D,MAAM,uBAAuB,GAAG,mBAAmB,EAAE,CAAC;AAEtD,6DAA6D;AAC7D,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;AAElC,SAAS,WAAW,CAAC,OAA8B;IACjD,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,UAAU,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAA6B,EAAE,EAAE;IACzD,MAAM,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC;IAEvB,SAAS,MAAM;QACb,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC5D,CAAC;IAED,uFAAuF;IACvF,2FAA2F;IAC3F,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE3B,qBAAqB,CAAC,OAAO,CAAC;SAC3B,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;QACf,WAAW,CAAC,EAAE,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACjC,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;QACf,WAAW,CAAC;YACV,EAAE;YACF,UAAU,EAAE,EAAE;YACd,MAAM,EAAE,CAAC,EAAE,IAAI,EAAG,KAAe,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;SAC5D,CAAC,CAAC;IACL,CAAC,CAAC;SACD,OAAO,CAAC,GAAG,EAAE;QACZ,cAAc,CAAC,uBAAuB,CAAC,CAAC;QACxC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC5B,OAAO,CAAC,IAAI,GAAG,YAAY,CAAC;IAC9B,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC","sourcesContent":["import { isMainThread, parentPort } from 'worker_threads';\nimport { initBrowserEnvironment } from './initBrowserEnvironment.js';\nimport { cleanUpGlobals, getGlobalProperties } from './globals.js';\nimport { writeESMStubsInternal } from '../writeESMStubsInternal.js';\nimport type { ESMStubWorkerRequest, ESMStubWorkerResponse } from '../types/ESMStubWorkerMessages.js';\n\nif (isMainThread || !parentPort) {\n throw new Error('This file should only be loaded in a worker thread');\n}\n\nawait initBrowserEnvironment();\n\n// TODO should the globals be marked as readonly if possible?\nconst initialGlobalProperties = getGlobalProperties();\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst originalExit = process.exit;\n\nfunction emitMessage(message: ESMStubWorkerResponse) {\n parentPort?.postMessage(message);\n}\n\nparentPort.on('message', (options: ESMStubWorkerRequest) => {\n const { id } = options;\n\n function onExit(): never {\n throw new Error('process.exit() was unexpectedly called');\n }\n\n // Overwrite process.exit to throw an error, and also add an exit handler just in case.\n // This makes it easier to handle if one of the files being processed calls process.exit().\n process.exit = onExit;\n process.on('exit', onExit);\n\n writeESMStubsInternal(options)\n .then((result) => {\n emitMessage({ id, ...result });\n })\n .catch((error) => {\n emitMessage({\n id,\n newEntries: {},\n errors: [{ text: (error as Error).stack || String(error) }],\n });\n })\n .finally(() => {\n cleanUpGlobals(initialGlobalProperties);\n process.off('exit', onExit);\n process.exit = originalExit;\n });\n});\n"]}
1
+ {"version":3,"file":"workerEntry.js","sourceRoot":"","sources":["../../src/worker/workerEntry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,4CAA4C;AAC5C,MAAM,sBAAsB,EAAE,CAAC;AAE/B,6DAA6D;AAC7D,MAAM,uBAAuB,GAAG,mBAAmB,EAAE,CAAC;AAEtD,sFAAsF;AACtF,0DAA0D;AAC1D,OAAO,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,EAAE;IACtB,MAAM,IAAI,KAAK,CAAC,iCAAiC,IAAI,EAAE,CAAC,CAAC;AAC3D,CAAC,CAAC;AAEF,gFAAgF;AAChF,gBAAgB,CAAC;IACf,OAAO,EAAE;QACP,aAAa;KACd;IACD,SAAS,EAAE,GAAG,EAAE;QACd,cAAc,CAAC,uBAAuB,CAAC,CAAC;IAC1C,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { initBrowserEnvironment } from './initBrowserEnvironment.js';\nimport { cleanUpGlobals, getGlobalProperties } from './globals.js';\nimport { writeESMStubs } from '../writeESMStubs.js';\nimport { initializeWorker } from '@ms-cloudpack/worker-pool';\n\n// Load any environmental side effects here.\nawait initBrowserEnvironment();\n\n// TODO should the globals be marked as readonly if possible?\nconst initialGlobalProperties = getGlobalProperties();\n\n// Override process.exit calls to throw rather than exit the process, in the case that\n// we load some CJS code that calls process.exit on parse.\nprocess.exit = (code) => {\n throw new Error(`process.exit called with code ${code}`);\n};\n\n// Then initialize the worker with the appropriate listeners and api dictionary.\ninitializeWorker({\n methods: {\n writeESMStubs,\n },\n afterEach: () => {\n cleanUpGlobals(initialGlobalProperties);\n },\n});\n"]}
@@ -1,9 +1,8 @@
1
1
  import type { WriteESMStubsOptions } from './types/WriteESMStubsOptions.js';
2
2
  import type { WriteESMStubsResult } from './types/WriteESMStubsResult.js';
3
3
  /**
4
- * Writes ESM stubs for CJS entries. Take in `intputPath` and `entries` and returns the stubs.
5
- * The `entries` record has key of output path minus extension (e.g. './index') and value
6
- * represents the entry source path (e.g. './src/index.js').
4
+ * Generates a set of ESM stubs for given entries and writes it to disk.
5
+ * If any files doesn't need a stub, the returned entry will use the original path.
7
6
  */
8
7
  export declare function writeESMStubs(options: WriteESMStubsOptions): Promise<WriteESMStubsResult>;
9
8
  //# sourceMappingURL=writeESMStubs.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"writeESMStubs.d.ts","sourceRoot":"","sources":["../src/writeESMStubs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAE1E;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAE/F"}
1
+ {"version":3,"file":"writeESMStubs.d.ts","sourceRoot":"","sources":["../src/writeESMStubs.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAE1E;;;GAGG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAsC/F"}
@@ -1,10 +1,50 @@
1
- import { processStubsInWorker } from './processStubsInWorker.js';
1
+ import { slash } from '@ms-cloudpack/path-string-parsing';
2
+ import { writeFile } from 'fs/promises';
3
+ import path from 'path';
4
+ import { generateESMStubFromCJS } from './generateESMStubFromCJS.js';
5
+ import { generateESMStubFromJSON } from './generateESMStubFromJSON.js';
6
+ import { getStubPath } from './getStubPath.js';
7
+ import { processError } from './processError.js';
2
8
  /**
3
- * Writes ESM stubs for CJS entries. Take in `intputPath` and `entries` and returns the stubs.
4
- * The `entries` record has key of output path minus extension (e.g. './index') and value
5
- * represents the entry source path (e.g. './src/index.js').
9
+ * Generates a set of ESM stubs for given entries and writes it to disk.
10
+ * If any files doesn't need a stub, the returned entry will use the original path.
6
11
  */
7
12
  export async function writeESMStubs(options) {
8
- return processStubsInWorker(options);
13
+ const { inputPath, entries } = options;
14
+ const result = {
15
+ newEntries: {},
16
+ errors: [],
17
+ };
18
+ for (const [entryKey, entryPath] of Object.entries(entries)) {
19
+ const filePath = slash(path.join(inputPath, entryPath));
20
+ const safeEntryKey = stripLeadingRelativePath(entryKey);
21
+ try {
22
+ const stubPath = await getStubPath({ inputPath, entryPath });
23
+ if (!stubPath) {
24
+ // Stub not needed
25
+ result.newEntries[safeEntryKey] = path.join(inputPath, entryPath);
26
+ continue;
27
+ }
28
+ let stubContent = '';
29
+ if (path.extname(entryPath).toLowerCase() === '.json') {
30
+ stubContent = await generateESMStubFromJSON({ filePath });
31
+ }
32
+ else {
33
+ stubContent = generateESMStubFromCJS({ filePath, stubPath });
34
+ }
35
+ // Attempt to write it to disk.
36
+ await writeFile(stubPath, stubContent, 'utf-8');
37
+ result.newEntries[safeEntryKey] = stubPath;
38
+ }
39
+ catch (e) {
40
+ const entryFullPath = path.join(inputPath, entryPath);
41
+ result.newEntries[safeEntryKey] = entryFullPath;
42
+ result.errors.push(processError(safeEntryKey, entryFullPath, e));
43
+ }
44
+ }
45
+ return result;
46
+ }
47
+ function stripLeadingRelativePath(relativePath) {
48
+ return relativePath.replace(/^\.\//, '');
9
49
  }
10
50
  //# sourceMappingURL=writeESMStubs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"writeESMStubs.js","sourceRoot":"","sources":["../src/writeESMStubs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAIjE;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,OAAO,oBAAoB,CAAC,OAAO,CAAC,CAAC;AACvC,CAAC","sourcesContent":["import { processStubsInWorker } from './processStubsInWorker.js';\nimport type { WriteESMStubsOptions } from './types/WriteESMStubsOptions.js';\nimport type { WriteESMStubsResult } from './types/WriteESMStubsResult.js';\n\n/**\n * Writes ESM stubs for CJS entries. Take in `intputPath` and `entries` and returns the stubs.\n * The `entries` record has key of output path minus extension (e.g. './index') and value\n * represents the entry source path (e.g. './src/index.js').\n */\nexport async function writeESMStubs(options: WriteESMStubsOptions): Promise<WriteESMStubsResult> {\n return processStubsInWorker(options);\n}\n"]}
1
+ {"version":3,"file":"writeESMStubs.js","sourceRoot":"","sources":["../src/writeESMStubs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,MAAM,GAAwB;QAClC,UAAU,EAAE,EAAE;QACd,MAAM,EAAE,EAAE;KACX,CAAC;IAEF,KAAK,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,O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AAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,wBAAwB,CAAC,YAAoB;IACpD,OAAO,YAAY,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import { slash } from '@ms-cloudpack/path-string-parsing';\nimport { writeFile } from 'fs/promises';\nimport path from 'path';\nimport { generateESMStubFromCJS } from './generateESMStubFromCJS.js';\nimport { generateESMStubFromJSON } from './generateESMStubFromJSON.js';\nimport { getStubPath } from './getStubPath.js';\nimport { processError } from './processError.js';\nimport type { WriteESMStubsOptions } from './types/WriteESMStubsOptions.js';\nimport type { WriteESMStubsResult } from './types/WriteESMStubsResult.js';\n\n/**\n * Generates a set of ESM stubs for given entries and writes it to disk.\n * If any files doesn't need a stub, the returned entry will use the original path.\n */\nexport async function writeESMStubs(options: WriteESMStubsOptions): Promise<WriteESMStubsResult> {\n const { inputPath, entries } = options;\n const result: WriteESMStubsResult = {\n newEntries: {},\n errors: [],\n };\n\n for (const [entryKey, entryPath] of Object.entries(entries)) {\n const filePath = slash(path.join(inputPath, entryPath));\n const safeEntryKey = stripLeadingRelativePath(entryKey);\n\n try {\n const stubPath = await getStubPath({ inputPath, entryPath });\n if (!stubPath) {\n // Stub not needed\n result.newEntries[safeEntryKey] = path.join(inputPath, entryPath);\n continue;\n }\n\n let stubContent: string = '';\n if (path.extname(entryPath).toLowerCase() === '.json') {\n stubContent = await generateESMStubFromJSON({ filePath });\n } else {\n stubContent = generateESMStubFromCJS({ filePath, stubPath });\n }\n\n // Attempt to write it to disk.\n await writeFile(stubPath, stubContent, 'utf-8');\n\n result.newEntries[safeEntryKey] = stubPath;\n } catch (e) {\n const entryFullPath = path.join(inputPath, entryPath);\n result.newEntries[safeEntryKey] = entryFullPath;\n result.errors.push(processError(safeEntryKey, entryFullPath, e));\n }\n }\n\n return result;\n}\n\nfunction stripLeadingRelativePath(relativePath: string) {\n return relativePath.replace(/^\\.\\//, '');\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ms-cloudpack/esm-stub-utilities",
3
- "version": "0.9.2",
3
+ "version": "0.10.0",
4
4
  "description": "Generates ESM stubs for CommonJS entry files.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,13 +11,19 @@
11
11
  "source": "./src/index.ts",
12
12
  "types": "./lib/index.d.ts",
13
13
  "import": "./lib/index.js"
14
+ },
15
+ "./workerEntry": {
16
+ "source": "./src/worker/workerEntry.ts",
17
+ "types": "./lib/worker/workerEntry.d.ts",
18
+ "import": "./lib/worker/workerEntry.js"
14
19
  }
15
20
  },
16
21
  "dependencies": {
17
- "@ms-cloudpack/bundler-types": "^0.24.0",
22
+ "@ms-cloudpack/bundler-types": "^0.24.1",
18
23
  "@ms-cloudpack/json-utilities": "^0.1.3",
19
24
  "@ms-cloudpack/path-string-parsing": "^1.1.3",
20
- "@ms-cloudpack/package-utilities": "^5.8.2",
25
+ "@ms-cloudpack/package-utilities": "^5.10.0",
26
+ "@ms-cloudpack/worker-pool": "^0.1.1",
21
27
  "jsdom-global": "^3.0.2",
22
28
  "jsdom": "^22.0.0",
23
29
  "regenerator-runtime": "^0.14.1"
@@ -1,12 +0,0 @@
1
- import type { WriteESMStubsOptions } from './types/WriteESMStubsOptions.js';
2
- import type { WriteESMStubsResult } from './types/WriteESMStubsResult.js';
3
- /**
4
- * Generates ESM stubs for CommonJS and JSON modules.
5
- */
6
- export declare function processStubsInWorker(options: WriteESMStubsOptions): Promise<WriteESMStubsResult>;
7
- /**
8
- * Stop the worker for testing.
9
- * @internal
10
- */
11
- export declare function _stopStubWorker(): Promise<void>;
12
- //# sourceMappingURL=processStubsInWorker.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"processStubsInWorker.d.ts","sourceRoot":"","sources":["../src/processStubsInWorker.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAU1E;;GAEG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAoFtG;AAED;;;GAGG;AACH,wBAAsB,eAAe,kBAGpC"}
@@ -1,94 +0,0 @@
1
- import path from 'path';
2
- import { fileURLToPath } from 'url';
3
- import { Worker } from 'worker_threads';
4
- const currentPath = path.dirname(fileURLToPath(import.meta.url));
5
- const workerPath = path.join(currentPath, './worker/workerEntry.js');
6
- let _counter = 0;
7
- // TODO do we need a pool?
8
- let worker;
9
- /**
10
- * Generates ESM stubs for CommonJS and JSON modules.
11
- */
12
- export async function processStubsInWorker(options) {
13
- const id = _counter++;
14
- // Initialize worker.
15
- if (!worker) {
16
- try {
17
- worker = new Worker(workerPath, { stdout: true, stderr: true, execArgv: [] });
18
- worker.stdout?.on('data', (data) => {
19
- console.debug(`[worker stdout] ${data}`);
20
- });
21
- worker.stderr?.on('data', (data) => {
22
- console.debug(`[worker stderr] ${data}`);
23
- });
24
- worker.on('exit', () => {
25
- worker = undefined;
26
- });
27
- // don't hold the process open if only the worker is left
28
- worker.unref();
29
- }
30
- catch (err) {
31
- throw new Error(`Error initializing worker: ${err?.stack || err}`);
32
- }
33
- }
34
- return new Promise((resolve, reject) => {
35
- // just for type checking
36
- if (!worker)
37
- return;
38
- worker.on('message', onMessage);
39
- worker.on('messageerror', onMessageError);
40
- worker.on('error', onError);
41
- worker.on('exit', onExit);
42
- const whileStubbingMessage = `while creating stubs for ${options.inputPath}`;
43
- // Send a message requesting the stubs to be created.
44
- const request = { id, ...options };
45
- worker.postMessage(request);
46
- /** Normally, both success and error results should be sent back as messages. */
47
- function onMessage(message) {
48
- if (message.id !== id) {
49
- return; // result about a different request
50
- }
51
- handlersOff();
52
- if (message.newEntries) {
53
- resolve(message);
54
- }
55
- else {
56
- reject(new Error(`Unexpected stub worker message ${whileStubbingMessage}: ${JSON.stringify(message, null, 2)}`));
57
- }
58
- }
59
- /** 'messageerror' event: deserializing a message failed (very unexpected). */
60
- function onMessageError(err) {
61
- handlersOff();
62
- reject(new Error(`Error with stub worker message serialization ${whileStubbingMessage}:\n${err.stack || err}\n`));
63
- }
64
- /** 'error' event: unhandled exception in the worker, which shouldn't happen. */
65
- function onError(err) {
66
- handlersOff();
67
- reject(new Error(`Uncaught error in stub worker ${whileStubbingMessage}:\n${err.stack || err}\n`));
68
- }
69
- /**
70
- * Make sure the promise rejects if the worker exits unexpectedly. (We override process.exit
71
- * in the worker to throw an error, so this shouldn't happen.)
72
- */
73
- function onExit() {
74
- worker = undefined;
75
- reject(new Error(`Stub worker exited unexpectedly ${whileStubbingMessage}`));
76
- }
77
- /** Remove all event handlers to avoid interference with future sandbox runs. */
78
- function handlersOff() {
79
- worker?.off('message', onMessage);
80
- worker?.off('messageerror', onMessageError);
81
- worker?.off('error', onError);
82
- worker?.off('exit', onExit);
83
- }
84
- });
85
- }
86
- /**
87
- * Stop the worker for testing.
88
- * @internal
89
- */
90
- export async function _stopStubWorker() {
91
- await worker?.terminate();
92
- worker = undefined;
93
- }
94
- //# sourceMappingURL=processStubsInWorker.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"processStubsInWorker.js","sourceRoot":"","sources":["../src/processStubsInWorker.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAKxC,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACjE,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,yBAAyB,CAAC,CAAC;AACrE,IAAI,QAAQ,GAAG,CAAC,CAAC;AAEjB,0BAA0B;AAC1B,IAAI,MAA0B,CAAC;AAE/B;;GAE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/E,CAAC;QAED,gFAAgF;QAChF,SAAS,WAAW;YAClB,MAAM,EAAE,GAAG,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;YAClC,MAAM,EAAE,GAAG,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;YAC5C,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9B,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe;IACnC,MAAM,MAAM,EAAE,SAAS,EAAE,CAAC;IAC1B,MAAM,GAAG,SAAS,CAAC;AACrB,CAAC","sourcesContent":["import path from 'path';\nimport { fileURLToPath } from 'url';\nimport { Worker } from 'worker_threads';\nimport type { WriteESMStubsOptions } from './types/WriteESMStubsOptions.js';\nimport type { WriteESMStubsResult } from './types/WriteESMStubsResult.js';\nimport type { ESMStubWorkerRequest, ESMStubWorkerResponse } from './types/ESMStubWorkerMessages.js';\n\nconst currentPath = path.dirname(fileURLToPath(import.meta.url));\nconst workerPath = path.join(currentPath, './worker/workerEntry.js');\nlet _counter = 0;\n\n// TODO do we need a pool?\nlet worker: Worker | undefined;\n\n/**\n * Generates ESM stubs for CommonJS and JSON modules.\n */\nexport async function processStubsInWorker(options: WriteESMStubsOptions): Promise<WriteESMStubsResult> {\n const id = _counter++;\n\n // Initialize worker.\n if (!worker) {\n try {\n worker = new Worker(workerPath, { stdout: true, stderr: true, execArgv: [] });\n worker.stdout?.on('data', (data) => {\n console.debug(`[worker stdout] ${data}`);\n });\n worker.stderr?.on('data', (data) => {\n console.debug(`[worker stderr] ${data}`);\n });\n worker.on('exit', () => {\n worker = undefined;\n });\n // don't hold the process open if only the worker is left\n worker.unref();\n } catch (err) {\n throw new Error(`Error initializing worker: ${(err as Error)?.stack || err}`);\n }\n }\n\n return new Promise((resolve, reject) => {\n // just for type checking\n if (!worker) return;\n\n worker.on('message', onMessage);\n worker.on('messageerror', onMessageError);\n worker.on('error', onError);\n worker.on('exit', onExit);\n\n const whileStubbingMessage = `while creating stubs for ${options.inputPath}`;\n\n // Send a message requesting the stubs to be created.\n const request: ESMStubWorkerRequest = { id, ...options };\n worker.postMessage(request);\n\n /** Normally, both success and error results should be sent back as messages. */\n function onMessage(message: ESMStubWorkerResponse) {\n if (message.id !== id) {\n return; // result about a different request\n }\n\n handlersOff();\n\n if (message.newEntries) {\n resolve(message);\n } else {\n reject(\n new Error(`Unexpected stub worker message ${whileStubbingMessage}: ${JSON.stringify(message, null, 2)}`),\n );\n }\n }\n\n /** 'messageerror' event: deserializing a message failed (very unexpected). */\n function onMessageError(err: Error) {\n handlersOff();\n reject(new Error(`Error with stub worker message serialization ${whileStubbingMessage}:\\n${err.stack || err}\\n`));\n }\n\n /** 'error' event: unhandled exception in the worker, which shouldn't happen. */\n function onError(err: Error) {\n handlersOff();\n reject(new Error(`Uncaught error in stub worker ${whileStubbingMessage}:\\n${err.stack || err}\\n`));\n }\n\n /**\n * Make sure the promise rejects if the worker exits unexpectedly. (We override process.exit\n * in the worker to throw an error, so this shouldn't happen.)\n */\n function onExit() {\n worker = undefined;\n reject(new Error(`Stub worker exited unexpectedly ${whileStubbingMessage}`));\n }\n\n /** Remove all event handlers to avoid interference with future sandbox runs. */\n function handlersOff() {\n worker?.off('message', onMessage);\n worker?.off('messageerror', onMessageError);\n worker?.off('error', onError);\n worker?.off('exit', onExit);\n }\n });\n}\n\n/**\n * Stop the worker for testing.\n * @internal\n */\nexport async function _stopStubWorker() {\n await worker?.terminate();\n worker = undefined;\n}\n"]}
@@ -1,8 +0,0 @@
1
- import type { WriteESMStubsOptions } from './types/WriteESMStubsOptions.js';
2
- import type { WriteESMStubsResult } from './types/WriteESMStubsResult.js';
3
- /**
4
- * Generates a set of ESM stubs for given entries and writes it to disk. If
5
- * any files doesn't need a stub, then entry will have an undefined stubPath.
6
- */
7
- export declare function writeESMStubsInternal(options: WriteESMStubsOptions): Promise<WriteESMStubsResult>;
8
- //# sourceMappingURL=writeESMStubsInternal.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"writeESMStubsInternal.d.ts","sourceRoot":"","sources":["../src/writeESMStubsInternal.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAE1E;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAsCvG"}
@@ -1,50 +0,0 @@
1
- import { slash } from '@ms-cloudpack/path-string-parsing';
2
- import { writeFile } from 'fs/promises';
3
- import path from 'path';
4
- import { generateESMStubFromCJS } from './generateESMStubFromCJS.js';
5
- import { generateESMStubFromJSON } from './generateESMStubFromJSON.js';
6
- import { getStubPath } from './getStubPath.js';
7
- import { processError } from './processError.js';
8
- /**
9
- * Generates a set of ESM stubs for given entries and writes it to disk. If
10
- * any files doesn't need a stub, then entry will have an undefined stubPath.
11
- */
12
- export async function writeESMStubsInternal(options) {
13
- const { inputPath, entries } = options;
14
- const result = {
15
- newEntries: {},
16
- errors: [],
17
- };
18
- for (const [entryKey, entryPath] of Object.entries(entries)) {
19
- const filePath = slash(path.join(inputPath, entryPath));
20
- const safeEntryKey = stripLeadingRelativePath(entryKey);
21
- try {
22
- const stubPath = await getStubPath({ inputPath, entryPath });
23
- if (!stubPath) {
24
- // Stub not needed
25
- result.newEntries[safeEntryKey] = path.join(inputPath, entryPath);
26
- continue;
27
- }
28
- let stubContent = '';
29
- if (path.extname(entryPath).toLowerCase() === '.json') {
30
- stubContent = await generateESMStubFromJSON({ filePath });
31
- }
32
- else {
33
- stubContent = generateESMStubFromCJS({ filePath, stubPath });
34
- }
35
- // Attempt to write it to disk.
36
- await writeFile(stubPath, stubContent, 'utf-8');
37
- result.newEntries[safeEntryKey] = stubPath;
38
- }
39
- catch (e) {
40
- const entryFullPath = path.join(inputPath, entryPath);
41
- result.newEntries[safeEntryKey] = entryFullPath;
42
- result.errors.push(processError(safeEntryKey, entryFullPath, e));
43
- }
44
- }
45
- return result;
46
- }
47
- function stripLeadingRelativePath(relativePath) {
48
- return relativePath.replace(/^\.\//, '');
49
- }
50
- //# sourceMappingURL=writeESMStubsInternal.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"writeESMStubsInternal.js","sourceRoot":"","sources":["../src/writeESMStubsInternal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,OAA6B;IACvE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,MAAM,GAAwB;QAClC,UAAU,EAAE,EAAE;QACd,MAAM,EAAE,EAAE;KACX,CAAC;IAEF,KAAK,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5D,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC;QACxD,MAAM,YAAY,GAAG,wBAAwB,CAAC,QAAQ,CAAC,CAAC;QAExD,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC,CAAC;YAC7D,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,kBAAkB;gBAClB,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;gBAClE,SAAS;YACX,CAAC;YAED,IAAI,WAAW,GAAW,EAAE,CAAC;YAC7B,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,KAAK,OAAO,EAAE,CAAC;gBACtD,WAAW,GAAG,MAAM,uBAAuB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;YAC5D,CAAC;iBAAM,CAAC;gBACN,WAAW,GAAG,sBAAsB,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAC;YAC/D,CAAC;YAED,+BAA+B;YAC/B,MAAM,SAAS,CAAC,QAAQ,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;YAEhD,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC,GAAG,QAAQ,CAAC;QAC7C,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;YACtD,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC,GAAG,aAAa,CAAC;YAChD,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,wBAAwB,CAAC,YAAoB;IACpD,OAAO,YAAY,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import { slash } from '@ms-cloudpack/path-string-parsing';\nimport { writeFile } from 'fs/promises';\nimport path from 'path';\nimport { generateESMStubFromCJS } from './generateESMStubFromCJS.js';\nimport { generateESMStubFromJSON } from './generateESMStubFromJSON.js';\nimport { getStubPath } from './getStubPath.js';\nimport { processError } from './processError.js';\nimport type { WriteESMStubsOptions } from './types/WriteESMStubsOptions.js';\nimport type { WriteESMStubsResult } from './types/WriteESMStubsResult.js';\n\n/**\n * Generates a set of ESM stubs for given entries and writes it to disk. If\n * any files doesn't need a stub, then entry will have an undefined stubPath.\n */\nexport async function writeESMStubsInternal(options: WriteESMStubsOptions): Promise<WriteESMStubsResult> {\n const { inputPath, entries } = options;\n const result: WriteESMStubsResult = {\n newEntries: {},\n errors: [],\n };\n\n for (const [entryKey, entryPath] of Object.entries(entries)) {\n const filePath = slash(path.join(inputPath, entryPath));\n const safeEntryKey = stripLeadingRelativePath(entryKey);\n\n try {\n const stubPath = await getStubPath({ inputPath, entryPath });\n if (!stubPath) {\n // Stub not needed\n result.newEntries[safeEntryKey] = path.join(inputPath, entryPath);\n continue;\n }\n\n let stubContent: string = '';\n if (path.extname(entryPath).toLowerCase() === '.json') {\n stubContent = await generateESMStubFromJSON({ filePath });\n } else {\n stubContent = generateESMStubFromCJS({ filePath, stubPath });\n }\n\n // Attempt to write it to disk.\n await writeFile(stubPath, stubContent, 'utf-8');\n\n result.newEntries[safeEntryKey] = stubPath;\n } catch (e) {\n const entryFullPath = path.join(inputPath, entryPath);\n result.newEntries[safeEntryKey] = entryFullPath;\n result.errors.push(processError(safeEntryKey, entryFullPath, e));\n }\n }\n\n return result;\n}\n\nfunction stripLeadingRelativePath(relativePath: string) {\n return relativePath.replace(/^\\.\\//, '');\n}\n"]}