vitest-pool-assemblyscript 0.9.1 → 0.10.1

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 (100) hide show
  1. package/assembly/compare.ts +11 -12
  2. package/assembly/describe.ts +4 -4
  3. package/assembly/expect.ts +44 -26
  4. package/assembly/test.ts +9 -9
  5. package/assembly/utils.ts +218 -62
  6. package/dist/{addon-interface-CYFXMbK7.mjs → addon-interface-BaUmn7uC.mjs} +12 -12
  7. package/dist/addon-interface-BaUmn7uC.mjs.map +1 -0
  8. package/dist/{ast-visitor-CWEOd3UH.mjs → ast-visitor-w1HMbuJR.mjs} +2 -2
  9. package/dist/{ast-visitor-CWEOd3UH.mjs.map → ast-visitor-w1HMbuJR.mjs.map} +1 -1
  10. package/dist/compile-runner-BGHM_85g.mjs +82 -0
  11. package/dist/compile-runner-BGHM_85g.mjs.map +1 -0
  12. package/dist/compiler/transforms/deep-equals.d.mts.map +1 -1
  13. package/dist/compiler/transforms/deep-equals.mjs +61 -22
  14. package/dist/compiler/transforms/deep-equals.mjs.map +1 -1
  15. package/dist/compiler/transforms/strip-inline.mjs +2 -2
  16. package/dist/{compiler-Dqs-qd3I.mjs → compiler-CXR5UJId.mjs} +55 -27
  17. package/dist/compiler-CXR5UJId.mjs.map +1 -0
  18. package/dist/config/index-v3.d.mts +1 -1
  19. package/dist/config/index-v3.d.mts.map +1 -1
  20. package/dist/config/index-v3.mjs.map +1 -1
  21. package/dist/config/index.d.mts +2 -2
  22. package/dist/config/index.mjs +5 -7
  23. package/dist/{constants-DbxJ3hzg.mjs → constants-Bq5KNxXJ.mjs} +4 -2
  24. package/dist/constants-Bq5KNxXJ.mjs.map +1 -0
  25. package/dist/{coverage-merge-CBXkpM1O.mjs → coverage-merge-0WqdC-dq.mjs} +1 -1
  26. package/dist/{coverage-merge-CBXkpM1O.mjs.map → coverage-merge-0WqdC-dq.mjs.map} +1 -1
  27. package/dist/coverage-provider/index.mjs +36 -36
  28. package/dist/coverage-provider/index.mjs.map +1 -1
  29. package/dist/{feature-check-Bje3ntpV.mjs → feature-check-BJpc4LoO.mjs} +4 -4
  30. package/dist/{feature-check-Bje3ntpV.mjs.map → feature-check-BJpc4LoO.mjs.map} +1 -1
  31. package/dist/index-internal.d.mts +3 -3
  32. package/dist/index-internal.d.mts.map +1 -1
  33. package/dist/index-internal.mjs +5 -4
  34. package/dist/index-v3.d.mts.map +1 -1
  35. package/dist/index-v3.mjs +19 -33
  36. package/dist/index-v3.mjs.map +1 -1
  37. package/dist/index.d.mts +1 -1
  38. package/dist/index.mjs +5 -7
  39. package/dist/{load-user-imports-Bx5ZlhSm.mjs → load-user-imports-Bcx9NOt9.mjs} +119 -232
  40. package/dist/load-user-imports-Bcx9NOt9.mjs.map +1 -0
  41. package/dist/pool-errors-Bn6YaguR.mjs +630 -0
  42. package/dist/pool-errors-Bn6YaguR.mjs.map +1 -0
  43. package/dist/{pool-runner-init-CNpRdA5u.d.mts → pool-runner-init-CCvnKt5o.d.mts} +2 -2
  44. package/dist/pool-runner-init-CCvnKt5o.d.mts.map +1 -0
  45. package/dist/{pool-runner-init-BqkwQ2tk.mjs → pool-runner-init-DjRCbiX-.mjs} +15 -30
  46. package/dist/pool-runner-init-DjRCbiX-.mjs.map +1 -0
  47. package/dist/pool-thread/compile-worker-thread.d.mts +1 -1
  48. package/dist/pool-thread/compile-worker-thread.d.mts.map +1 -1
  49. package/dist/pool-thread/compile-worker-thread.mjs +29 -19
  50. package/dist/pool-thread/compile-worker-thread.mjs.map +1 -1
  51. package/dist/pool-thread/test-worker-thread.d.mts +1 -1
  52. package/dist/pool-thread/test-worker-thread.d.mts.map +1 -1
  53. package/dist/pool-thread/test-worker-thread.mjs +25 -18
  54. package/dist/pool-thread/test-worker-thread.mjs.map +1 -1
  55. package/dist/pool-thread/v3-tinypool-thread.d.mts +1 -1
  56. package/dist/pool-thread/v3-tinypool-thread.d.mts.map +1 -1
  57. package/dist/pool-thread/v3-tinypool-thread.mjs +43 -33
  58. package/dist/pool-thread/v3-tinypool-thread.mjs.map +1 -1
  59. package/dist/test-runner-BeP8ClnE.mjs +147 -0
  60. package/dist/test-runner-BeP8ClnE.mjs.map +1 -0
  61. package/dist/{types-DHVk5iAx.d.mts → types-CoroKYxB.d.mts} +39 -16
  62. package/dist/types-CoroKYxB.d.mts.map +1 -0
  63. package/dist/vitest-file-tasks-vvZzigcF.mjs +473 -0
  64. package/dist/vitest-file-tasks-vvZzigcF.mjs.map +1 -0
  65. package/dist/wasm-memory-C8Nkl2Sz.mjs +134 -0
  66. package/dist/wasm-memory-C8Nkl2Sz.mjs.map +1 -0
  67. package/dist/{worker-rpc-channel-CZZIxtv5.mjs → worker-rpc-channel-CvCrc8aa.mjs} +1 -1
  68. package/dist/{worker-rpc-channel-CZZIxtv5.mjs.map → worker-rpc-channel-CvCrc8aa.mjs.map} +1 -1
  69. package/package.json +1 -1
  70. package/prebuilds/darwin-arm64/vitest-pool-assemblyscript.glibc.node +0 -0
  71. package/prebuilds/darwin-x64/vitest-pool-assemblyscript.glibc.node +0 -0
  72. package/prebuilds/linux-arm64/vitest-pool-assemblyscript.glibc.node +0 -0
  73. package/prebuilds/linux-x64/vitest-pool-assemblyscript.glibc.node +0 -0
  74. package/prebuilds/linux-x64/vitest-pool-assemblyscript.musl.node +0 -0
  75. package/prebuilds/win32-arm64/vitest-pool-assemblyscript.glibc.node +0 -0
  76. package/prebuilds/win32-x64/vitest-pool-assemblyscript.glibc.node +0 -0
  77. package/src/instrumentation/native/addon.cpp +71 -32
  78. package/dist/addon-interface-CYFXMbK7.mjs.map +0 -1
  79. package/dist/compile-runner-BNFHRGZO.mjs +0 -85
  80. package/dist/compile-runner-BNFHRGZO.mjs.map +0 -1
  81. package/dist/compiler-Dqs-qd3I.mjs.map +0 -1
  82. package/dist/constants-DbxJ3hzg.mjs.map +0 -1
  83. package/dist/debug-DtRAL4rM.mjs +0 -232
  84. package/dist/debug-DtRAL4rM.mjs.map +0 -1
  85. package/dist/load-user-imports-Bx5ZlhSm.mjs.map +0 -1
  86. package/dist/path-utils-t9OzjXYF.mjs +0 -24
  87. package/dist/path-utils-t9OzjXYF.mjs.map +0 -1
  88. package/dist/pool-runner-init-BqkwQ2tk.mjs.map +0 -1
  89. package/dist/pool-runner-init-CNpRdA5u.d.mts.map +0 -1
  90. package/dist/resolve-config-s9gSJSMc.mjs +0 -85
  91. package/dist/resolve-config-s9gSJSMc.mjs.map +0 -1
  92. package/dist/test-runner-BGqc9uCK.mjs +0 -138
  93. package/dist/test-runner-BGqc9uCK.mjs.map +0 -1
  94. package/dist/types-DHVk5iAx.d.mts.map +0 -1
  95. package/dist/vitest-file-tasks-D8sOClGX.mjs +0 -149
  96. package/dist/vitest-file-tasks-D8sOClGX.mjs.map +0 -1
  97. package/dist/vitest-tasks-BZ24sghI.mjs +0 -321
  98. package/dist/vitest-tasks-BZ24sghI.mjs.map +0 -1
  99. package/dist/wasm-names-BFtzQCH4.mjs +0 -124
  100. package/dist/wasm-names-BFtzQCH4.mjs.map +0 -1
@@ -0,0 +1,134 @@
1
+ //#region src/util/assemblyscript/binding-helpers.ts
2
+ const STRING_EXTRACT_CHUNK_SIZE = 1024;
3
+ /**
4
+ * Decode an AssemblyScript string from WASM memory, using the length stored at
5
+ * the beginning of the string.
6
+ *
7
+ * This approach is borrowed from AssemblyScript with changes for clarity.
8
+ * AssemblyScript is released under the Apache 2.0 license, included here.
9
+ *
10
+ * When a string argument crosses the boundary to JS, we get a pointer to the
11
+ * string data in WASM memory. WASM strings store their length in the 4 bytes
12
+ * before the string data pointer so we know how much to read from memory.
13
+ *
14
+ * @param memory - WebAssembly memory instance
15
+ * @param pointer - Pointer to the start of the string
16
+ * @returns Decoded string
17
+ */
18
+ function liftString(memory, pointer) {
19
+ if (!pointer) return void 0;
20
+ const unsigned = pointer >>> 0;
21
+ const uint32LengthPtr = unsigned - 4 >>> 2;
22
+ const byteOffsetLength = new Uint32Array(memory.buffer)[uint32LengthPtr];
23
+ if (byteOffsetLength === 0) return "";
24
+ const uint16EndPtr = unsigned + byteOffsetLength >>> 1;
25
+ let uint16StartPtr = unsigned >>> 1;
26
+ const memoryU16 = new Uint16Array(memory.buffer);
27
+ let string = "";
28
+ while (uint16EndPtr - uint16StartPtr > STRING_EXTRACT_CHUNK_SIZE) string += String.fromCharCode(...memoryU16.subarray(uint16StartPtr, uint16StartPtr += STRING_EXTRACT_CHUNK_SIZE));
29
+ return string + String.fromCharCode(...memoryU16.subarray(uint16StartPtr, uint16EndPtr));
30
+ }
31
+
32
+ //#endregion
33
+ //#region src/wasm-executor/wasm-memory.ts
34
+ const DEFAULT_MEMORY_REQS = {
35
+ testMemory: { initialPages: 1 },
36
+ coverageMemory: { initialPages: 1 }
37
+ };
38
+ const TEST_MEM_KEY = "env.memory";
39
+ const COVERAGE_MEM_KEY = `${"__as_pool_env__"}.${"__coverage_memory"}`;
40
+ /**
41
+ * Create a WebAssembly memory instance
42
+ * Used for imported memory pattern (matches --importMemory flag)
43
+ */
44
+ function createMemory(initialPages, maximumPages) {
45
+ return new WebAssembly.Memory({
46
+ initial: initialPages,
47
+ maximum: maximumPages
48
+ });
49
+ }
50
+ /**
51
+ * Decode AssemblyScript abort information
52
+ *
53
+ * Helper for handling abort() calls from AssemblyScript runtime.
54
+ * Decodes the error message and file path from WASM memory.
55
+ *
56
+ * @param memory - WebAssembly memory instance
57
+ * @param msgPtr - Pointer to error message string (or 0 if none)
58
+ * @param filePtr - Pointer to file path string (or 0 if none)
59
+ * @param line - Line number where abort occurred
60
+ * @param column - Column number where abort occurred
61
+ * @returns Decoded message and location (null if no meaningful location info)
62
+ */
63
+ function decodeAbortInfo(memory, msgPtr, filePtr, line, column) {
64
+ const errorMsg = liftString(memory, msgPtr) ?? "Unknown error";
65
+ const filePath = liftString(memory, filePtr);
66
+ return {
67
+ message: errorMsg,
68
+ location: filePath && filePath !== "unknown" && (line !== 0 || column !== 0) ? `${filePath}:${line}:${column}` : null
69
+ };
70
+ }
71
+ function getWasmMemoryRequirements(u8) {
72
+ if (u8[0] !== 0 || u8[1] !== 97 || u8[2] !== 115 || u8[3] !== 109) throw new Error("Not a valid WebAssembly binary");
73
+ const reqs = {
74
+ testMemory: { ...DEFAULT_MEMORY_REQS.testMemory },
75
+ coverageMemory: { ...DEFAULT_MEMORY_REQS.coverageMemory }
76
+ };
77
+ let offset = 8;
78
+ const decoder = new TextDecoder("utf-8");
79
+ function readVarUint() {
80
+ let result = 0;
81
+ let shift = 0;
82
+ while (true) {
83
+ const byte = u8[offset++];
84
+ result |= (byte & 127) << shift;
85
+ if ((byte & 128) === 0) break;
86
+ shift += 7;
87
+ }
88
+ return result;
89
+ }
90
+ while (offset < u8.length) {
91
+ const sectionId = u8[offset++];
92
+ const sectionLength = readVarUint();
93
+ const nextSectionOffset = offset + sectionLength;
94
+ if (sectionId === 2) {
95
+ const numImports = readVarUint();
96
+ for (let i = 0; i < numImports; i++) {
97
+ const modLen = readVarUint();
98
+ const modName = decoder.decode(u8.subarray(offset, offset + modLen));
99
+ offset += modLen;
100
+ const fieldLen = readVarUint();
101
+ const fieldName = decoder.decode(u8.subarray(offset, offset + fieldLen));
102
+ offset += fieldLen;
103
+ const kind = u8[offset++];
104
+ if (kind === 2) {
105
+ const flags = u8[offset++];
106
+ const initialPages = readVarUint();
107
+ const maximumPages = (flags & 1) === 1 ? readVarUint() : void 0;
108
+ const key = `${modName}.${fieldName}`;
109
+ if (key === TEST_MEM_KEY) reqs.testMemory = {
110
+ initialPages,
111
+ maximumPages
112
+ };
113
+ else if (key === COVERAGE_MEM_KEY) reqs.coverageMemory = {
114
+ initialPages,
115
+ maximumPages
116
+ };
117
+ } else if (kind === 0) readVarUint();
118
+ else if (kind === 1) {
119
+ offset++;
120
+ const flags = u8[offset++];
121
+ readVarUint();
122
+ if (flags & 1) readVarUint();
123
+ } else if (kind === 3) offset += 2;
124
+ }
125
+ return reqs;
126
+ }
127
+ offset = nextSectionOffset;
128
+ }
129
+ return reqs;
130
+ }
131
+
132
+ //#endregion
133
+ export { createMemory, decodeAbortInfo, getWasmMemoryRequirements, liftString };
134
+ //# sourceMappingURL=wasm-memory-C8Nkl2Sz.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wasm-memory-C8Nkl2Sz.mjs","names":[],"sources":["../src/util/assemblyscript/binding-helpers.ts","../src/wasm-executor/wasm-memory.ts"],"sourcesContent":["const STRING_EXTRACT_CHUNK_SIZE = 1024 as const;\n\n/**\n * Decode an AssemblyScript string from WASM memory, using the length stored at\n * the beginning of the string.\n *\n * This approach is borrowed from AssemblyScript with changes for clarity.\n * AssemblyScript is released under the Apache 2.0 license, included here.\n * \n * When a string argument crosses the boundary to JS, we get a pointer to the\n * string data in WASM memory. WASM strings store their length in the 4 bytes\n * before the string data pointer so we know how much to read from memory.\n *\n * @param memory - WebAssembly memory instance\n * @param pointer - Pointer to the start of the string\n * @returns Decoded string\n */\nexport function liftString(\n memory: WebAssembly.Memory,\n pointer: number,\n): string | undefined {\n if (!pointer) return undefined;\n\n const unsigned = pointer >>> 0;\n \n const lengthPtr = unsigned - 4;\n\n // convert byte-based lengthPtr to uint32-based index for Uint32Array\n // with: bytes / 4 (=== bytes >>> 2) and read length\n const uint32LengthPtr = lengthPtr >>> 2;\n const byteOffsetLength = new Uint32Array(memory.buffer)[uint32LengthPtr];\n\n if (byteOffsetLength === 0) return '';\n \n // calculate end pointer, and convert byte-based start and end pointers\n // to uint16-based indexes for Uint16Array with: bytes / 2 (=== bytes >>> 1) \n const uint16EndPtr = (unsigned + byteOffsetLength!) >>> 1;\n let uint16StartPtr = unsigned >>> 1;\n\n const memoryU16 = new Uint16Array(memory.buffer);\n let string = '';\n\n // extract in 1024-character chunks to avoid hitting spread operator limit\n while (uint16EndPtr - uint16StartPtr > STRING_EXTRACT_CHUNK_SIZE) {\n string += String.fromCharCode(\n ...memoryU16.subarray(uint16StartPtr, uint16StartPtr += STRING_EXTRACT_CHUNK_SIZE)\n );\n }\n\n return string + String.fromCharCode(...memoryU16.subarray(uint16StartPtr, uint16EndPtr));\n}\n","import {\n AS_POOL_WASM_COVERAGE_MEM_IMPORT_NAME,\n AS_POOL_WASM_IMPORTS_MODULE_NAME\n} from '../types/constants.js';\nimport type { WASMModuleMemoryRequirements } from '../types/types.js';\nimport { liftString } from '../util/assemblyscript/binding-helpers.js';\n\nconst DEFAULT_MEMORY_REQS: WASMModuleMemoryRequirements = {\n testMemory: { initialPages: 1 },\n coverageMemory: { initialPages: 1 }\n} as const;\nconst TEST_MEM_KEY = 'env.memory' as const;\nconst COVERAGE_MEM_KEY = `${AS_POOL_WASM_IMPORTS_MODULE_NAME}.${AS_POOL_WASM_COVERAGE_MEM_IMPORT_NAME}`;\n\n/**\n * Create a WebAssembly memory instance\n * Used for imported memory pattern (matches --importMemory flag)\n */\nexport function createMemory(initialPages: number, maximumPages?: number): WebAssembly.Memory {\n return new WebAssembly.Memory({ initial: initialPages, maximum: maximumPages });\n}\n\n/**\n * Decode AssemblyScript abort information\n *\n * Helper for handling abort() calls from AssemblyScript runtime.\n * Decodes the error message and file path from WASM memory.\n *\n * @param memory - WebAssembly memory instance\n * @param msgPtr - Pointer to error message string (or 0 if none)\n * @param filePtr - Pointer to file path string (or 0 if none)\n * @param line - Line number where abort occurred\n * @param column - Column number where abort occurred\n * @returns Decoded message and location (null if no meaningful location info)\n */\nexport function decodeAbortInfo(\n memory: WebAssembly.Memory,\n msgPtr: number,\n filePtr: number,\n line: number,\n column: number\n): { message: string; location: string | null } {\n const errorMsg = liftString(memory, msgPtr) ?? 'Unknown error'; \n const filePath = liftString(memory, filePtr);\n\n // Only include location if we have meaningful file info (not null/empty and not at 0:0)\n const hasLocation = filePath && filePath !== 'unknown' && (line !== 0 || column !== 0);\n const location = hasLocation ? `${filePath}:${line}:${column}` : null;\n\n return {\n message: errorMsg,\n location: location,\n };\n}\n\nexport function getWasmMemoryRequirements(u8: Uint8Array): WASMModuleMemoryRequirements {\n if (u8[0] !== 0x00 || u8[1] !== 0x61 || u8[2] !== 0x73 || u8[3] !== 0x6d) {\n throw new Error(\"Not a valid WebAssembly binary\");\n }\n\n const reqs: WASMModuleMemoryRequirements = {\n testMemory: { ...DEFAULT_MEMORY_REQS.testMemory },\n coverageMemory: { ...DEFAULT_MEMORY_REQS.coverageMemory }\n };\n\n let offset = 8;\n const decoder = new TextDecoder('utf-8');\n\n function readVarUint() {\n let result = 0;\n let shift = 0;\n while (true) {\n const byte = u8[offset++]!;\n result |= (byte & 0x7f) << shift;\n if ((byte & 0x80) === 0) break;\n shift += 7;\n }\n return result;\n }\n\n while (offset < u8.length) {\n const sectionId = u8[offset++];\n const sectionLength = readVarUint();\n const nextSectionOffset = offset + sectionLength;\n\n if (sectionId === 2) { // 2 = Import Section\n const numImports = readVarUint();\n\n for (let i = 0; i < numImports; i++) {\n // Extract and decode Module Name\n const modLen = readVarUint();\n const modName = decoder.decode(u8.subarray(offset, offset + modLen));\n offset += modLen;\n\n // Extract and decode Field/Memory Name\n const fieldLen = readVarUint();\n const fieldName = decoder.decode(u8.subarray(offset, offset + fieldLen));\n offset += fieldLen;\n\n const kind = u8[offset++];\n \n if (kind === 0x02) { // Memory Import\n const flags = u8[offset++];\n const initialPages = readVarUint();\n \n const hasMaximum = (flags! & 0x01) === 0x01;\n const maximumPages = hasMaximum ? readVarUint() : undefined;\n \n const key = `${modName}.${fieldName}`;\n if (key === TEST_MEM_KEY) {\n reqs.testMemory = { initialPages, maximumPages };\n } else if (key === COVERAGE_MEM_KEY) {\n reqs.coverageMemory = { initialPages, maximumPages }\n }\n } else if (kind === 0x00) { // Function\n readVarUint();\n } else if (kind === 0x01) { // Table\n offset++;\n const flags = u8[offset++];\n readVarUint();\n if (flags! & 1) readVarUint();\n } else if (kind === 0x03) { // Global\n offset += 2;\n }\n }\n // We can stop processing once the import section is completely parsed\n return reqs;\n }\n offset = nextSectionOffset;\n }\n return reqs; \n}\n"],"mappings":";AAAA,MAAM,4BAA4B;;;;;;;;;;;;;;;;AAiBlC,SAAgB,WACd,Q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URL=worker-rpc-channel-CZZIxtv5.mjs.map
25
+ //# sourceMappingURL=worker-rpc-channel-CvCrc8aa.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker-rpc-channel-CZZIxtv5.mjs","names":[],"sources":["../src/pool/worker-rpc-channel.ts"],"sourcesContent":["import { MessageChannel } from 'node:worker_threads';\nimport { createBirpc } from 'birpc';\nimport type { RunnerRPC, RuntimeRPC } from 'vitest';\nimport { type TestProject, createMethodsRPC } from 'vitest/node';\n\nimport type { WorkerChannel } from '../types/types.js';\n\n/**\n * Create a MessageChannel with RPC for worker thread communication\n */\nexport function createWorkerRPCChannel(project: TestProject, collect: boolean): WorkerChannel {\n const channel = new MessageChannel();\n const workerPort = channel.port1;\n const poolPort = channel.port2;\n\n const methods = createMethodsRPC(project, { collect });\n\n // Create RPC in pool\n const rpc = createBirpc<RuntimeRPC, RunnerRPC>(\n methods,\n {\n post: (v) => poolPort.postMessage(v),\n on: (fn) => poolPort.on('message', fn),\n }\n );\n\n return { workerPort, poolPort, rpc };\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,uBAAuB,SAAsB,SAAiC;CAC5F,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,aAAa,QAAQ;CAC3B,MAAM,WAAW,QAAQ;AAazB,QAAO;EAAE;EAAY;EAAU,KARnB,YAHI,iBAAiB,SAAS,EAAE,SAAS,CAAC,EAKpD;GACE,OAAO,MAAM,SAAS,YAAY,EAAE;GACpC,KAAK,OAAO,SAAS,GAAG,WAAW,GAAG;GACvC,CACF;EAEmC"}
1
+ {"version":3,"file":"worker-rpc-channel-CvCrc8aa.mjs","names":[],"sources":["../src/pool/worker-rpc-channel.ts"],"sourcesContent":["import { MessageChannel } from 'node:worker_threads';\nimport { createBirpc } from 'birpc';\nimport type { RunnerRPC, RuntimeRPC } from 'vitest';\nimport { type TestProject, createMethodsRPC } from 'vitest/node';\n\nimport type { WorkerChannel } from '../types/types.js';\n\n/**\n * Create a MessageChannel with RPC for worker thread communication\n */\nexport function createWorkerRPCChannel(project: TestProject, collect: boolean): WorkerChannel {\n const channel = new MessageChannel();\n const workerPort = channel.port1;\n const poolPort = channel.port2;\n\n const methods = createMethodsRPC(project, { collect });\n\n // Create RPC in pool\n const rpc = createBirpc<RuntimeRPC, RunnerRPC>(\n methods,\n {\n post: (v) => poolPort.postMessage(v),\n on: (fn) => poolPort.on('message', fn),\n }\n );\n\n return { workerPort, poolPort, rpc };\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,uBAAuB,SAAsB,SAAiC;CAC5F,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,aAAa,QAAQ;CAC3B,MAAM,WAAW,QAAQ;AAazB,QAAO;EAAE;EAAY;EAAU,KARnB,YAHI,iBAAiB,SAAS,EAAE,SAAS,CAAC,EAKpD;GACE,OAAO,MAAM,SAAS,YAAY,EAAE;GACpC,KAAK,OAAO,SAAS,GAAG,WAAW,GAAG;GACvC,CACF;EAEmC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest-pool-assemblyscript",
3
- "version": "0.9.1",
3
+ "version": "0.10.1",
4
4
  "description": "AssemblyScript testing with Vitest - Simple, fast, familiar, AS-native, with full coverage output",
5
5
  "author": "Matt Ritter <matthew.d.ritter@gmail.com>",
6
6
  "license": "MIT",
@@ -25,10 +25,10 @@
25
25
  using namespace wasm;
26
26
 
27
27
  // 32
28
- const uint32_t BYTES_PER_COUNTER = 4;
28
+ const int32_t BYTES_PER_COUNTER = 4;
29
29
 
30
30
  // 1 page = 64KB / 4bytes (32bits) each = 16384 counters
31
- const uint32_t COUNTERS_PER_PAGE = 16384;
31
+ const int32_t COUNTERS_PER_PAGE = 16384;
32
32
 
33
33
  // TODO - pass these through the call stack as params instead
34
34
  // for now we don't expect them to change between different calls
@@ -38,9 +38,9 @@ thread_local std::string LOG_PREFIX = "InstNative";
38
38
 
39
39
  struct SourceDebugLocation {
40
40
  bool exists = false;
41
- uint32_t fileIndex = 0; // Debug location file index
42
- uint32_t lineNumber = 0; // Debug location line number
43
- uint32_t columnNumber = 0; // Debug location column number
41
+ int32_t fileIndex = 0; // Debug location file index
42
+ int32_t lineNumber = 0; // Debug location line number
43
+ int32_t columnNumber = 0; // Debug location column number
44
44
  };
45
45
 
46
46
  /**
@@ -48,12 +48,12 @@ struct SourceDebugLocation {
48
48
  */
49
49
  struct ExpressionInfo {
50
50
  std::string type; // Expression type name
51
- uint32_t fileIndex; // Debug location file index
52
- uint32_t lineNumber; // Debug location line number
53
- uint32_t columnNumber; // Debug location column number
51
+ int32_t fileIndex; // Debug location file index
52
+ int32_t lineNumber; // Debug location line number
53
+ int32_t columnNumber; // Debug location column number
54
54
  bool hasDebugLocation; // Whether debug location exists
55
55
  bool isBranch; // Whether this is a branch expression
56
- uint32_t branchPaths; // Number of branch paths (if isBranch)
56
+ int32_t branchPaths; // Number of branch paths (if isBranch)
57
57
  };
58
58
 
59
59
  /**
@@ -67,7 +67,7 @@ struct BasicBlockInfo {
67
67
  // Data structure to collect function info during instrumentation
68
68
  struct FunctionInfo {
69
69
  std::string name;
70
- uint32_t coverageMemoryIndex;
70
+ int32_t coverageMemoryIndex;
71
71
  SourceDebugLocation representativeLocation;
72
72
  std::vector<ExpressionInfo> expressions;
73
73
  std::vector<BasicBlockInfo> blocks;
@@ -437,12 +437,16 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
437
437
  std::string excludedLibraryFilePrefix;
438
438
  std::string excludedLibraryFileOverridePrefix = "";
439
439
  std::string excludedInternalFunctionSubstring = "";
440
+ std::string coverageMemoryModule = "";
441
+ std::string coverageMemoryName = "";
440
442
 
441
443
  // 1 page = 64KB / 4bytes (32bits) each = 16384 counters
442
- uint32_t coverageMemoryPagesMin = 1;
444
+ int32_t coverageMemoryPagesMin = 1;
443
445
  // 4 pages = 256KB / 4bytes (32bits) each = 65536 counters
444
- uint32_t coverageMemoryPagesMax = 4;
445
- uint32_t maxCounters = coverageMemoryPagesMax * COUNTERS_PER_PAGE;
446
+ int32_t coverageMemoryPagesMax = -1;
447
+
448
+ // computed values
449
+ int32_t maxCounters = coverageMemoryPagesMax == -1 ? -1 : coverageMemoryPagesMax * COUNTERS_PER_PAGE;
446
450
 
447
451
  if (options.Has("logPrefix")) {
448
452
  Napi::Value logPrefixProp = options.Get("logPrefix");
@@ -467,14 +471,14 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
467
471
  if (excludedFilesProperty.IsArray()) {
468
472
  const Napi::Array filesArray = excludedFilesProperty.As<Napi::Array>();
469
473
 
470
- const uint32_t count = filesArray.Length();
474
+ const int32_t count = filesArray.Length();
471
475
  if (DEBUG && count > 0) {
472
476
  std::cout << LOG_PREFIX << " - OPTIONS - " << count << " Excluded Files:" << std::endl;
473
477
  } else if (DEBUG) {
474
478
  std::cout << LOG_PREFIX << " - 0 Excluded Files" << std::endl;
475
479
  }
476
480
 
477
- for (size_t i = 0; i < count; i++) {
481
+ for (int32_t i = 0; i < count; i++) {
478
482
  Napi::Value fileItem = filesArray[i];
479
483
  if (fileItem.IsString()) {
480
484
  const std::string file = fileItem.As<Napi::String>().Utf8Value();
@@ -526,7 +530,7 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
526
530
  coverageMemoryPagesMin = coverageMinProperty.As<Napi::Number>().Int32Value();
527
531
 
528
532
  if (DEBUG) {
529
- const uint32_t minCounters = coverageMemoryPagesMin * COUNTERS_PER_PAGE;
533
+ const int32_t minCounters = coverageMemoryPagesMin * COUNTERS_PER_PAGE;
530
534
  std::cout << LOG_PREFIX << " - OPTIONS - Coverage Memory Pages MIN: " << coverageMemoryPagesMin
531
535
  << " (" << minCounters << " counters)" << std::endl;
532
536
  }
@@ -546,6 +550,28 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
546
550
  }
547
551
  }
548
552
 
553
+ if (options.Has("coverageMemoryModule")) {
554
+ Napi::Value coverageMemoryModuleProperty = options.Get("coverageMemoryModule");
555
+ if (coverageMemoryModuleProperty.IsString()) {
556
+ coverageMemoryModule = coverageMemoryModuleProperty.As<Napi::String>().Utf8Value();
557
+
558
+ if (DEBUG) {
559
+ std::cout << LOG_PREFIX << " - OPTIONS - Coverage Memory Module: \"" << coverageMemoryModule << "\"" << std::endl;
560
+ }
561
+ }
562
+ }
563
+
564
+ if (options.Has("coverageMemoryName")) {
565
+ Napi::Value coverageMemoryNameProperty = options.Get("coverageMemoryName");
566
+ if (coverageMemoryNameProperty.IsString()) {
567
+ coverageMemoryName = coverageMemoryNameProperty.As<Napi::String>().Utf8Value();
568
+
569
+ if (DEBUG) {
570
+ std::cout << LOG_PREFIX << " - OPTIONS - Coverage Memory Name: \"" << coverageMemoryName << "\"" << std::endl;
571
+ }
572
+ }
573
+ }
574
+
549
575
  std::vector<char> wasmData(wasmBuf.Data(), wasmBuf.Data() + wasmBuf.Length());
550
576
  std::vector<char> sourceMapData(sourceMapBuf.Data(), sourceMapBuf.Data() + sourceMapBuf.Length());
551
577
 
@@ -565,22 +591,14 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
565
591
 
566
592
  // Instrument functions and collect debug info
567
593
  Builder builder(module);
568
- uint32_t coverageIndex = 0;
594
+ int32_t coverageIndex = 0;
569
595
  std::vector<FunctionInfo> instrumentedFunctions;
570
596
 
571
597
  // Enable multi-memory feature for coverage memory
572
598
  module.features.setMultiMemory(true);
573
599
 
574
- // Add __coverage_memory import
575
- // This is a secondary memory used to store coverage counters
576
- Name coverageMemoryName("__coverage_memory");
577
- auto coverageMemory = Builder::makeMemory(coverageMemoryName);
578
- coverageMemory->module = "__as_pool_env__";
579
- coverageMemory->base = "__coverage_memory";
580
- coverageMemory->initial = coverageMemoryPagesMin;
581
- coverageMemory->max = coverageMemoryPagesMax;
582
- coverageMemory->shared = false;
583
- module.addMemory(std::move(coverageMemory));
600
+ // secondary memory import used to store coverage counters
601
+ const Name coverageMemoryWasmName(coverageMemoryName);
584
602
 
585
603
  // Create walker for debug info extraction
586
604
  DebugInfoWalker walker(&module);
@@ -588,10 +606,10 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
588
606
  ModuleUtils::iterDefinedFunctions(module, [&](Function* func) {
589
607
  std::string funcName = func->name.toString();
590
608
 
591
- if (coverageIndex >= maxCounters) {
609
+ if (maxCounters > 0 && coverageIndex >= maxCounters) {
592
610
  if (DEBUG) {
593
611
  std::cout << LOG_PREFIX << " - ERROR: Processing function: \"" << funcName << "\""
594
- << " Further instrumentation would exceed max covergare memory size" << std::endl;
612
+ << " Further instrumentation would exceed max coverage memory size" << std::endl;
595
613
  }
596
614
  return;
597
615
  }
@@ -658,7 +676,7 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
658
676
  // incremented = counter + 1
659
677
  // i32.store(addr, incremented, __coverage_memory)
660
678
 
661
- const uint32_t counterAddressVal = coverageIndex * BYTES_PER_COUNTER;
679
+ const int32_t counterAddressVal = coverageIndex * BYTES_PER_COUNTER;
662
680
  Expression* counterAddress = builder.makeConstantExpression(Literal(counterAddressVal));
663
681
 
664
682
  // Load current counter value
@@ -669,7 +687,7 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
669
687
  BYTES_PER_COUNTER, // align - we should always be aligned
670
688
  counterAddress, // address
671
689
  Type::i32,
672
- coverageMemoryName
690
+ coverageMemoryWasmName
673
691
  );
674
692
 
675
693
  // Increment counter
@@ -686,7 +704,7 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
686
704
  counterAddress, // address
687
705
  incrementedCounter, // value
688
706
  Type::i32,
689
- coverageMemoryName
707
+ coverageMemoryWasmName
690
708
  );
691
709
 
692
710
  // Prepend instrumentation to function body
@@ -701,6 +719,27 @@ Napi::Object InstrumentForCoverage(const Napi::CallbackInfo& info) {
701
719
  coverageIndex++;
702
720
  });
703
721
 
722
+ int32_t requiredCoverageMemoryPagesMax = std::ceil(coverageIndex / static_cast<double>(COUNTERS_PER_PAGE));
723
+
724
+ // Add __coverage_memory import
725
+ auto coverageMemory = Builder::makeMemory(coverageMemoryWasmName);
726
+ coverageMemory->module = coverageMemoryModule;
727
+ coverageMemory->base = coverageMemoryName;
728
+ coverageMemory->shared = false;
729
+ coverageMemory->initial = coverageMemoryPagesMin;
730
+
731
+ if (coverageMemoryPagesMax <= 0) {
732
+ coverageMemory->max = requiredCoverageMemoryPagesMax <= 0 ? 1 : requiredCoverageMemoryPagesMax;
733
+ } else {
734
+ coverageMemory->max = coverageMemoryPagesMax;
735
+ }
736
+
737
+ if (DEBUG) {
738
+ std::cout << LOG_PREFIX << " - Coverage memory max pages set to: " << coverageMemory->max << std::endl;
739
+ }
740
+
741
+ module.addMemory(std::move(coverageMemory));
742
+
704
743
  if (DEBUG) {
705
744
  std::cout << LOG_PREFIX << " - Instrumentation complete: " << coverageIndex << " functions instrumented" << std::endl;
706
745
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"addon-interface-CYFXMbK7.mjs","names":[],"sources":["../src/instrumentation/addon-interface.ts"],"sourcesContent":["/**\n * Native addon interface for extracting debug information from WebAssembly binaries\n *\n * This module wraps Binaryen's C++ API to provide expression-level debug locations\n * and basic block information that the JavaScript API doesn't expose.\n *\n * The native addon outputs raw data (0-based columns, relative paths) which this\n * wrapper transforms into the final BinaryDebugInfo format (1-based columns,\n * absolute paths, grouped by file and position).\n */\n\nimport { createRequire } from 'node:module';\nimport { resolve, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type {\n NativeAddon,\n NativeInstrumentationResult,\n NativeDebugInfoOutput,\n NativeFunctionDebugInfo,\n NativeExpressionDebugInfo,\n NativeSourceLocation,\n BinaryDebugInfo,\n FunctionDebugInfo,\n SourceLocation,\n ExpressionDebugInfo,\n InstrumentationResult,\n NativeInstrumentationOptions,\n InstrumentationOptions,\n InstrumentForCoverageFunc,\n} from '../types/types.js';\nimport {\n POOL_ERROR_NAMES,\n INTERNAL_PATH_LIB_PREFIX,\n} from '../types/constants.js';\nimport { debug } from '../util/debug.js';\nimport { toForwardSlash } from '../util/path-utils.js';\nimport { createPoolError } from '../util/pool-errors.js';\nimport { getShortFunctionName } from '../wasm-executor/wasm-names.js';\n\n// Load the native addon via node-gyp-build\n// node-gyp-build checks: prebuilds/ first, then build/Release/\n// It searches from the given directory for a package.json to find the package root.\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst rootFromDist = resolve(__dirname, '..');\n// TODO: Verify if this src fallback is still needed — pool always runs from dist/ even locally.\n// If confirmed dead code, remove this and simplify to a single nodeGypBuild call.\nconst rootFromSrc = resolve(__dirname, '../..');\n\nconst require = createRequire(import.meta.url);\nconst nodeGypBuild: (dir: string) => NativeAddon = require('node-gyp-build');\n\nlet addon: NativeAddon;\ntry {\n addon = nodeGypBuild(rootFromDist);\n} catch {\n try {\n addon = nodeGypBuild(rootFromSrc);\n } catch (err) {\n throw createPoolError(\n `vitest-pool-assemblyscript native instrumentation addon not found. Searched from ${rootFromDist} and ${rootFromSrc}. `\n + `Ensure prebuilds are available or run 'node node_modules/vitest-pool-assemblyscript/scripts/install-native-addon.js'`\n + ` to compile from source. Original error: ${err instanceof Error ? err.message : String(err)}`,\n POOL_ERROR_NAMES.WASMInstrumentationError\n );\n }\n}\n\n/**\n * Convert a raw location (0-indexed columns, path indexes) to\n * processed location (1-indexed columns, absolute path strings)\n *\n * Source map paths vary by import style and project structure:\n * - Relative imports: \"assembly/compare.ts\"\n * - Bare package imports: \"~lib/vitest-pool-assemblyscript/assembly/compare.ts\"\n * - Source outside project root: \"../assembly/compare.ts\" (e.g. test-external importing parent sources)\n *\n * All are normalized to absolute filesystem paths for consistent coverage key matching.\n */\nfunction convertLocation(\n rawLocation: NativeSourceLocation,\n debugSourceFiles: string[],\n projectRoot: string\n): SourceLocation {\n let filePath = debugSourceFiles[rawLocation.fileIndex];\n\n if (!filePath) {\n throw createPoolError(\n `No debug source file with index: ${rawLocation.fileIndex}}`,\n POOL_ERROR_NAMES.WASMInstrumentationError\n );\n }\n\n // Normalize to absolute path for consistent coverage key matching\n if (filePath.startsWith(INTERNAL_PATH_LIB_PREFIX)) {\n // ~lib/vitest-pool-assemblyscript/assembly/X.ts -> projectRoot/assembly/X.ts\n const relativePart = filePath.slice(INTERNAL_PATH_LIB_PREFIX.length);\n filePath = toForwardSlash(resolve(projectRoot, 'assembly', relativePart));\n } else {\n // Resolve relative path (handles both 'assembly/X.ts' and '../assembly/X.ts')\n filePath = toForwardSlash(resolve(projectRoot, filePath));\n }\n\n return {\n filePath,\n line: rawLocation.line,\n column: rawLocation.column + 1, // convert from 0-indexed to 1-indexed\n };\n}\n\n/**\n * Convert a raw expression to processed format\n */\nfunction convertExpression(\n rawExpr: NativeExpressionDebugInfo,\n debugSourceFiles: string[],\n projectRoot: string\n): ExpressionDebugInfo {\n const converted: ExpressionDebugInfo = {\n type: rawExpr.type,\n isBranch: rawExpr.isBranch,\n };\n\n if (rawExpr.branchPaths !== undefined) {\n converted.branchPaths = rawExpr.branchPaths;\n }\n\n if (rawExpr.location) {\n const convertedLocation = convertLocation(rawExpr.location, debugSourceFiles, projectRoot);\n if (convertedLocation) {\n converted.location = convertedLocation;\n }\n }\n\n return converted;\n}\n\n/**\n * Generate a position key to identify the SourceLocation uniquely\n * within a file. Does NOT include the file identifier.\n */\nfunction getPositionKey(location: SourceLocation) {\n return `${location.line}:${location.column}`;\n}\n\n/**\n * Convert a raw function to processed format and compute position key\n * Returns undefined if function has no valid representative location\n */\nfunction convertFunction(\n rawFunc: NativeFunctionDebugInfo,\n debugSourceFiles: string[],\n projectRoot: string\n): { func: FunctionDebugInfo; filePath: string; positionKey: string } | undefined {\n const representativeLocation = convertLocation(rawFunc.representativeLocation, debugSourceFiles, projectRoot);\n\n // Convert expressions\n const expressions: ExpressionDebugInfo[] = [];\n if (rawFunc.expressions) {\n for (const expr of rawFunc.expressions) {\n expressions.push(convertExpression(expr, debugSourceFiles, projectRoot));\n }\n }\n\n const converted: FunctionDebugInfo = {\n wasmIndex: rawFunc.wasmIndex,\n name: rawFunc.name,\n representativeLocation,\n coverageMemoryIndex: rawFunc.coverageMemoryIndex,\n expressions,\n basicBlocks: rawFunc.basicBlocks,\n };\n\n const filePath = representativeLocation.filePath;\n const positionKey = getPositionKey(representativeLocation);\n\n return { func: converted, filePath, positionKey };\n}\n\n/**\n * Check if two WASM function names are monomorphizations of the same generic function.\n * Generic monomorphizations share the same base name and suffix, differing only in\n * the type parameters inside angle brackets.\n *\n * e.g. \"assembly/compare/closeTo<bool\\2cbool>\" and \"assembly/compare/closeTo<bool\\2cu8>\"\n * e.g. \"assembly/expect/BaseExpectMatcher<bool>#constructor\" and \"assembly/expect/BaseExpectMatcher<i8>#constructor\"\n */\nfunction isGenericMonomorphizationMatch(nameA: string, nameB: string): boolean {\n const openA = nameA.indexOf('<');\n const openB = nameB.indexOf('<');\n\n // Both must contain generic type parameters\n if (openA === -1 || openB === -1) return false;\n\n const lastCloseA = nameA.lastIndexOf('>');\n const lastCloseB = nameB.lastIndexOf('>');\n\n if (lastCloseA === -1 || lastCloseB === -1) return false;\n\n // Prefix before '<' must match (includes module path, class, function name)\n const prefixA = nameA.substring(0, openA);\n const prefixB = nameB.substring(0, openB);\n if (prefixA !== prefixB) return false;\n\n // Suffix after last '>' must match (e.g. \"#constructor\", or empty)\n const suffixA = nameA.substring(lastCloseA + 1);\n const suffixB = nameB.substring(lastCloseB + 1);\n if (suffixA !== suffixB) return false;\n\n return true;\n}\n\n/**\n * Transform raw native addon output to processed BinaryDebugInfo\n */\nfunction transformDebugInfo(\n raw: NativeDebugInfoOutput,\n logPrefix: string,\n projectRoot: string,\n): BinaryDebugInfo {\n const functionsByFileAndPosition: Record<string, Record<string, FunctionDebugInfo[]>> = {};\n\n debug(`${logPrefix} - Converting ${raw.functions.length} functions`);\n\n let genericCollisionCount = 0;\n let skippedCount = 0;\n let instrumentedFunctionCount = 0;\n\n for (const rawFunc of raw.functions) {\n const result = convertFunction(rawFunc, raw.debugSourceFiles, projectRoot);\n if (!result) {\n debug(`${logPrefix} - WARNING: Skipped function (bad conversion): \"${rawFunc.name}\"`);\n skippedCount++;\n continue;\n }\n\n const { func, filePath, positionKey } = result;\n\n // Check for position collisions\n const existingAtPosition = functionsByFileAndPosition[filePath]?.[positionKey];\n if (existingAtPosition) {\n const existingName = existingAtPosition[0]!.name;\n\n // Only allow collision if both are monomorphizations of the same generic\n if (isGenericMonomorphizationMatch(existingName, func.name)) {\n existingAtPosition.push(func);\n genericCollisionCount++;\n instrumentedFunctionCount++;\n debug(\n `${logPrefix} - Generic monomorphization at ${filePath}:${positionKey}:`\n + ` \"${getShortFunctionName(func.name)}\" grouped with \"${getShortFunctionName(existingName)}\"`\n );\n continue;\n }\n\n throw createPoolError(\n `ERROR - Function Debug Position Collision at ${filePath}:${positionKey}: \"${getShortFunctionName(existingName)}\"`\n + ` will be replaced by \"${getShortFunctionName(func.name)}\". This is a bug. Please report it at:`\n + ` https://github.com/themattspiral/vitest-pool-assemblyscript/issues/new`,\n POOL_ERROR_NAMES.WASMInstrumentationError\n );\n }\n\n instrumentedFunctionCount++;\n\n // Group by file and position\n if (!functionsByFileAndPosition[filePath]) {\n functionsByFileAndPosition[filePath] = {};\n }\n\n functionsByFileAndPosition[filePath][positionKey] = [func];\n }\n\n debug(\n `${logPrefix} - BinaryDebugInfo transform complete: ${instrumentedFunctionCount} instrumented functions`\n + ` (${genericCollisionCount} generic collisions, ${skippedCount} skipped)`\n );\n\n return {\n debugSourceFiles: raw.debugSourceFiles,\n functionsByFileAndPosition,\n instrumentedFunctionCount,\n };\n}\n\n/**\n * Instrument a WASM binary for coverage collection and regenerate source map\n *\n * This function:\n * 1. Adds __coverage_memory import (multi-memory for coverage counters)\n * 2. Injects coverage counter increments at each function entry\n * 3. Regenerates source map with correct offsets after instrumentation\n * 4. Extracts debug info with coverageMemoryIndex assigned\n *\n * @param wasmBuffer - Buffer containing the clean WASM binary\n * @param sourceMapBuffer - Buffer containing the source map JSON\n * @returns Instrumented binary, regenerated source map, and debug info\n *\n * @throws {TypeError} If wasmBuffer or sourceMapBuffer are not Buffers\n * @throws {Error} If WASM binary or source map is invalid\n */\nexport const instrumentForCoverage: InstrumentForCoverageFunc = (\n wasmBuffer: Buffer,\n sourceMapBuffer: Buffer,\n instrumentationOptions: InstrumentationOptions,\n logModule: string,\n logLabel: string,\n): InstrumentationResult => {\n if (!Buffer.isBuffer(wasmBuffer)) {\n throw createPoolError(\n 'instrumentForCoverage - wasmBuffer must be a Buffer',\n POOL_ERROR_NAMES.WASMInstrumentationError\n );\n }\n if (!Buffer.isBuffer(sourceMapBuffer)) {\n throw createPoolError(\n 'instrumentForCoverage - sourceMapBuffer must be a Buffer',\n POOL_ERROR_NAMES.WASMInstrumentationError\n );\n }\n\n const interfaceLogPrefix = `[${logModule} Inst] ${logLabel}`;\n const nativeLogPrefix = `[${logModule} InstNative] ${logLabel}`;\n\n debug(`${interfaceLogPrefix} - Calling native instrumentForCoverage`);\n const startTime = performance.now();\n\n const options: NativeInstrumentationOptions = {\n coverageMemoryPagesMin: instrumentationOptions.coverageMemoryPagesMin,\n coverageMemoryPagesMax: instrumentationOptions.coverageMemoryPagesMax,\n excludedFiles: instrumentationOptions.relativeExcludedFiles,\n excludedLibraryFilePrefix: instrumentationOptions.excludedLibraryFilePrefix,\n excludedLibraryFileOverridePrefix: instrumentationOptions.excludedLibraryFileOverridePrefix,\n excludedInternalFunctionSubstring: instrumentationOptions.excludedInternalFunctionSubstring,\n debug: instrumentationOptions.debug,\n logPrefix: nativeLogPrefix\n };\n const nativeResult: NativeInstrumentationResult = addon.instrumentForCoverage(wasmBuffer, sourceMapBuffer, options);\n const addonTime = performance.now();\n debug(`${interfaceLogPrefix} - TIMING Native addon: ${(addonTime - startTime).toFixed(2)} ms`);\n\n if (nativeResult.errors?.length) {\n throw createPoolError(\n `Errors encountered duriing native instrumentation: ${nativeResult.errors.join('\\n')}`,\n POOL_ERROR_NAMES.WASMInstrumentationError,\n );\n }\n\n const debugInfo = transformDebugInfo(nativeResult.debugInfo, interfaceLogPrefix, instrumentationOptions.projectRoot);\n \n const transformTime = performance.now();\n debug(`${interfaceLogPrefix} - TIMING DebugInfo Transform: ${(transformTime - addonTime).toFixed(2)} ms`);\n debug(`${interfaceLogPrefix} - Binary size: ${nativeResult.instrumentedWasm.length} bytes | Source map size: ${nativeResult.sourceMap.length * 2} bytes`);\n\n return {\n instrumentedWasm: nativeResult.instrumentedWasm,\n sourceMap: nativeResult.sourceMap,\n debugInfo,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4CA,MAAM,YAAY,QADC,cAAc,OAAO,KAAK,IAAI,CACZ;AACrC,MAAM,eAAe,QAAQ,WAAW,KAAK;AAG7C,MAAM,cAAc,QAAQ,WAAW,QAAQ;AAG/C,MAAM,eADU,cAAc,OAAO,KAAK,IAAI,CACa,iBAAiB;AAE5E,IAAI;AACJ,IAAI;AACF,SAAQ,aAAa,aAAa;QAC5B;AACN,KAAI;AACF,UAAQ,aAAa,YAAY;UAC1B,KAAK;AACZ,QAAM,gBACJ,oFAAoF,aAAa,OAAO,YAAY,iKAEtE,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,IAC9F,iBAAiB,yBAClB;;;;;;;;;;;;;;AAeL,SAAS,gBACP,aACA,kBACA,aACgB;CAChB,IAAI,WAAW,iBAAiB,YAAY;AAE5C,KAAI,CAAC,SACH,OAAM,gBACJ,oCAAoC,YAAY,UAAU,IAC1D,iBAAiB,yBAClB;AAIH,KAAI,SAAS,WAAW,yBAAyB,CAG/C,YAAW,eAAe,QAAQ,aAAa,YAD1B,SAAS,MAAM,yBAAyB,OAAO,CACI,CAAC;KAGzE,YAAW,eAAe,QAAQ,aAAa,SAAS,CAAC;AAG3D,QAAO;EACL;EACA,MAAM,YAAY;EAClB,QAAQ,YAAY,SAAS;EAC9B;;;;;AAMH,SAAS,kBACP,SACA,kBACA,aACqB;CACrB,MAAM,YAAiC;EACrC,MAAM,QAAQ;EACd,UAAU,QAAQ;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,kBAAkB,IAAI,UAAU,eAAe;AAErD,OAAM,GAAG,mBAAmB,yCAAyC;CACrE,MAAM,YAAY,YAAY,KAAK;CAEnC,MAAM,UAAwC;EAC5C,wBAAwB,uBAAuB;EAC/C,wBAAwB,uBAAuB;EAC/C,eAAe,uBAAuB;EACtC,2BAA2B,uBAAuB;EAClD,mCAAmC,uBAAuB;EAC1D,mCAAmC,uBAAuB;EAC1D,OAAO,uBAAuB;EAC9B,WAAW;EACZ;CACD,MAAM,eAA4C,MAAM,sBAAsB,YAAY,iBAAiB,QAAQ;CACnH,MAAM,YAAY,YAAY,KAAK;AACnC,OAAM,GAAG,mBAAmB,2BAA2B,YAAY,WAAW,QAAQ,EAAE,CAAC,KAAK;AAE9F,KAAI,aAAa,QAAQ,OACvB,OAAM,gBACJ,sDAAsD,aAAa,OAAO,KAAK,KAAK,IACpF,iBAAiB,yBAClB;CAGH,MAAM,YAAY,mBAAmB,aAAa,WAAW,oBAAoB,uBAAuB,YAAY;AAGpH,OAAM,GAAG,mBAAmB,kCADN,YAAY,KAAK,GACuC,WAAW,QAAQ,EAAE,CAAC,KAAK;AACzG,OAAM,GAAG,mBAAmB,kBAAkB,aAAa,iBAAiB,OAAO,4BAA4B,aAAa,UAAU,SAAS,EAAE,QAAQ;AAEzJ,QAAO;EACL,kBAAkB,aAAa;EAC/B,WAAW,aAAa;EACxB;EACD"}
@@ -1,85 +0,0 @@
1
- import { INTERNAL_PATH_LIB_PREFIX, POOL_ERROR_NAMES, POOL_INTERNAL_PATHS } from "./constants-DbxJ3hzg.mjs";
2
- import { createPoolErrorFromAnyError, debug, getTestErrorFromPoolError } from "./debug-DtRAL4rM.mjs";
3
- import { toForwardSlash } from "./path-utils-t9OzjXYF.mjs";
4
- import { failFile, getFullTaskHierarchy, prepareFileTaskForCollection } from "./vitest-file-tasks-D8sOClGX.mjs";
5
- import { getTaskLogLabel, getTaskLogPrefix } from "./vitest-tasks-BZ24sghI.mjs";
6
- import { executeWASMDiscovery, flushRpcUpdates, reportFileCollected, reportFileError, reportFileQueued, reportUserConsoleLogs } from "./load-user-imports-Bx5ZlhSm.mjs";
7
- import { compileAssemblyScript } from "./compiler-Dqs-qd3I.mjs";
8
- import { basename, relative } from "node:path";
9
-
10
- //#region src/pool-thread/runner/compile-runner.ts
11
- /**
12
- * Worker thread test runner logic for AssemblyScript Pool
13
- */
14
- let threadCompilationCount = 0;
15
- async function runCompileAndDiscover(file, logModule, rpc, poolOptions, projectRoot, collectCoverage, relativeUserCoverageExclusions, threadImports, diffOptions, testNamePattern, allowOnly) {
16
- const base = basename(file.filepath);
17
- const fileLogPrefix = getTaskLogPrefix(logModule, base, file);
18
- const fileLogLabel = getTaskLogLabel(base, file);
19
- debug(`${fileLogPrefix} - Beginning runCompileAndDiscover for "${file.filepath}" at ${Date.now()}`);
20
- const runStart = performance.now();
21
- let compilation;
22
- try {
23
- await reportFileQueued(rpc, file, logModule, fileLogLabel);
24
- const instrumentationOptions = {
25
- projectRoot,
26
- relativeExcludedFiles: [
27
- toForwardSlash(relative(projectRoot, file.filepath)),
28
- ...poolOptions._instrumentPoolInternals ? [] : POOL_INTERNAL_PATHS,
29
- ...relativeUserCoverageExclusions
30
- ],
31
- excludedLibraryFilePrefix: "~lib/",
32
- excludedLibraryFileOverridePrefix: poolOptions._instrumentPoolInternals ? INTERNAL_PATH_LIB_PREFIX : void 0,
33
- excludedInternalFunctionSubstring: "__vitest_assemblyscript_",
34
- coverageMemoryPagesMin: poolOptions.coverageMemoryPagesInitial,
35
- coverageMemoryPagesMax: poolOptions.coverageMemoryPagesMax,
36
- debug: poolOptions.debugNative
37
- };
38
- const compilerOptions = {
39
- stripInline: poolOptions.stripInline,
40
- projectRoot,
41
- shouldInstrument: collectCoverage,
42
- instrumentationOptions,
43
- extraFlags: poolOptions.extraCompilerFlags
44
- };
45
- const { binary, sourceMap, debugInfo, compileTiming } = await compileAssemblyScript(file.filepath, compilerOptions, logModule, fileLogLabel);
46
- file.setupDuration = compileTiming;
47
- threadCompilationCount++;
48
- debug(`${fileLogPrefix} - TIMING compileAssemblyScript total (thread comp # ${threadCompilationCount}): ${compileTiming.toFixed(2)} ms`);
49
- const logMessages = [];
50
- const handleLog = (msg, isError = false) => {
51
- logMessages.push({
52
- msg,
53
- time: Date.now(),
54
- isError
55
- });
56
- };
57
- const discoverStart = performance.now();
58
- await executeWASMDiscovery(binary, sourceMap, base, poolOptions, collectCoverage, handleLog, file, logModule, threadImports, diffOptions);
59
- prepareFileTaskForCollection(file, testNamePattern, allowOnly);
60
- file.collectDuration = performance.now() - discoverStart;
61
- debug(`${fileLogPrefix} - TIMING Discovery Phase: ${file.collectDuration.toFixed(2)} ms`);
62
- await Promise.all([reportUserConsoleLogs(rpc, logMessages, logModule, base, file), reportFileCollected(rpc, file, logModule, fileLogLabel)]);
63
- debug(() => `${fileLogPrefix} - Collected Test Suite Hierarchy:\n${getFullTaskHierarchy(file)}`);
64
- debug(`${fileLogPrefix} - TIMING Compilation and Discovery: ${(performance.now() - runStart).toFixed(2)} ms`);
65
- compilation = {
66
- filePath: file.filepath,
67
- binary,
68
- sourceMap,
69
- debugInfo
70
- };
71
- } catch (error) {
72
- failFile(file, getTestErrorFromPoolError(createPoolErrorFromAnyError(`${fileLogLabel} - runCompileAndDiscover failure in worker`, POOL_ERROR_NAMES.WASMExecutionHarnessError, error)), runStart);
73
- await reportFileQueued(rpc, file, logModule, fileLogLabel);
74
- await reportFileError(rpc, file, logModule, fileLogLabel);
75
- debug(`${fileLogPrefix} - Reported file error`);
76
- } finally {
77
- await flushRpcUpdates(rpc);
78
- debug(`${fileLogPrefix} - runCompileAndDiscover Completed`);
79
- }
80
- return compilation;
81
- }
82
-
83
- //#endregion
84
- export { runCompileAndDiscover };
85
- //# sourceMappingURL=compile-runner-BNFHRGZO.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"compile-runner-BNFHRGZO.mjs","names":[],"sources":["../src/pool-thread/runner/compile-runner.ts"],"sourcesContent":["/**\n * Worker thread test runner logic for AssemblyScript Pool\n */\n\nimport { basename, relative } from 'node:path';\nimport type { File } from '@vitest/runner/types';\nimport type { SerializedDiffOptions } from '@vitest/utils/diff';\n\nimport { toForwardSlash } from '../../util/path-utils.js';\n\nimport type {\n AssemblyScriptCompilerOptions,\n AssemblyScriptConsoleLog,\n AssemblyScriptConsoleLogHandler,\n InstrumentationOptions,\n ResolvedAssemblyScriptPoolOptions,\n ThreadImports,\n WASMCompilation,\n WorkerRPC,\n} from '../../types/types.js';\nimport {\n ASSEMBLYSCRIPT_LIB_PREFIX,\n INTERNAL_FUNCTION_NAME_SUBSTRING,\n INTERNAL_PATH_LIB_PREFIX,\n POOL_ERROR_NAMES,\n POOL_INTERNAL_PATHS,\n} from '../../types/constants.js';\nimport { executeWASMDiscovery } from '../../wasm-executor/index.js';\nimport { debug } from '../../util/debug.js';\nimport {\n reportFileQueued,\n reportFileCollected,\n reportUserConsoleLogs,\n flushRpcUpdates,\n reportFileError,\n} from '../rpc-reporter.js';\nimport { createPoolErrorFromAnyError, getTestErrorFromPoolError } from '../../util/pool-errors.js';\nimport { compileAssemblyScript } from '../../compiler/index.js';\nimport {\n getTaskLogLabel,\n getTaskLogPrefix,\n} from '../../util/vitest-tasks.js';\nimport {\n failFile,\n getFullTaskHierarchy,\n prepareFileTaskForCollection,\n} from '../../util/vitest-file-tasks.js';\n\nlet threadCompilationCount: number = 0;\n\nexport async function runCompileAndDiscover(\n file: File,\n logModule: string,\n rpc: WorkerRPC,\n poolOptions: ResolvedAssemblyScriptPoolOptions,\n projectRoot: string,\n collectCoverage: boolean,\n relativeUserCoverageExclusions: string[],\n threadImports: ThreadImports,\n diffOptions?: SerializedDiffOptions,\n testNamePattern?: RegExp,\n allowOnly?: boolean,\n): Promise<WASMCompilation | undefined> {\n const base = basename(file.filepath);\n const fileLogPrefix = getTaskLogPrefix(logModule, base, file);\n const fileLogLabel = getTaskLogLabel(base, file);\n\n debug(`${fileLogPrefix} - Beginning runCompileAndDiscover for \"${file.filepath}\" at ${Date.now()}`);\n\n const runStart = performance.now();\n let compilation: WASMCompilation | undefined;\n\n try {\n await reportFileQueued(rpc, file, logModule, fileLogLabel);\n\n const relativeTestFilePath = toForwardSlash(relative(projectRoot, file.filepath));\n const instrumentationOptions: InstrumentationOptions = {\n projectRoot,\n relativeExcludedFiles: [\n relativeTestFilePath,\n ...(poolOptions._instrumentPoolInternals ? [] : POOL_INTERNAL_PATHS),\n ...relativeUserCoverageExclusions,\n ],\n excludedLibraryFilePrefix: ASSEMBLYSCRIPT_LIB_PREFIX,\n excludedLibraryFileOverridePrefix: poolOptions._instrumentPoolInternals ? INTERNAL_PATH_LIB_PREFIX : undefined,\n excludedInternalFunctionSubstring: INTERNAL_FUNCTION_NAME_SUBSTRING,\n coverageMemoryPagesMin: poolOptions.coverageMemoryPagesInitial,\n coverageMemoryPagesMax: poolOptions.coverageMemoryPagesMax,\n debug: poolOptions.debugNative,\n };\n const compilerOptions: AssemblyScriptCompilerOptions = {\n stripInline: poolOptions.stripInline,\n projectRoot: projectRoot,\n shouldInstrument: collectCoverage,\n instrumentationOptions,\n extraFlags: poolOptions.extraCompilerFlags\n };\n\n const { binary, sourceMap, debugInfo, compileTiming } = await compileAssemblyScript(\n file.filepath,\n compilerOptions,\n logModule,\n fileLogLabel\n );\n file.setupDuration = compileTiming;\n threadCompilationCount++;\n\n debug(`${fileLogPrefix} - TIMING compileAssemblyScript total `\n + `(thread comp # ${threadCompilationCount}): ${compileTiming.toFixed(2)} ms`\n );\n \n const logMessages: AssemblyScriptConsoleLog[] = [];\n const handleLog: AssemblyScriptConsoleLogHandler = (msg: string, isError: boolean = false): void => {\n logMessages.push({ msg, time: Date.now(), isError });\n };\n \n const discoverStart = performance.now();\n\n await executeWASMDiscovery(\n binary,\n sourceMap,\n base,\n poolOptions,\n collectCoverage,\n handleLog,\n file,\n logModule,\n threadImports,\n diffOptions\n );\n\n // set skips when using only and/or user test name pattern, skip file task if all tests skipped\n prepareFileTaskForCollection(file, testNamePattern, allowOnly);\n\n file.collectDuration = performance.now() - discoverStart;\n debug(`${fileLogPrefix} - TIMING Discovery Phase: ${file.collectDuration.toFixed(2)} ms`);\n\n // vitest collect - report discovery results\n await Promise.all([\n // Report user console logs\n reportUserConsoleLogs(rpc, logMessages, logModule, base, file),\n\n // Report onCollected with collected and filtered tasks\n reportFileCollected(rpc, file, logModule, fileLogLabel),\n ]);\n\n debug(() => `${fileLogPrefix} - Collected Test Suite Hierarchy:\\n${getFullTaskHierarchy(file)}`);\n\n const totalTime = performance.now() - runStart;\n debug(`${fileLogPrefix} - TIMING Compilation and Discovery: ${totalTime.toFixed(2)} ms`);\n\n compilation = {\n filePath: file.filepath,\n binary,\n sourceMap,\n debugInfo,\n };\n } catch (error) {\n const poolError = createPoolErrorFromAnyError(\n `${fileLogLabel} - runCompileAndDiscover failure in worker`,\n POOL_ERROR_NAMES.WASMExecutionHarnessError,\n error\n );\n const testError = getTestErrorFromPoolError(poolError);\n\n failFile(file, testError, runStart);\n\n await reportFileQueued(rpc, file, logModule, fileLogLabel);\n await reportFileError(rpc, file, logModule, fileLogLabel);\n\n debug(`${fileLogPrefix} - Reported file error`);\n } finally {\n await flushRpcUpdates(rpc);\n debug(`${fileLogPrefix} - runCompileAndDiscover Completed`);\n }\n\n return compilation;\n}\n"],"mappings":";;;;;;;;;;;;;AAgDA,IAAI,yBAAiC;AAErC,eAAsB,sBACpB,MACA,WACA,KACA,aACA,aACA,iBACA,gCACA,eACA,aACA,iBACA,WACsC;CACtC,MAAM,OAAO,SAAS,KAAK,SAAS;CACpC,MAAM,gBAAgB,iBAAiB,WAAW,MAAM,KAAK;CAC7D,MAAM,eAAe,gBAAgB,MAAM,KAAK;AAEhD,OAAM,GAAG,cAAc,0CAA0C,KAAK,SAAS,OAAO,KAAK,KAAK,GAAG;CAEnG,MAAM,WAAW,YAAY,KAAK;CAClC,IAAI;AAEJ,KAAI;AACF,QAAM,iBAAiB,KAAK,MAAM,WAAW,aAAa;EAG1D,MAAM,yBAAiD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AChB,GAAG,aAAa,6CAChB,iBAAiB,2BACjB,MACD,CACqD,EAE5B,SAAS;AAEnC,QAAM,iBAAiB,KAAK,MAAM,WAAW,aAAa;AAC1D,QAAM,gBAAgB,KAAK,MAAM,WAAW,aAAa;AAEzD,QAAM,GAAG,cAAc,wBAAwB;WACvC;AACR,QAAM,gBAAgB,IAAI;AAC1B,QAAM,GAAG,cAAc,oCAAoC;;AAG7D,QAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"compiler-Dqs-qd3I.mjs","names":["ascMain"],"sources":["../src/compiler/index.ts"],"sourcesContent":["/**\n * AssemblyScript Compiler\n *\n * Handles compilation of AssemblyScript source code to WASM binaries.\n * Manages compiler options, transforms, and in-memory compilation.\n */\n\nimport { main as ascMain } from 'assemblyscript/asc';\nimport { basename, resolve } from 'node:path';\nimport { access, readFile, writeFile, mkdir } from 'node:fs/promises';\n\nimport type {\n AssemblyScriptCompilerResult,\n AssemblyScriptCompilerOptions,\n NativeAddonInterface\n} from '../types/types.js';\nimport { POOL_ERROR_NAMES } from '../types/constants.js';\nimport { debug } from '../util/debug.js';\nimport { createPoolError, throwPoolErrorIfAborted } from '../util/pool-errors.js';\nimport { clearNativeBuildError, hasNativeBuildError, warnASInstrumentationNotLoaded } from '../util/feature-check.js';\nimport { toForwardSlash } from '../util/path-utils.js';\n\nlet nativeAddon: NativeAddonInterface | undefined;\ntry {\n nativeAddon = await import('../instrumentation/addon-interface.js');\n // Addon loaded successfully — clear any stale build error marker (fire and forget)\n clearNativeBuildError();\n} catch (err: any) {\n const knownBuildFailure = await hasNativeBuildError();\n if (knownBuildFailure) {\n // Marker file exists — coverage provider will warn the user, just debug log here\n debug(`[Compiler] Native instrumentation addon not loaded (known build failure): ${err?.message ?? String(err)}`);\n } else {\n // Unexpected failure — no marker file, warn the user\n warnASInstrumentationNotLoaded(err?.message ?? String(err));\n }\n}\n\nconst DEBUG_WRITE_FILES = false;\n\n// Path prefix the AS compiler uses when resolving bare `vitest-pool-assemblyscript/assembly` imports\n// via node_modules. Used to detect self-imports and redirect to local assembly/ dir when running locally in-tree.\nconst POOL_ASSEMBLY_NODE_MODULES_PREFIX = 'node_modules/vitest-pool-assemblyscript/assembly/';\n\n// paths assume that we're running from dist/\nconst STRIP_INLINE_TRANSFORM = resolve(import.meta.dirname, './compiler/transforms/strip-inline.mjs');\nconst DEEP_EQUALS_TRANSFORM = resolve(import.meta.dirname, './compiler/transforms/deep-equals.mjs');\n\nsetImmediate(async () => {\n try {\n await access(STRIP_INLINE_TRANSFORM);\n } catch {\n throw createPoolError(\n `AS Compiler strip inline transform file not found at \"${STRIP_INLINE_TRANSFORM}\"`,\n POOL_ERROR_NAMES.CompilationError\n );\n }\n\n try {\n await access(DEEP_EQUALS_TRANSFORM);\n } catch {\n throw createPoolError(\n `AS Compiler deep equals transform file not found at \"${DEEP_EQUALS_TRANSFORM}\"`,\n POOL_ERROR_NAMES.CompilationError\n );\n }\n});\n\n/**\n * Compile AssemblyScript source code to WASM binary\n */\nexport async function compileAssemblyScript(\n filename: string,\n options: AssemblyScriptCompilerOptions,\n logModule: string,\n logLabel: string,\n signal?: AbortSignal\n): Promise<AssemblyScriptCompilerResult> {\n throwPoolErrorIfAborted(signal);\n\n const compileStart = performance.now();\n const logPrefix = `[${logModule} ASC] ${logLabel}`;\n\n const { shouldInstrument, instrumentationOptions, extraFlags } = options;\n\n if (shouldInstrument && !instrumentationOptions) {\n throw createPoolError(\n 'Instrumentation options are required for coverage instrumentation',\n POOL_ERROR_NAMES.CompilationError\n );\n }\n\n const stdoutLines: string[] = [];\n const stderrLines: string[] = [];\n let binary: Uint8Array | undefined;\n let sourceMap: string | undefined;\n\n // Use full path as entry file so AS compiler can resolve relative imports\n const entryFile = filename;\n // Use simple output name to avoid AS compiler prepending it to source map paths\n const outputFile = 'output.wasm';\n\n debug(`${logPrefix} - Compiling: \"${filename}\"`);\n\n // Capture stdout/stderr (for potential error reporting)\n const stdout = {\n write: (text: string) => {\n stdoutLines.push(text);\n return true;\n }\n };\n\n const stderr = {\n write: (text: string) => {\n stderrLines.push(text);\n return true;\n }\n };\n\n // Build compiler flags\n const compilerFlags = [\n entryFile,\n\n // overrideable, though not recommended\n '--optimizeLevel', '0', // No optimization for easier debugging\n '--shrinkLevel', '0', // No shrink\n '--runtime', 'stub', // stub runtime (no GC)\n\n ...(extraFlags || []),\n\n // non-overrideable\n '--outFile', outputFile,\n '--importMemory', // Import memory from JS (enables imports during WASM start)\n '--debug', // Include debug info\n '--sourceMap', // Generate source maps for error reporting\n '--exportStart', '_start', // Export start function for explicit initialization control\n '--exportTable', // Export function table for direct test execution\n\n // Injects deep equality comparison method into user-defined classes for toEqual support\n '--transform', DEEP_EQUALS_TRANSFORM,\n ];\n\n // Add transform to strip @inline decorators if requested\n // This improves coverage accuracy by preventing functions from being inlined,\n // and enables correct source-mapped error reporting for errors originating\n // inside inlined functions.\n if (options.stripInline === true) {\n compilerFlags.push(\n '--transform', STRIP_INLINE_TRANSFORM\n );\n debug(`${logPrefix} - Added Transform - Stripping @inline decorators`);\n }\n\n // Compile with AssemblyScript compiler\n const ascStart = performance.now();\n const result = await ascMain(compilerFlags, {\n stdout,\n stderr,\n // Let AS read from filesystem for import resolution\n // WASM binary and source map are captured in memory via writeFile callback\n writeFile: (name: string, contents: string | Uint8Array, _baseDir: string) => {\n throwPoolErrorIfAborted(signal);\n\n if (name.endsWith('.wasm') && contents instanceof Uint8Array) {\n binary = contents;\n debug(`${logPrefix} - Captured binary in memory: \"${name}\"`);\n } else if (name.endsWith('.wasm.map') && typeof contents === 'string') {\n debug(`${logPrefix} - Captured source map in memory: \"${name}\"`);\n sourceMap = contents;\n } else {\n debug(`${logPrefix} - WARNING - Captured Unexpected File: \"${name}\" at baseDir: \"${_baseDir}\"`);\n }\n },\n \n // Custom readFile enables in-tree resolution of bare pool assembly imports.\n // When a test file imports 'vitest-pool-assemblyscript/assembly', the AS compiler\n // resolves it to a node_modules path. This works when the package is installed,\n // but fails in-tree (the package isn't in its own node_modules). The fallback\n // redirects these to the local assembly/ directory when the normal path isn't found.\n readFile: async (filename, baseDir): Promise<string | null> => {\n const filePath = resolve(baseDir, filename);\n\n try {\n return await readFile(filePath, { encoding: 'utf-8' });\n } catch {\n // Fallback: when running in-tree, redirect pool assembly imports to local assembly/ dir\n const normalizedFilename = toForwardSlash(filename);\n if (normalizedFilename.startsWith(POOL_ASSEMBLY_NODE_MODULES_PREFIX)) {\n const localSubpath = normalizedFilename.substring(POOL_ASSEMBLY_NODE_MODULES_PREFIX.length);\n const localPath = resolve(baseDir, 'assembly', localSubpath);\n\n try {\n return await readFile(localPath, { encoding: 'utf-8' });\n } catch {\n return null;\n }\n }\n\n return null;\n }\n },\n });\n\n debug(`${logPrefix} - TIMING asc.main: ${(performance.now() - ascStart).toFixed(2)} ms`);\n\n if (result.error) {\n const errorMessage = stderrLines.length > 0\n ? `${result.error.message}\\n\\n${stderrLines.join('')}`\n : result.error.message;\n\n throw createPoolError(errorMessage, POOL_ERROR_NAMES.CompilationError, errorMessage);\n }\n\n if (!binary) {\n const errorMessage = stderrLines.length > 0\n ? `No WASM binary was generated\\n\\nAS Compiler output:\\n${stderrLines.join('')}`\n : 'No WASM binary was generated';\n\n throw createPoolError(errorMessage, POOL_ERROR_NAMES.CompilationError);\n }\n\n if (!sourceMap) {\n throw createPoolError('Source map not captured from AssemblyScript Compiler', POOL_ERROR_NAMES.CompilationError);\n }\n\n const cleanBinary: Uint8Array = binary;\n const wasmSourceMap: string = sourceMap;\n\n debug(`${logPrefix} - Compilation successful, clean binary size: ${cleanBinary.length} bytes`);\n debug(`${logPrefix} - Source map generated, size: ${wasmSourceMap.length * 2} bytes`);\n \n if (DEBUG_WRITE_FILES) {\n // Write source map for debugging\n const dir = './debug';\n // TODO - handle non-.ts extensions\n const sourceMapFileName = `${basename(filename, '.ts')}.ts.map`;\n const sourceMapPath = `${dir}/${sourceMapFileName}`;\n\n // Create directory if it doesn't exist\n try {\n await mkdir(dir, { recursive: true });\n } catch {\n // Directory already exists or creation failed, continue\n }\n\n // Format as well-formed JSON\n const formattedSourceMap = JSON.stringify(JSON.parse(wasmSourceMap), null, 2);\n\n writeFile(sourceMapPath, formattedSourceMap, { encoding: 'utf8' });\n debug(`${logPrefix} - Wrote source map to: \"${sourceMapPath}\"`);\n\n // Also write WASM binary for inspection\n const wasmPath = sourceMapPath.replace('.map', '.wasm');\n writeFile(wasmPath, cleanBinary);\n debug(`${logPrefix} - Wrote WASM binary to: \"${wasmPath}\"`);\n }\n\n // Instrument binary for coverage if requested and available\n if (options.shouldInstrument && nativeAddon) {\n throwPoolErrorIfAborted(signal);\n\n const instrumentStart = performance.now();\n const wasmBuffer = Buffer.from(cleanBinary);\n const sourceMapBuffer = Buffer.from(wasmSourceMap);\n\n const instrumentResult = nativeAddon.instrumentForCoverage(wasmBuffer, sourceMapBuffer, options.instrumentationOptions!, logModule, logLabel);\n const instCount = instrumentResult.debugInfo.instrumentedFunctionCount;\n\n const instrumentEnd = performance.now();\n debug(`${logPrefix} - TIMING Instrumented ${instCount} functions: ${(performance.now() - instrumentStart).toFixed(2)} ms`);\n\n return {\n binary: instrumentResult.instrumentedWasm,\n sourceMap: instrumentResult.sourceMap,\n debugInfo: instrumentResult.debugInfo,\n isInstrumented: true,\n compileTiming: instrumentEnd - compileStart,\n };\n }\n\n // No instrumentation requested\n return {\n binary: cleanBinary,\n sourceMap: wasmSourceMap,\n isInstrumented: false,\n compileTiming: performance.now() - compileStart,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,IAAI;AACJ,IAAI;AACF,eAAc,MAAM,OAAO;AAE3B,wBAAuB;SAChB,KAAU;AAEjB,KAD0B,MAAM,qBAAqB,CAGnD,OAAM,6EAA6E,KAAK,WAAW,OAAO,IAAI,GAAG;KAGjH,gCAA+B,KAAK,WAAW,OAAO,IAAI,CAAC;;AAQ/D,MAAM,oCAAoC;AAG1C,MAAM,yBAAyB,QAAQ,OAAO,KAAK,SAAS,yCAAyC;AACrG,MAAM,wB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AAc,SAAS,EAAE,QAAQ;AA6BrF,KAAI,QAAQ,oBAAoB,aAAa;AAC3C,0BAAwB,OAAO;EAE/B,MAAM,kBAAkB,YAAY,KAAK;EACzC,MAAM,aAAa,OAAO,KAAK,YAAY;EAC3C,MAAM,kBAAkB,OAAO,KAAK,cAAc;EAElD,MAAM,mBAAmB,YAAY,sBAAsB,YAAY,iBAAiB,QAAQ,wBAAyB,WAAW,SAAS;EAC7I,MAAM,YAAY,iBAAiB,UAAU;EAE7C,MAAM,gBAAgB,YAAY,KAAK;AACvC,QAAM,GAAG,UAAU,yBAAyB,UAAU,eAAe,YAAY,KAAK,GAAG,iBAAiB,QAAQ,EAAE,CAAC,KAAK;AAE1H,SAAO;GACL,QAAQ,iBAAiB;GACzB,WAAW,iBAAiB;GAC5B,WAAW,iBAAiB;GAC5B,gBAAgB;GAChB,eAAe,gBAAgB;GAChC;;AAIH,QAAO;EACL,QAAQ;EACR,WAAW;EACX,gBAAgB;EAChB,eAAe,YAAY,KAAK,GAAG;EACpC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants-DbxJ3hzg.mjs","names":[],"sources":["../src/types/constants.ts"],"sourcesContent":["/**\n * Plain Constants\n * \n * Only things that don't require importing ./types to avoid circular dependencies.\n */\n\n\n// ============================================================================\n// General / Shared Constants\n// ============================================================================\n\nexport const ASSEMBLYSCRIPT_POOL_NAME = 'assemblyscript' as const;\n\nexport const AS_POOL_ERROR_TYPE_FLAG = '__as_pool__' as const;\n\nexport const AS_POOL_WORKER_MSG_FLAG = '__as_pool__' as const;\n\nexport const AS_POOL_WASM_IMPORTS_ENV = '__as_pool_env__' as const;\n\nexport const VITEST_WORKER_REQUEST_MSG_FLAG = '__vitest_worker_request__' as const;\n\nexport const VITEST_WORKER_RESPONSE_MSG_FLAG = '__vitest_worker_response__' as const;\n\nexport const COVERAGE_PAYLOAD_FORMATS = {\n AssemblyScript: 'assemblyscript',\n} as const;\n\n/** Prefix for AssemblyScript compiler strip-inline exclusions and instrumentation exclusions */\nexport const ASSEMBLYSCRIPT_LIB_PREFIX = '~lib/' as const;\n\nexport const INTERNAL_PATH_LIB_PREFIX: string = `${ASSEMBLYSCRIPT_LIB_PREFIX}vitest-pool-assemblyscript/assembly/` as const;\n\nexport const INTERNAL_FUNCTION_NAME_SUBSTRING = '__vitest_assemblyscript_' as const;\n\n/** Paths instrumentation exclusions and assetion error stack frame filtering */\nexport const POOL_INTERNAL_PATHS: string[] = [\n // AS compiler source maps these as relative paths when running locally\n 'assembly/compare.ts',\n 'assembly/describe.ts',\n 'assembly/expect.ts',\n 'assembly/index.ts',\n 'assembly/options.ts',\n 'assembly/utils.ts',\n 'assembly/test.ts',\n\n // AS compiler source maps these as library paths when running published version\n `${INTERNAL_PATH_LIB_PREFIX}compare.ts`,\n `${INTERNAL_PATH_LIB_PREFIX}describe.ts`,\n `${INTERNAL_PATH_LIB_PREFIX}expect.ts`,\n `${INTERNAL_PATH_LIB_PREFIX}index.ts`,\n `${INTERNAL_PATH_LIB_PREFIX}options.ts`,\n `${INTERNAL_PATH_LIB_PREFIX}stringify.ts`,\n `${INTERNAL_PATH_LIB_PREFIX}test.ts`,\n] as const;\n\n/** Name of the method injected by the deep-equals compiler transform */\nexport const DEEP_EQUALS_INJECTED_METHOD_NAME = '__vitest_assemblyscript_deep_equals' as const;\n\n/**\n * Export alias for pool's equals() function used by injected deep equal method comparison body.\n * Declared with @global in assembly/compare.ts to be available in all source files without import.\n */\nexport const COMPARE_EQUALS_EXPORT_ALIAS = '__vitest_assemblyscript_compare_equals' as const;\n\n/**\n * Name of the @global enum in assembly/compare.ts that represents deep equality comparison results.\n * Used in transform-generated code to reference enum members (e.g. EqualityResult.Equal).\n */\nexport const EQUALITY_RESULT_ENUM_NAME = '__vitest_assemblyscript_EqualityResult' as const;\n\n/**\n * Global alias for the path push function used by injected deep equality method field comparisons.\n * Declared with @global in assembly/compare.ts to be available in all source files without import.\n */\nexport const EQUALS_PATH_PUSH_GLOBAL_ALIAS = '__vitest_assemblyscript_equals_path_push' as const;\n\n/**\n * Global alias for the path pop function used by injected deep equality method field comparisons.\n * Declared with @global in assembly/compare.ts to be available in all source files without import.\n */\nexport const EQUALS_PATH_POP_GLOBAL_ALIAS = '__vitest_assemblyscript_equals_path_pop' as const;\n\n/** Name of the method injected by the compiler transform that returns the runtime class name */\nexport const TYPENAME_INJECTED_METHOD_NAME = '__vitest_assemblyscript_typename' as const;\n\n/** Name of the method injected by the compiler transform that returns stringified field contents */\nexport const STRINGIFY_INJECTED_METHOD_NAME = '__vitest_assemblyscript_stringify' as const;\n\n/**\n * Global alias for the stringifyValue() wrapper used by injected stringify method bodies.\n * Declared with @global in assembly/utils.ts to be available in all source files without import.\n */\nexport const STRINGIFY_VALUE_GLOBAL_ALIAS = '__vitest_assemblyscript_stringify_value' as const;\n\n/** Error names for AssemblyScript test failures reported to vitest */\nexport const TEST_ERROR_NAMES = {\n /** Assertion evaluated to false within a test function */\n AssertionError: 'AssertionError',\n /** WASM runtime called abort after a non-planned user code error */\n WASMRuntimeError: 'WASMRuntimeError',\n} as const;\n\n/** Error names for internal AssemblyScript pool failures */\nexport const POOL_ERROR_NAMES = {\n /** AssemblyScript compiler (asc) error */\n CompilationError: 'CompilationError',\n /** Native instrumentation and debug info extraction error */\n WASMInstrumentationError: 'WASMInstrumentationError',\n /** Unexpected WASM execution error (not a known test error path) */\n WASMExecutionHarnessError: 'WASMExecutionHarnessError',\n /** Hybrid coverage provider error */\n HybridCoverageProviderError: 'HybridCoverageProviderError',\n /** vitest RPC reporting error */\n PoolReportingError: 'PoolReportingError',\n /** User configuration error */\n PoolConfigError: 'PoolConfigError',\n /** Generic AssemblyScript pool error */\n PoolError: 'PoolError',\n /** User syntax error in test/suite/expect */\n PoolSyntaxError: 'PoolSyntaxError',\n\n /** Flow Control: Indicates intentional abort */\n PoolRunAbortedError: 'PoolRunAbortedError',\n /**\n * Flow Control: Indicates WASM execution halt through abort() handler,\n * and should be handled by reporting an AssemblyScriptTestError to vitest\n */\n WASMExecutionAbortError: 'WASMExecutionAbortError',\n /** Flow Control: Indicates WASM execution halt because test timeout elapsed */\n WASMExecutionTimeoutError: 'WASMExecutionTimeoutError',\n} as const;\n\n// ============================================================================\n// AssemblyScript Compiler\n// ============================================================================\n\n// Original const enum values defined in assemblyscript.generated.d.ts.\n// These are reexported to avoid access issues with `const enum` exports \n// in assemblyscript, because we're using isolatedModules & isolatedDeclarations\n\nimport * as ascript from 'assemblyscript';\nimport type * as AS from 'assemblyscript';\n\ntype NodeKindMap = Record<keyof typeof AS.NodeKind, number>;\ntype CommonFlagsMap = Record<keyof typeof AS.CommonFlags, number>;\ntype DecoratorKindMap = Record<keyof typeof AS.DecoratorKind, number>;\ntype SourceKindMap = Record<keyof typeof AS.SourceKind, number>;\n\nconst asRuntime = ascript as unknown as {\n NodeKind: NodeKindMap;\n CommonFlags: CommonFlagsMap;\n DecoratorKind: DecoratorKindMap;\n SourceKind: SourceKindMap;\n};\n\nexport const ASNodeKind: NodeKindMap = asRuntime.NodeKind;\nexport const ASCommonFlags: CommonFlagsMap = asRuntime.CommonFlags;\nexport const ASDecoratorKind: DecoratorKindMap = asRuntime.DecoratorKind;\nexport const ASSourceKind: SourceKindMap = asRuntime.SourceKind;\n"],"mappings":";;;AAuBA,MAAa,2BAA2B,EACtC,gBAAgB,kBACjB;;AAGD,MAAa,4BAA4B;AAEzC,MAAa,2BAAmC,WAA6B;;AAK7E,MAAa,sBAAgC;CAE3C;CACA;CACA;CACA;CACA;CACA;CACA;CAGA,GAAG,yBAAyB;CAC5B,GAAG,yBAAyB;CAC5B,GAAG,yBAAyB;CAC5B,GAAG,yBAAyB;CAC5B,GAAG,yBAAyB;CAC5B,GAAG,yBAAyB;CAC5B,GAAG,yBAAyB;CAC7B;;AA0CD,MAAa,mBAAmB;CAE9B,gBAAgB;CAEhB,kBAAkB;CACnB;;AAGD,MAAa,mBAAmB;CAE9B,kBAAkB;CAElB,0BAA0B;CAE1B,2BAA2B;CAE3B,6BAA6B;CAE7B,oBAAoB;CAEpB,iBAAiB;CAEjB,WAAW;CAEX,iBAAiB;CAGjB,qBAAqB;CAKrB,yBAAyB;CAEzB,2BAA2B;CAC5B;AAkBD,MAAM,YAAY;AAOlB,MAAa,aAA0B,UAAU;AACjD,MAAa,gBAAgC,UAAU;AACvD,MAAa,kBAAoC,UAAU;AAC3D,MAAa,eAA8B,UAAU"}