vitest-pool-assemblyscript 0.7.0 → 0.9.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.
Files changed (93) hide show
  1. package/README.md +10 -13
  2. package/assembly/compare.ts +469 -76
  3. package/assembly/expect.ts +160 -67
  4. package/assembly/index.ts +0 -10
  5. package/assembly/utils.ts +168 -0
  6. package/dist/{addon-interface-_pNXcbib.mjs → addon-interface-CYFXMbK7.mjs} +4 -3
  7. package/dist/addon-interface-CYFXMbK7.mjs.map +1 -0
  8. package/dist/{ast-visitor-C5gQqWD2.mjs → ast-visitor-CWEOd3UH.mjs} +15 -2
  9. package/dist/ast-visitor-CWEOd3UH.mjs.map +1 -0
  10. package/dist/{compile-runner-DOMhsLQE.mjs → compile-runner-BGQhBkBo.mjs} +8 -7
  11. package/dist/compile-runner-BGQhBkBo.mjs.map +1 -0
  12. package/dist/compiler/transforms/deep-equals.d.mts +14 -0
  13. package/dist/compiler/transforms/deep-equals.d.mts.map +1 -0
  14. package/dist/compiler/transforms/deep-equals.mjs +245 -0
  15. package/dist/compiler/transforms/deep-equals.mjs.map +1 -0
  16. package/dist/compiler/transforms/strip-inline.mjs +2 -2
  17. package/dist/{compiler-CIXpfKq0.mjs → compiler-hUlDr5vL.mjs} +14 -6
  18. package/dist/compiler-hUlDr5vL.mjs.map +1 -0
  19. package/dist/config/index-v3.d.mts +33 -3
  20. package/dist/config/index-v3.d.mts.map +1 -1
  21. package/dist/config/index-v3.mjs.map +1 -1
  22. package/dist/config/index.d.mts +29 -4
  23. package/dist/config/index.d.mts.map +1 -0
  24. package/dist/config/index.mjs +6 -6
  25. package/dist/{constants-DuBLuMjt.mjs → constants-DbxJ3hzg.mjs} +10 -97
  26. package/dist/constants-DbxJ3hzg.mjs.map +1 -0
  27. package/dist/coverage-provider/index.mjs +30 -10
  28. package/dist/coverage-provider/index.mjs.map +1 -1
  29. package/dist/{debug-Cm1VFmaz.mjs → debug-DtRAL4rM.mjs} +38 -4
  30. package/dist/debug-DtRAL4rM.mjs.map +1 -0
  31. package/dist/{feature-check-ELxw_Mji.mjs → feature-check-Bje3ntpV.mjs} +2 -2
  32. package/dist/{feature-check-ELxw_Mji.mjs.map → feature-check-Bje3ntpV.mjs.map} +1 -1
  33. package/dist/index-internal.d.mts +1 -1
  34. package/dist/index-internal.d.mts.map +1 -1
  35. package/dist/index-internal.mjs +4 -4
  36. package/dist/index-v3.d.mts.map +1 -1
  37. package/dist/index-v3.mjs +8 -7
  38. package/dist/index-v3.mjs.map +1 -1
  39. package/dist/index.d.mts +1 -2
  40. package/dist/index.mjs +6 -6
  41. package/dist/{load-user-imports-B3Iy_K8k.mjs → load-user-imports-Bx5ZlhSm.mjs} +9 -9
  42. package/dist/load-user-imports-Bx5ZlhSm.mjs.map +1 -0
  43. package/dist/{pool-runner-init-BDQtAGwQ.mjs → pool-runner-init-BqkwQ2tk.mjs} +7 -7
  44. package/dist/pool-runner-init-BqkwQ2tk.mjs.map +1 -0
  45. package/dist/{pool-runner-init-CvnB0-iN.d.mts → pool-runner-init-CNpRdA5u.d.mts} +2 -2
  46. package/dist/pool-runner-init-CNpRdA5u.d.mts.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 +10 -13
  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 +8 -11
  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 +12 -18
  58. package/dist/pool-thread/v3-tinypool-thread.mjs.map +1 -1
  59. package/dist/{resolve-config-DhZ4lOSK.mjs → resolve-config-s9gSJSMc.mjs} +14 -5
  60. package/dist/resolve-config-s9gSJSMc.mjs.map +1 -0
  61. package/dist/{test-runner-C4I9VknR.mjs → test-runner-BGqc9uCK.mjs} +4 -4
  62. package/dist/{test-runner-C4I9VknR.mjs.map → test-runner-BGqc9uCK.mjs.map} +1 -1
  63. package/dist/{types-D0nprJo1.d.mts → types-DHVk5iAx.d.mts} +17 -11
  64. package/dist/types-DHVk5iAx.d.mts.map +1 -0
  65. package/dist/vitest-file-tasks-D8sOClGX.mjs +149 -0
  66. package/dist/vitest-file-tasks-D8sOClGX.mjs.map +1 -0
  67. package/dist/{vitest-tasks--ow4pacR.mjs → vitest-tasks-BZ24sghI.mjs} +6 -4
  68. package/dist/vitest-tasks-BZ24sghI.mjs.map +1 -0
  69. package/package.json +11 -14
  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 +29 -3
  78. package/dist/addon-interface-_pNXcbib.mjs.map +0 -1
  79. package/dist/ast-visitor-C5gQqWD2.mjs.map +0 -1
  80. package/dist/compile-runner-DOMhsLQE.mjs.map +0 -1
  81. package/dist/compiler-CIXpfKq0.mjs.map +0 -1
  82. package/dist/constants-DuBLuMjt.mjs.map +0 -1
  83. package/dist/custom-provider-options-YTk1m7At.d.mts +0 -26
  84. package/dist/custom-provider-options-YTk1m7At.d.mts.map +0 -1
  85. package/dist/debug-Cm1VFmaz.mjs.map +0 -1
  86. package/dist/load-user-imports-B3Iy_K8k.mjs.map +0 -1
  87. package/dist/pool-runner-init-BDQtAGwQ.mjs.map +0 -1
  88. package/dist/pool-runner-init-CvnB0-iN.d.mts.map +0 -1
  89. package/dist/resolve-config-DhZ4lOSK.mjs.map +0 -1
  90. package/dist/types-D0nprJo1.d.mts.map +0 -1
  91. package/dist/vitest-file-tasks-Bn9CrWt_.mjs +0 -61
  92. package/dist/vitest-file-tasks-Bn9CrWt_.mjs.map +0 -1
  93. package/dist/vitest-tasks--ow4pacR.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"compiler-CIXpfKq0.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';\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 in-tree.\nconst POOL_ASSEMBLY_NODE_MODULES_PREFIX = 'node_modules/vitest-pool-assemblyscript/assembly/';\n\n// path assumes that we're running from dist/\nconst STRIP_INLINE_TRANSFORM = resolve(import.meta.dirname, './compiler/transforms/strip-inline.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\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\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 if (filename.startsWith(POOL_ASSEMBLY_NODE_MODULES_PREFIX)) {\n const localSubpath = filename.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":";;;;;;;;;;;;;;AAqBA,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;AAErG,aAAa,YAAY;AACvB,KAAI;AACF,QAAM,OAAO,uBAAuB;SAC9B;AACN,QAAM,gBACJ,yDAAyD,uBAAuB,IAChF,iBAAiB,iBAClB;;EAEH;;;;AAKF,eAAsB,sBACpB,UACA,SACA,WACA,UACA,QACuC;AACvC,yBAAwB,OAAO;CAE/B,MAAM,eAAe,YAAY,KAAK;CACtC,MAAM,YAAY,IAAI,UAAU,QAAQ;CAExC,MAAM,EAAE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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-DuBLuMjt.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\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/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}test.ts`,\n] 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// Redefined locally to avoid isolatedModules const enum access issues\n// with assemmblyscript enum exports. Reference assemblyscript.generated.d.ts\n\nexport const ASCommonFlags = {\n Static: 32,\n Get: 2048,\n Set: 4096,\n} as const;\n\nexport const ASNodeKind = {\n Source: 0,\n NamedType: 1,\n FunctionType: 2,\n TypeName: 3,\n TypeParameter: 4,\n Parameter: 5,\n Identifier: 6,\n Assertion: 7,\n Binary: 8,\n Call: 9,\n Class: 10,\n Comma: 11,\n ElementAccess: 12,\n False: 13,\n Function: 14,\n InstanceOf: 15,\n Literal: 16,\n New: 17,\n Null: 18,\n Omitted: 19,\n Parenthesized: 20,\n PropertyAccess: 21,\n Ternary: 22,\n Super: 23,\n This: 24,\n True: 25,\n Constructor: 26,\n UnaryPostfix: 27,\n UnaryPrefix: 28,\n Compiled: 29,\n Block: 30,\n Break: 31,\n Continue: 32,\n Do: 33,\n Empty: 34,\n Export: 35,\n ExportDefault: 36,\n ExportImport: 37,\n Expression: 38,\n For: 39,\n ForOf: 40,\n If: 41,\n Import: 42,\n Return: 43,\n Switch: 44,\n Throw: 45,\n Try: 46,\n Variable: 47,\n Void: 48,\n While: 49,\n Module: 50,\n ClassDeclaration: 51,\n EnumDeclaration: 52,\n EnumValueDeclaration: 53,\n FieldDeclaration: 54,\n FunctionDeclaration: 55,\n ImportDeclaration: 56,\n InterfaceDeclaration: 57,\n MethodDeclaration: 58,\n NamespaceDeclaration: 59,\n TypeDeclaration: 60,\n VariableDeclaration: 61,\n Decorator: 62,\n ExportMember: 63,\n SwitchCase: 64,\n IndexSignature: 65,\n Comment: 66,\n} as const;\n\nexport const ASDecoratorKind = {\n Custom: 0,\n Global: 1,\n Operator: 2,\n OperatorBinary: 3,\n OperatorPrefix: 4,\n OperatorPostfix: 5,\n Unmanaged: 6,\n Final: 7,\n Inline: 8,\n External: 9,\n ExternalJs: 10,\n Builtin: 11,\n Lazy: 12,\n Unsafe: 13\n} as const;\n\nexport const ASSourceKind = {\n User: 0,\n UserEntry: 1,\n Library: 2,\n LibraryEntry: 3\n} as const;\n"],"mappings":";AAuBA,MAAa,2BAA2B,EACtC,gBAAgB,kBACjB;;AAGD,MAAa,4BAA4B;AAEzC,MAAa,2BAAmC,WAA6B;;AAG7E,MAAa,sBAAgC;CAE3C;CACA;CACA;CACA;CACA;CACA;CAGA,GAAG,yBAAyB;CAC5B,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V;AAED,MAAa,kBAAkB;CAC7B,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,gBAAgB;CAChB,gBAAgB;CAChB,iBAAiB;CACjB,WAAW;CACX,OAAO;CACP,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,SAAS;CACT,MAAM;CACN,QAAQ;CACT;AAED,MAAa,eAAe;CAC1B,MAAM;CACN,WAAW;CACX,SAAS;CACT,cAAc;CACf"}
@@ -1,26 +0,0 @@
1
- import { HybridProviderOptions } from "./types-D0nprJo1.mjs";
2
- import { CoverageV8Options } from "vitest/node";
3
-
4
- //#region src/config/custom-provider-options.d.ts
5
- /**
6
- * Module augmentation for CustomProviderOptions
7
- *
8
- * Vitest v3's CustomProviderOptions only includes fields with default values,
9
- * but users should be able to configure all optional fields from BaseCoverageOptions.
10
- * This augmentation adds the missing optional fields that work at runtime but
11
- * aren't typed in vitest v3.
12
- *
13
- * Additionally, we add AssemblyScript-specific coverage fields that our hybrid
14
- * coverage provider uses to glob AS source files separately from JS sources.
15
- *
16
- * By placing this augmentation here, it automatically loads when users import
17
- * our config helpers, providing proper coverage typing alongside pool typing.
18
- */
19
- declare module "vitest/node" {
20
- interface CustomProviderOptions extends HybridProviderOptions, Omit<CoverageV8Options, "provider"> {
21
- provider: "custom";
22
- /** Name of the module or path to a file to load the custom provider from */
23
- customProviderModule: string;
24
- }
25
- }
26
- //# sourceMappingURL=custom-provider-options-YTk1m7At.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"custom-provider-options-YTk1m7At.d.mts","names":[],"sources":["../src/config/custom-provider-options.ts"],"mappings":";;;;;;AAE2C;;;;;;;;;;;;;YAiB/B,qBAAA,SAA8B,qBAAA,EAAuB,IAAA,CAAK,iBAAA;IAClE,QAAA;IAGD;IAAA,oBAAA;EAAA;AAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"debug-Cm1VFmaz.mjs","names":[],"sources":["../src/util/test-error-formatting.ts","../src/util/pool-errors.ts","../src/util/debug.ts"],"sourcesContent":["import { stripVTControlCharacters } from 'node:util';\nimport type { RawSourceMap } from 'source-map';\nimport c from 'tinyrainbow';\nimport type { ParsedStack } from '@vitest/utils';\n\nimport { HighlightFunc } from '../types/types.js';\n\nconst FRAME_POINTER = '❯' as const;\nconst CODE_FRAME_INDENT_SPACES = 4 as const;\n\n// same performance guard used in vitest `printError`\nconst MAX_CODE_HIGHLIGHT_LENGTH = 100_000 as const;\n\nexport function getYellowString(str: string): string {\n return c.yellow(str);\n}\n\nexport function toPlaintextStackFrameString(frame: ParsedStack): string {\n return ` at ${frame.method} ${frame.file}:${frame.line}:${frame.column}`;\n}\n\nexport function toVitestLikeStackFrameString(frame: ParsedStack): string {\n return c.cyan(\n ` ${c.dim(FRAME_POINTER)} ${frame.method} ${frame.file}:${c.dim(`${frame.line}:${frame.column}`)}`\n );\n}\n\nexport function getSourceCodeFrameString(\n sourceMap: RawSourceMap,\n frame: ParsedStack,\n highlight: HighlightFunc,\n): string | undefined {\n if (!sourceMap.sourcesContent) {\n return undefined;\n }\n\n const fileIndex = sourceMap.sources.indexOf(frame.file);\n if (fileIndex < 0) {\n return undefined;\n }\n\n const source = sourceMap.sourcesContent[fileIndex];\n if (!source) {\n return undefined;\n }\n\n const highlightedSource = source.length < MAX_CODE_HIGHLIGHT_LENGTH\n ? highlight(source, { colors: c })\n : source;\n\n return generateCodeFrame(highlightedSource, CODE_FRAME_INDENT_SPACES, frame);\n}\n\n\n// ============================================================================\n// Source code formatting functions borrowed from Vitest\n// ============================================================================\n\n/**\n * Vitest doesn't expose generateCodeFrame as a util, so we have\n * recreated it here with minimal changes.\n * \n * @see https://github.com/vitest-dev/vitest/blob/v3.2.4/packages/vitest/src/node/printError.ts#L424\n * \n * Vitest is released under the MIT license, included in this project's root.\n * Copyright (c) 2021-Present Vitest Team\n */\n\nconst lineSplitRE: RegExp = /\\r?\\n/;\n\nfunction generateCodeFrame(\n source: string,\n indent = 0,\n loc: { line: number; column: number } | number,\n range = 2,\n): string {\n const start\n = typeof loc === 'object'\n ? positionToOffset(source, loc.line, loc.column)\n : loc\n const end = start\n const lines = source.split(lineSplitRE)\n const nl = /\\r\\n/.test(source) ? 2 : 1\n let count = 0\n let res: string[] = []\n\n const columns = process.stdout?.columns || 80\n\n for (let i = 0; i < lines.length; i++) {\n count += lines[i]!.length + nl\n if (count >= start) {\n for (let j = i - range; j <= i + range || end > count; j++) {\n if (j < 0 || j >= lines.length) {\n continue\n }\n\n const lineLength = lines[j]!.length\n\n // too long, maybe it's a minified file, skip for codeframe\n if (stripVTControlCharacters(lines[j]!).length > 200) {\n return ''\n }\n\n res.push(\n lineNo(j + 1)\n + truncateString(lines[j]!.replace(/\\t/g, ' '), columns - 5 - indent),\n )\n\n if (j === i) {\n // push underline\n const pad = start - (count - lineLength) + (nl - 1)\n const length = Math.max(\n 1,\n end > count ? lineLength - pad : end - start,\n )\n res.push(lineNo() + ' '.repeat(pad) + c.red('^'.repeat(length)))\n }\n else if (j > i) {\n if (end > count) {\n const length = Math.max(1, Math.min(end - count, lineLength))\n res.push(lineNo() + c.red('^'.repeat(length)))\n }\n count += lineLength + 1\n }\n }\n break\n }\n }\n\n if (indent) {\n res = res.map(line => ' '.repeat(indent) + line)\n }\n\n return res.join('\\n')\n}\n\n\nfunction positionToOffset(\n source: string,\n lineNumber: number,\n columnNumber: number,\n): number {\n const lines = source.split(lineSplitRE)\n const nl = /\\r\\n/.test(source) ? 2 : 1\n let start = 0\n\n if (lineNumber > lines.length) {\n return source.length\n }\n\n for (let i = 0; i < lineNumber - 1; i++) {\n start += lines[i]!.length + nl\n }\n\n return start + columnNumber\n}\n\nfunction lineNo(no: number | string = '') {\n return c.gray(`${String(no).padStart(3, ' ')}| `)\n}\n\nfunction truncateString(text: string, maxLength: number): string {\n const plainText = stripVTControlCharacters(text)\n\n if (plainText.length <= maxLength) {\n return text\n }\n\n return `${plainText.slice(0, maxLength - 1)}…`\n}\n","import type { Test } from '@vitest/runner/types';\n\nimport type {\n AssemblyScriptPoolError,\n AssemblyScriptTestError,\n PoolErrorName,\n TestErrorName\n} from '../types/types.js';\nimport {\n AS_POOL_ERROR_TYPE_FLAG,\n POOL_ERROR_NAMES,\n TEST_ERROR_NAMES\n} from '../types/constants.js';\nimport { getYellowString } from './test-error-formatting.js';\n\nexport function createPoolError(\n message: string,\n name: PoolErrorName,\n stack?: string,\n cause?: any,\n rawCallStack?: NodeJS.CallSite[],\n): AssemblyScriptPoolError {\n return { name, message, stack, cause, rawCallStack, [AS_POOL_ERROR_TYPE_FLAG]: true };\n}\n\nexport function createTestTimeoutError(\n test: Test\n): AssemblyScriptTestError {\n const message = `Test timed out after ${test.timeout}ms`;\n const err: AssemblyScriptTestError = {\n name: POOL_ERROR_NAMES.WASMExecutionTimeoutError,\n message,\n stack: `${test.id}_${message}`,\n diff: getYellowString(` Test Timeout Exceeded (${test.timeout}ms)`)\n };\n return err;\n}\n\nexport function createTestExpectedToFailError(test: Test): AssemblyScriptTestError {\n const message = `Test is expected to fail, but all assertions passed`;\n const err: AssemblyScriptTestError = {\n name: TEST_ERROR_NAMES.AssertionError,\n message,\n stack: `${test.id}_${message}`,\n diff: getYellowString(` Expected to fail, but all assertions passed`)\n };\n return err;\n}\n\nexport function throwPoolErrorIfAborted(signal?: AbortSignal): void {\n if (!signal || !signal.aborted) {\n return;\n }\n\n throw createPoolError(signal.reason, POOL_ERROR_NAMES.PoolRunAbortedError);\n}\n\nexport function isAbortErrorString(item: any): boolean {\n return item === POOL_ERROR_NAMES.PoolRunAbortedError || item === 'AbortError';\n}\n\nexport function isAbortError(error: any): boolean {\n return isAbortErrorString(error) \n || isAbortErrorString(error?.name)\n || error?.message === 'Terminating worker thread';\n}\n\nexport function createPoolErrorFromAnyError(\n context: string,\n contextErrorName: PoolErrorName,\n error: any\n): AssemblyScriptPoolError {\n const isErrorAbortString = isAbortErrorString(error);\n if (isErrorAbortString) {\n const msg = `${contextErrorName}: ${context} - Aborted, Unknown Cause`;\n return createPoolError(msg, POOL_ERROR_NAMES.PoolRunAbortedError);\n }\n\n if (error[AS_POOL_ERROR_TYPE_FLAG]) {\n return error as AssemblyScriptPoolError;\n }\n\n if (error instanceof Error) {\n const isAbortError = isAbortErrorString(error.name);\n const asErr = createPoolError(\n `${context} - ${error.name}: ${error.message}`,\n isAbortError ? POOL_ERROR_NAMES.PoolRunAbortedError : contextErrorName,\n error.stack,\n error.cause\n );\n return asErr;\n }\n\n const errorMsg = String(error);\n return createPoolError(`${context} - ${errorMsg}`, contextErrorName);\n}\n\nexport function getTestErrorFromPoolError(error: AssemblyScriptPoolError): AssemblyScriptTestError {\n const anyCause: any = error?.cause;\n if (error.causeIsEnhancedError) {\n return error.cause as AssemblyScriptTestError;\n }\n\n const message = error.message ?? anyCause.message ?? 'Unknown error';\n return {\n name: error.name ?? anyCause.name ?? POOL_ERROR_NAMES.PoolError,\n message,\n stack: anyCause?.stack ?? error.stack ?? message,\n stacks: anyCause?.stacks ,\n cause: getTestErrorFromAnyError(anyCause?.cause),\n diff: anyCause?.diff\n };\n}\n\nexport function getTestErrorFromAnyError(\n error: any,\n context: string = '',\n fallbackName: TestErrorName | PoolErrorName = POOL_ERROR_NAMES.PoolError\n): AssemblyScriptTestError | undefined {\n if (!error) {\n return undefined;\n }\n\n const message = `${context ?? ''}${error?.message ?? ''}`;\n return {\n name: error?.name ?? fallbackName,\n message,\n stack: error?.stack ?? message,\n stacks: error?.stacks,\n cause: getTestErrorFromAnyError(error?.cause)\n };\n}\n","/**\n * Debug logging utility\n */\n\ndeclare global {\n var AS_POOL_DEBUG: boolean | undefined;\n}\n\nglobalThis.AS_POOL_DEBUG = false;\n\nconst DEBUG_ENV_ENABLED_VALUE = 'vitest_as_pool' as const;\n\nfunction isEnabled(): boolean {\n return globalThis.AS_POOL_DEBUG === true || process.env.DEBUG === DEBUG_ENV_ENABLED_VALUE;\n}\n\n/**\n * Initialize debug mode for current async context (called by worker at task start)\n * @param {boolean} debugEnabled - Enable verbose debug logging\n */\nexport function setGlobalDebugMode(debugEnabled: boolean): void {\n globalThis.AS_POOL_DEBUG = debugEnabled;\n}\n\nfunction debugLog(...args: any): void {\n // if first arg is a function, execute it and then print the result\n if (args?.length > 0 && typeof args[0] === 'function') {\n const result = args[0]();\n const rest = args.length > 1 ? args.slice(1) : [];\n console.log(Date.now(), String(result), ...rest);\n } else {\n console.log(Date.now(), ...args);\n }\n}\n\n/**\n * Log debug message (only when debug enabled in current global context)\n * or when environment has a given DEBUG variable set.\n */\nexport function debug(...args: any): void {\n if (isEnabled()) {\n debugLog(...args);\n }\n}\n\n/**\n * Log debug message (caller expected to determine if enabled)\n */\nexport function debugOverride(...args: any): void {\n debugLog(...args);\n}\n\n/**\n * Determine if debug mode is enabled for the current global context\n */\nexport function isDebugModeEnabled(): boolean {\n return isEnabled();\n}\n\nexport async function delay(ms: number = 5000): Promise<void> {\n return new Promise<void>((resolve, _reject) => {\n setTimeout(resolve, ms);\n });\n}\n"],"mappings":";;;;;AAOA,MAAM,gBAAgB;AACtB,MAAM,2BAA2B;AAGjC,MAAM,4BAA4B;AAElC,SAAgB,gBAAgB,KAAqB;AACnD,QAAO,EAAE,OAAO,IAAI;;AAGtB,SAAgB,4BAA4B,OAA4B;AACtE,QAAO,UAAU,MAAM,OAAO,GAAG,MAAM,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM;;AAGrE,SAAgB,6BAA6B,OAA4B;AACvE,QAAO,EAAE,KACP,IAAI,EAAE,IAAI,cAAc,CAAC,GAAG,MAAM,OAAO,GAAG,MAAM,KAAK,GAAG,EAAE,IAAI,GAAG,MAAM,KAAK,GAAG,MAAM,SAAS,GACjG;;AAGH,SAAgB,yBACd,WACA,OACA,WACoB;AACpB,KAAI,CAAC,UAAU,eACb;CAGF,MAAM,YAAY,UAAU,QAAQ,QAAQ,MAAM,KAAK;AACvD,KAAI,YAAY,EACd;CAGF,MAAM,SAAS,UAAU,eAAe;AACxC,KAAI,CAAC,OACH;AAOF,QAAO,kBAJmB,OAAO,SAAS,4BACtC,UAAU,QA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C1HH,WAAW,gBAAgB;AAE3B,MAAM,0BAA0B;AAEhC,SAAS,YAAqB;AAC5B,QAAO,WAAW,kBAAkB,QAAQ,QAAQ,IAAI,UAAU;;;;;;AAOpE,SAAgB,mBAAmB,cAA6B;AAC9D,YAAW,gBAAgB;;AAG7B,SAAS,SAAS,GAAG,MAAiB;AAEpC,KAAI,MAAM,SAAS,KAAK,OAAO,KAAK,OAAO,YAAY;EACrD,MAAM,SAAS,KAAK,IAAI;EACxB,MAAM,OAAO,KAAK,SAAS,IAAI,KAAK,MAAM,EAAE,GAAG,EAAE;AACjD,UAAQ,IAAI,KAAK,KAAK,EAAE,OAAO,OAAO,EAAE,GAAG,KAAK;OAEhD,SAAQ,IAAI,KAAK,KAAK,EAAE,GAAG,KAAK;;;;;;AAQpC,SAAgB,MAAM,GAAG,MAAiB;AACxC,KAAI,WAAW,CACb,UAAS,GAAG,KAAK;;;;;AAOrB,SAAgB,cAAc,GAAG,MAAiB;AAChD,UAAS,GAAG,KAAK"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"load-user-imports-B3Iy_K8k.mjs","names":[],"sources":["../src/util/assemblyscript/binding-helpers.ts","../src/wasm-executor/wasm-memory.ts","../src/wasm-executor/wasm-console.ts","../src/wasm-executor/collect-options.ts","../src/wasm-executor/wasm-imports.ts","../src/wasm-executor/wasm-errors.ts","../src/wasm-executor/index.ts","../src/pool-thread/rpc-reporter.ts","../src/pool-thread/load-user-imports.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 { liftString } from '../util/assemblyscript/binding-helpers.js';\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","import type { AssemblyScriptConsoleLogHandler } from '../types/types.js';\nimport { liftString } from '../util/assemblyscript/binding-helpers.js';\n\nexport function createWasmConsole(\n memory: WebAssembly.Memory,\n handleLog: AssemblyScriptConsoleLogHandler\n) {\n const getMessage = (msgPtr: number, memory: WebAssembly.Memory, prefix: string = ''): string => {\n return `${prefix}${msgPtr ? liftString(memory, msgPtr) : '<no message>'}`;\n };\n\n const timersByLabel: { [label: string]: number } = {};\n\n // provides the AssemblyScript \"brower-like console\" from AS std lib\n // see https://github.com/AssemblyScript/assemblyscript/blob/v0.28.9/std/assembly/index.d.ts#L2609\n return {\n 'console.assert': <T>(assertion: T, msgPtr: number): void => {\n if (!assertion) {\n const msg = getMessage(msgPtr, memory);\n handleLog(`Assertion failed${msg ? `: ${msg}` : ''}`);\n }\n },\n 'console.log': (msgPtr: number): void => {\n handleLog(getMessage(msgPtr, memory));\n },\n 'console.debug': (msgPtr: number): void => {\n handleLog(getMessage(msgPtr, memory, 'Debug: '));\n },\n 'console.info': (msgPtr: number): void => {\n handleLog(getMessage(msgPtr, memory, 'Info: '));\n },\n 'console.warn': (msgPtr: number): void => {\n handleLog(getMessage(msgPtr, memory, 'Warning: '), true);\n },\n 'console.error': (msgPtr: number): void => {\n handleLog(getMessage(msgPtr, memory, 'Error: '), true);\n },\n 'console.time': (labelPtr?: number): void => {\n const label = labelPtr ? liftString(memory, labelPtr) ?? 'default' : 'default';\n timersByLabel[label] = performance.now();\n },\n 'console.timeLog': (labelPtr?: number): void => {\n const label = labelPtr ? liftString(memory, labelPtr) ?? 'default' : 'default';\n const start = timersByLabel[label];\n let msg = '';\n if (start === undefined) {\n msg = `Warning: No such label '${label}' for console.timeLog()`;\n } else {\n msg = `${label}: ${(performance.now() - start).toFixed(3)}ms`;\n }\n handleLog(msg);\n },\n 'console.timeEnd': (labelPtr?: number): void => {\n const label = labelPtr ? liftString(memory, labelPtr) ?? 'default' : 'default';\n const start = timersByLabel[label];\n let msg = '';\n if (start === undefined) {\n msg = `Warning: No such label '${label}' for console.timeLog()`;\n } else {\n msg = `${label}: ${(performance.now() - start).toFixed(3)}ms`;\n }\n handleLog(msg);\n delete timersByLabel[label];\n },\n\n trace(msgPtr: number, n: number, a0: any, a1: any, a2: any, a3: any): void {\n const msg = liftString(memory, msgPtr);\n const args: any[] = [a0, a1, a2, a3];\n const nArgs: any[] = n && n > 0 ? args.slice(0, n) : args;\n\n console.trace(`WASM Trace:${msg ? ` ${msg}` : ''}`, ...nArgs);\n },\n };\n}\n","import { AssemblyScriptTestOptions } from '../types/types.js';\n\nconst TEST_OPTION_UNDEFINED: number = -1;\nconst TEST_OPTION_TRUE: number = 1;\n\nexport function mergeAssemblyScriptTestOptions(\n baseOptions: AssemblyScriptTestOptions,\n timeout: number,\n retry: number,\n skip: number,\n only: number,\n fails: number,\n): AssemblyScriptTestOptions {\n const options: AssemblyScriptTestOptions = { ...baseOptions };\n \n // numerical options\n if (timeout > TEST_OPTION_UNDEFINED) {\n options.timeout = timeout;\n }\n if (retry > TEST_OPTION_UNDEFINED) {\n options.retry = retry;\n }\n\n // boolean options\n if (skip > TEST_OPTION_UNDEFINED) {\n options.skip = skip === TEST_OPTION_TRUE ? true : false;\n }\n if (only > TEST_OPTION_UNDEFINED) {\n options.only = only === TEST_OPTION_TRUE ? true : false;\n }\n if (fails > TEST_OPTION_UNDEFINED) {\n options.fails = fails === TEST_OPTION_TRUE ? true : false;\n }\n\n return options;\n}\n","import type { File, Suite, Test } from '@vitest/runner/types';\n\nimport type {\n AssemblyScriptConsoleLogHandler,\n AssemblyScriptSuiteTaskMeta,\n AssemblyScriptTestError,\n AssemblyScriptTestTaskMeta,\n FailedAssertion,\n WasmImportsFactory,\n} from '../types/types.js';\nimport { AS_POOL_WASM_IMPORTS_ENV, POOL_ERROR_NAMES, TEST_ERROR_NAMES } from '../types/constants.js';\nimport { debug } from '../util/debug.js';\nimport { createPoolError, createPoolErrorFromAnyError } from '../util/pool-errors.js';\nimport { liftString } from '../util/assemblyscript/binding-helpers.js';\nimport { extractCallStack } from './source-maps.js';\nimport { decodeAbortInfo } from './wasm-memory.js';\nimport { createWasmConsole } from './wasm-console.js';\nimport { mergeAssemblyScriptTestOptions } from './collect-options.js';\nimport { createSuiteTask, createTestTask, failTest } from '../util/vitest-tasks.js';\n\nfunction createUserWasmImports(\n createWasmImports: WasmImportsFactory | undefined,\n memory: WebAssembly.Memory,\n module: WebAssembly.Module,\n logPrefix: string\n) {\n let userEnvImports: WebAssembly.ModuleImports | undefined;\n let userCustomEnvImports: WebAssembly.Imports | undefined;\n\n if (createWasmImports) {\n try {\n const start = performance.now();\n const userImports: WebAssembly.Imports = createWasmImports({\n memory,\n module,\n utils: {\n liftString: (stringPtr: number) => liftString(memory, stringPtr)\n }\n });\n debug(`${logPrefix} Created user WASM imports for test execution in ${(performance.now() - start).toFixed(2)} ms`);\n\n userEnvImports = userImports?.env;\n \n if (userEnvImports) {\n userCustomEnvImports = { ...userImports };\n delete userCustomEnvImports.env;\n }\n } catch (error) {\n throw createPoolErrorFromAnyError(\n `Error creating user WASM Imports`,\n POOL_ERROR_NAMES.PoolConfigError,\n error\n );\n }\n }\n\n return { userEnvImports, userCustomEnvImports };\n}\n\n/**\n * Create import object for test discovery\n */\nexport function createDiscoveryImports(\n memory: WebAssembly.Memory,\n module: WebAssembly.Module,\n file: File,\n handleLog: AssemblyScriptConsoleLogHandler,\n logPrefix: string,\n coverageMemory?: WebAssembly.Memory,\n createWasmImports?: WasmImportsFactory,\n): WebAssembly.Imports {\n const suiteStack: Suite[] = [file];\n\n const {\n userEnvImports,\n userCustomEnvImports\n } = createUserWasmImports(createWasmImports, memory, module, logPrefix);\n \n return {\n env: {\n // users can choose to hide these with their own\n ...createWasmConsole(memory, handleLog),\n\n // user imports for \"env\"\n ...(userEnvImports ?? {}),\n\n memory,\n\n // handle runtime aborts, which are always unexpected during discovery\n abort(msgPtr: number, filePtr: number, line: number, column: number) {\n const { message, location } = decodeAbortInfo(memory, msgPtr, filePtr, line, column);\n const msgAtLoc = `${message}${location ? ` at ${location}` : ''}`;\n \n debug(`${logPrefix} - Unexpected abort during test discovery: ${msgAtLoc}`);\n\n // Create error to capture V8 stack trace and extract V8 call stack before throwing.\n // This gives us WAT line:column positions that can be mapped to AS source\n const rawCallStack = extractCallStack(new Error());\n\n // Send the test error that we will report to vitest in the PoolError's `cause` field.\n // The rawCallStack will be enahnced and deleted by the executor, with the parsed result\n // added to the reported test error.\n const testError: AssemblyScriptTestError = {\n message,\n name: TEST_ERROR_NAMES.WASMRuntimeError,\n };\n\n throw createPoolError(\n msgAtLoc,\n POOL_ERROR_NAMES.WASMExecutionAbortError,\n undefined, // stack\n testError, // cause\n rawCallStack\n );\n },\n },\n\n [AS_POOL_WASM_IMPORTS_ENV]: {\n\n ...(coverageMemory ? { __coverage_memory: coverageMemory } : {}),\n\n // stubs during discovery\n __assertion_pass() {},\n __assertion_fail() {},\n __expect_throw() {},\n __end_expect_throw() {},\n\n __begin_register_suite(\n namePtr: number,\n timeout: number,\n retry: number,\n skip: number,\n only: number,\n fails: number,\n ) {\n const parentSuite = suiteStack[suiteStack.length - 1]!;\n const defaultTestOptions = (parentSuite.meta as AssemblyScriptSuiteTaskMeta).defaultTestOptions;\n const suiteName = liftString(memory, namePtr) ?? 'unknown suite';\n const options = mergeAssemblyScriptTestOptions(defaultTestOptions, timeout, retry, skip, only, fails);\n const suite = createSuiteTask(suiteName, file, parentSuite, options);\n suiteStack.push(suite);\n\n debug(\n `${logPrefix} - Registering Suite \"${suite.name}\" | timeout: ${options.timeout} ms | retry: ${options.retry}`\n + ` | skip: ${options.skip} | only: ${options.only} | fails: ${options.fails} `\n + ` | parent: \"${suite.suite?.name}\" (parent idx: ${(suite.meta as AssemblyScriptSuiteTaskMeta).idxInParentTasks})`\n );\n },\n \n __end_register_suite(_namePtr: number) {\n const suite = suiteStack.pop();\n\n debug(\n `${logPrefix} - Registered Suite \"${suite?.name}\" | ${suite?.tasks.length} top-level tasks | mode: \"${suite?.mode}\"`\n + ` | parent: \"${suite?.suite?.name}\" (parent idx: ${(suite?.meta as AssemblyScriptSuiteTaskMeta)?.idxInParentTasks})`\n );\n },\n\n // called by test() to register test names and function indices\n __register_test(\n namePtr: number,\n fnIndex: number,\n timeout: number,\n retry: number,\n skip: number,\n only: number,\n fails: number,\n ) {\n const parentSuite = suiteStack[suiteStack.length - 1]!;\n const defaultTestOptions = (parentSuite.meta as AssemblyScriptSuiteTaskMeta).defaultTestOptions;\n const testName = liftString(memory, namePtr) ?? 'unknown test';\n const options = mergeAssemblyScriptTestOptions(defaultTestOptions, timeout, retry, skip, only, fails);\n const test = createTestTask(testName, fnIndex, file, parentSuite, options);\n \n debug(`${logPrefix} - Registered test \"${test.name}\" | mode (pre-interp): \"${test.mode}\"`\n + ` | fnIndex ${fnIndex} | timeout: ${options.timeout} ms | retry: ${options.retry} | skip: ${options.skip}`\n + ` | only: ${options.only} | fails: ${options.fails} | suite: \"${test.suite?.name}\"`\n + ` (parent idx: ${(test.meta as AssemblyScriptTestTaskMeta).idxInParentTasks})`\n );\n },\n },\n\n // user imports for any other environments they defined\n ...(userCustomEnvImports ?? {}),\n };\n}\n\n/**\n * Create import object for test execution\n *\n * Used during test execution to capture test results / assertions, and to handle\n * runtime aborts as expected cases for test execution by capturing the error on the test meta.\n */\nexport function createTestExecutionImports(\n memory: WebAssembly.Memory,\n module: WebAssembly.Module,\n test: Test,\n handleLog: AssemblyScriptConsoleLogHandler,\n logPrefix: string,\n coverageMemory?: WebAssembly.Memory,\n createWasmImports?: WasmImportsFactory,\n): { imports: WebAssembly.Imports; provideFunctionTable: (table: WebAssembly.Table) => void; } {\n // execution imports are created per-test, so these represent per-test state\n let isExpectingError: boolean = false;\n let expectedErrorMsgStr: string | undefined;\n let wasmFunctionTable: WebAssembly.Table | undefined;\n\n const {\n userEnvImports,\n userCustomEnvImports\n } = createUserWasmImports(createWasmImports, memory, module, logPrefix);\n\n const imports = {\n env: {\n // users can choose to hide these with their own\n ...createWasmConsole(memory, handleLog),\n\n // user imports for \"env\"\n ...(userEnvImports ?? {}),\n\n memory,\n\n abort(msgPtr: number, filePtr: number, line: number, column: number) {\n const { message, location } = decodeAbortInfo(memory, msgPtr, filePtr, line, column);\n const msgAtLoc = `${message}${location ? ` at ${location}` : ''}`;\n \n debug(`${logPrefix} - Handling test execution abort: ${msgAtLoc}`);\n\n let failureMessage = message;\n\n if (isExpectingError) {\n if (!expectedErrorMsgStr || message.includes(expectedErrorMsgStr)) {\n (test.meta as AssemblyScriptTestTaskMeta).assertionsPassedCount++;\n \n debug(`${logPrefix} - Thrown error matches expected - assertion passes`);\n\n throw createPoolError(\n `AssemblyScript abort() import called for expected error throw in test \"${test.name}\"`,\n POOL_ERROR_NAMES.WASMExecutionAbortError\n );\n } else {\n failureMessage = `expected function to throw \"${expectedErrorMsgStr}\" error but received \"${message}\"`;\n\n (test.meta as AssemblyScriptTestTaskMeta).assertionsFailed.push({\n message: failureMessage,\n typeName: 'Error',\n valuesProvided: true,\n actual: message,\n expected: expectedErrorMsgStr\n } satisfies FailedAssertion);\n\n const errStr = `Thrown error does not match expected | Expected: \"${expectedErrorMsgStr}\" | Actual: \"${message}\"`\n debug(`${logPrefix} - Assertion failed: ${errStr}`);\n }\n }\n\n // Create error to capture V8 stack trace and extract V8 call stack before throwing.\n // This gives us WAT line:column positions that can be mapped to AS source\n const capturedError = new Error();\n\n failTest(test, failureMessage, capturedError, logPrefix);\n\n // Must throw here to halt WASM execution on an assertion or runtime failure for this test.\n // This will be caught by the executor and reported as an appropriate test error\n // using test.meta.lastError value set in failTest()\n throw createPoolError(\n `AssemblyScript abort() import called during test execution for ${test.name}`,\n POOL_ERROR_NAMES.WASMExecutionAbortError,\n );\n },\n },\n\n [AS_POOL_WASM_IMPORTS_ENV]: {\n \n ...(coverageMemory ? { __coverage_memory: coverageMemory } : {}),\n\n // stubs during execution\n __register_test() {},\n __begin_register_suite() {},\n __end_register_suite() {},\n\n __assertion_pass() {\n (test.meta as AssemblyScriptTestTaskMeta).assertionsPassedCount++;\n },\n\n __assertion_fail(msgPtr: number, typeNamePtr: number, valuesProvided: boolean, actualPtr?: number, expectedPtr?: number) {\n const errorMsg = liftString(memory, msgPtr);\n const assertionValueType = liftString(memory, typeNamePtr);\n let actual: string | undefined;\n let expected: string | undefined;\n \n const assertionFailure: FailedAssertion = {\n message: errorMsg,\n typeName: assertionValueType,\n valuesProvided: Boolean(valuesProvided)\n };\n \n if (valuesProvided && actualPtr && expectedPtr) {\n assertionFailure.actual = liftString(memory, actualPtr);\n assertionFailure.expected = liftString(memory, expectedPtr);\n }\n \n (test.meta as AssemblyScriptTestTaskMeta).assertionsFailed.push(assertionFailure);\n \n const valuesMsg = valuesProvided ? ` | Value Type: ${assertionValueType}`\n + ` | Expected: \\`${expected !== undefined ? expected : ''}\\` | Actual: \\`${actual !== undefined ? actual : ''}\\``\n : '';\n debug(`${logPrefix} - Assertion failed: ${errorMsg}${valuesMsg}`);\n },\n\n __expect_throw(fnIndex: number, expectedErrorMsgPtr?: number) {\n isExpectingError = true;\n if (expectedErrorMsgPtr) {\n expectedErrorMsgStr = liftString(memory, expectedErrorMsgPtr);\n }\n\n debug(`${logPrefix} - Registered expected error throw: ${expectedErrorMsgStr !== undefined\n ? `\"${expectedErrorMsgStr}\"` : '<any>'}`\n );\n\n if (wasmFunctionTable && typeof wasmFunctionTable.get === 'function') {\n const fn = wasmFunctionTable.get(fnIndex);\n if (!fn) {\n throw createPoolError(\n `Could not access function (fnPtr ${fnIndex}) which is expected to throw in test \"${test.name}\"`,\n POOL_ERROR_NAMES.WASMExecutionHarnessError,\n );\n }\n\n // successful:\n // - throws in WASM, calls abort handler\n // - abort handler confirms error matches expected, does NOT fail test, halts execution with WASMExecutionAbortError\n // - executor catches WASMExecutionAbortError as 'known' and proceeds to process & report passed test\n // failure (wrong error):\n // - throws in WASM, calls abort handler\n // - abort handler confirms error matches mismatch, failTest packages up an appropriate test error\n // - abort handler halts execution with WASMExecutionAbortError containing test error\n // - executor catches WASMExecutionAbortError as 'known' and proceeds to process & report test error\n // failure (no error):\n // - does NOT throw in WASM\n // - WASM continues executing and calls __end_expect_throw\n // - __end_expect_throw sees it is STILL expecting an error, failTest packages up an appropriate test error\n // - __end_expect_throw halts execution with WASMExecutionAbortError containing test error\n // - executor catches WASMExecutionAbortError as 'known' and proceeds to process & report test error\n debug(`${logPrefix} - Calling function (idx ${fnIndex})`);\n fn();\n } else {\n throw createPoolError(\n `Could not access WASM function table to call function expected to throw in test \"${test.name}\"`,\n POOL_ERROR_NAMES.WASMExecutionHarnessError,\n );\n }\n },\n\n __end_expect_throw() {\n if (isExpectingError) {\n const isAnyErr: boolean = !!expectedErrorMsgStr;\n const failureMessage = `expected function to throw ${isAnyErr ?\n `\"${expectedErrorMsgStr}\"` : 'any'\n } error - did not throw`;\n\n (test.meta as AssemblyScriptTestTaskMeta).assertionsFailed.push({\n message: failureMessage,\n typeName: 'Error',\n valuesProvided: !isAnyErr,\n actual: undefined,\n expected: expectedErrorMsgStr\n } satisfies FailedAssertion);\n\n const errStr = `Expected thrown error but got none | Expected: \"${expectedErrorMsgStr}\"`\n debug(`${logPrefix} - Assertion failed: ${errStr}`);\n\n failTest(test, failureMessage, new Error(), logPrefix);\n\n // Must throw here to halt WASM execution on an assertion or runtime failure for this test.\n // This will be caught by the executor and reported as an appropriate test error\n // using test.meta.lastError value set in failTest()\n throw createPoolError(\n `AssemblyScript __end_expect_throw() import called during test execution for ${test.name}`,\n POOL_ERROR_NAMES.WASMExecutionAbortError,\n );\n }\n },\n },\n\n // user imports for any other environments they defined\n ...(userCustomEnvImports ?? {}),\n };\n\n return {\n imports,\n provideFunctionTable: (table: WebAssembly.Table) => {\n debug(`${logPrefix} - Got WASM function table | length: ${table.length}`);\n wasmFunctionTable = table;\n },\n };\n}\n","/**\n * Error Enhancement and Source Mapping\n *\n * This module handles mapping WASM errors to AssemblyScript source locations\n * using source maps. It enhances error messages and stack traces with accurate\n * file:line:column information for better developer experience.\n */\n\nimport { type ParsedStack } from '@vitest/utils';\nimport { diff, type SerializedDiffOptions } from '@vitest/utils/diff';\nimport type { Test, Suite } from '@vitest/runner/types';\nimport { type RawSourceMap, SourceMapConsumer } from 'source-map';\n\nimport type { AssemblyScriptTestError, HighlightFunc, WebAssemblyCallSite } from '../types/types.js';\nimport { debug } from '../util/debug.js';\nimport { POOL_INTERNAL_PATHS, TEST_ERROR_NAMES } from '../types/constants.js';\nimport { createWebAssemblyCallSite, parseSourceMap } from './source-maps.js';\nimport { getShortFunctionName } from './wasm-names.js';\nimport {\n getSourceCodeFrameString,\n toPlaintextStackFrameString,\n toVitestLikeStackFrameString,\n} from '../util/test-error-formatting.js';\n\nconst POOL_INTERNAL_PATHS_SET = new Set(POOL_INTERNAL_PATHS);\n\nasync function sourceMapRawCallStack(\n rawCallStack: NodeJS.CallSite[],\n sourceMap: RawSourceMap,\n loggingPrefix: string,\n): Promise<WebAssemblyCallSite[]> {\n const mappedStack: WebAssemblyCallSite[] = [];\n\n if (!rawCallStack || rawCallStack.length === 0) {\n return mappedStack;\n }\n\n const sourceMapConsumer = await new SourceMapConsumer(sourceMap);\n \n // map stack call sites from raw WASM locations to source locations \n rawCallStack.forEach(callSite => {\n const mappedCallSite = createWebAssemblyCallSite(callSite, sourceMapConsumer, loggingPrefix);\n if (mappedCallSite) {\n mappedStack.push(mappedCallSite);\n }\n }); \n \n sourceMapConsumer.destroy();\n\n return mappedStack;\n}\n\n// Parse source-mapped stack array to Vitest TestError reporting format\nfunction parseMappedStack(mappedStack: WebAssemblyCallSite[]): ParsedStack[] {\n return mappedStack\n // filter out frames for internal assertion framework calls\n // (e.g. assert(), assertEqual(), etc) by known location, for more concise/meaningful error stack report\n .filter(frame => !(POOL_INTERNAL_PATHS_SET.has(frame.location.filePath)))\n \n // map to format that vitest reporter can display\n .map(frame => ({\n method: getShortFunctionName(frame.functionName),\n file: frame.location.filePath,\n line: frame.location.line,\n column: frame.location.column + 1, // Convert from raw 0-indexed to 1-indexed for display\n }));\n}\n\nexport async function processWASMErrorStack(\n rawCallStack: NodeJS.CallSite[],\n sourceMap: string,\n loggingPrefix: string,\n): Promise<{ parsedStack: ParsedStack[], parsedSourceMap: RawSourceMap }> {\n const sourceMapObj = parseSourceMap(sourceMap);\n\n // map stack call sites from WASM locations to source code locations \n const sourceMappedStack = await sourceMapRawCallStack(rawCallStack, sourceMapObj, loggingPrefix);\n\n debug(`${loggingPrefix} - Mapped ${rawCallStack.length} call sites to ${sourceMappedStack.length} source locations`);\n\n return {\n parsedStack: parseMappedStack(sourceMappedStack),\n parsedSourceMap: sourceMapObj,\n };\n}\n\n/**\n * Enhance reportable test error on the provided test result with source mapped stack locations\n * and a formatted diff based on the error type\n */\nexport async function enhanceTestError(\n error: AssemblyScriptTestError,\n task: Test | Suite,\n sourceMap: string,\n valuesProvided: boolean,\n logPrefix: string,\n highlight: HighlightFunc,\n rawCallStack?: NodeJS.CallSite[],\n diffOptions?: SerializedDiffOptions\n): Promise<AssemblyScriptTestError> {\n const isAssertionFailure = error.name === TEST_ERROR_NAMES.AssertionError;\n let expectedVsActualDiffString: string = '';\n\n if (isAssertionFailure && valuesProvided) {\n // remain undefined if there were no expected/actual values provided with the assertion failure\n expectedVsActualDiffString = diff(error.expected, error.actual, diffOptions) ?? '';\n }\n\n // if there's no stack to map, set the expected vs actual diff (if any) and return\n if (!rawCallStack || rawCallStack.length === 0) {\n error.diff = expectedVsActualDiffString;\n\n // stack is used by vitest for error deduplication, so make sure it is set\n error.stack = `${task.name} - ${error.message}`;\n\n return error;\n }\n\n // map stack call sites from WASM locations to source locations\n const { parsedStack, parsedSourceMap } = await processWASMErrorStack(rawCallStack, sourceMap, logPrefix);\n \n // build additional strings to add to test error's `diff` field based on parsed stack contents\n let primaryStackFrameString: string | undefined;\n let highlightedSourceCodeFrameString: string | undefined;\n \n if (parsedStack.length > 0) {\n const primaryStackFrame = parsedStack[0]!;\n \n primaryStackFrameString = toVitestLikeStackFrameString(primaryStackFrame);\n \n // Test error is set to rest of the stack without the first frame.\n // Vitest will report the ParsedError[] on TestError.stacks below the diff we set.\n error.stacks = parsedStack.slice(1);\n\n // get source code diff from source map source content\n highlightedSourceCodeFrameString = getSourceCodeFrameString(parsedSourceMap, primaryStackFrame, highlight);\n\n debug(`${logPrefix} - Enhanced ${error.name} error with parsed source stack`);\n }\n\n // Use the diff field as our way to show all output (other than result.error.stacks)\n if (isAssertionFailure) {\n error.diff = [\n `${expectedVsActualDiffString}${expectedVsActualDiffString ? '\\n\\n' : ''}`,\n `${primaryStackFrameString}\\n`,\n `${highlightedSourceCodeFrameString}`,\n ].join('');\n } else {\n error.diff = [\n `${primaryStackFrameString}\\n`,\n `${highlightedSourceCodeFrameString}`,\n ].join('');\n }\n\n // stack is used by vitest for error deduplication, so make sure it is set\n error.stack = parsedStack.map(toPlaintextStackFrameString).join('\\n');\n \n debug(`[${logPrefix} - Enhanced ${error.name} error with diffs`);\n\n return error;\n}\n","import { basename } from 'node:path';\nimport type { SerializedDiffOptions } from '@vitest/utils/diff';\nimport type { File, Test } from '@vitest/runner/types';\n\nimport type {\n AssemblyScriptConsoleLogHandler,\n AssemblyScriptPoolError,\n AssemblyScriptTestError,\n AssemblyScriptTestTaskMeta,\n CoverageData,\n ResolvedAssemblyScriptPoolOptions,\n ThreadImports,\n WASMCompilation,\n WASMExecutorPerfTimings,\n} from '../types/types.js';\nimport { POOL_ERROR_NAMES, TEST_ERROR_NAMES } from '../types/constants.js';\nimport { debug, debugOverride } from '../util/debug.js';\nimport { createMemory } from './wasm-memory.js';\nimport { createDiscoveryImports, createTestExecutionImports } from './wasm-imports.js';\nimport { enhanceTestError } from './wasm-errors.js';\nimport { createPoolError, createPoolErrorFromAnyError } from '../util/pool-errors.js';\nimport { getTaskLogLabel } from '../util/vitest-tasks.js';\nimport { extractCallStack } from './source-maps.js';\n\nconst SIG_MISMATCH_ERROR_MSG = `WASM RuntimeError indicates function signature type mismatch during test suite collection.`\n + ` This is likely caused by passing a non-void callback to expect().`\n + ` Use braces to ensure it returns void e.g. \\`expect(() => { failingFunction(); }).toThrowError()\\`.`\n + ` Look for the failing expect() within the describe() block indicated in the stack trace.`;\n\nfunction createExecutorPoolError(\n testFileBasename: string,\n context: string,\n reason: string,\n cause?: any,\n): AssemblyScriptPoolError {\n return createPoolError(\n `${testFileBasename} - ${context} WASM executor: ${reason}`,\n POOL_ERROR_NAMES.WASMExecutionHarnessError,\n undefined,\n cause\n );\n}\n\n/**\n * Discover tests via test() and suites via describe() registration calls\n */\nexport async function executeWASMDiscovery(\n binary: Uint8Array,\n sourceMap: string,\n testFileBasename: string,\n poolOptions: ResolvedAssemblyScriptPoolOptions,\n isBinaryInstrumented: boolean,\n handleLog: AssemblyScriptConsoleLogHandler,\n file: File,\n moduleLabel: string,\n threadImports: ThreadImports,\n diffOptions?: SerializedDiffOptions,\n): Promise<void> {\n const base = basename(file.filepath);\n const logPrefix = `[${moduleLabel} Exec] ${getTaskLogLabel(base, file)}`;\n const wasmModule = await WebAssembly.compile(binary as BufferSource);\n const memory = createMemory(poolOptions.testMemoryPagesInitial, poolOptions.testMemoryPagesMax);\n\n // Create coverage memory matching instrumentation expections (from user config).\n // While this memory will not be used, discovery instantiates the same binary,\n // and WebAssembly.Instance will throw if the expected memory sizes don't match\n const coverageMemory = isBinaryInstrumented ?\n createMemory(poolOptions.coverageMemoryPagesInitial, poolOptions.coverageMemoryPagesMax)\n : undefined;\n\n const importObject = createDiscoveryImports(\n memory,\n wasmModule,\n file,\n handleLog,\n logPrefix,\n coverageMemory,\n threadImports.createUserWasmImports\n );\n\n // Instantiate WASM module\n const instance = new WebAssembly.Instance(wasmModule, importObject);\n const exports = instance.exports as Record<string, unknown>;\n\n // Call _start to run top-level test() and describe()\n if (typeof exports._start === 'function') {\n try {\n exports._start();\n } catch (error) {\n const thrownErrAny: any = error as any;\n\n const isFunctionSignatureMismatch: boolean = error instanceof WebAssembly.RuntimeError\n && thrownErrAny?.message.includes('null function or function signature mismatch');\n if (isFunctionSignatureMismatch) {\n const runtimeError = error as WebAssembly.RuntimeError;\n const stack = extractCallStack(runtimeError);\n const testError = await enhanceTestError(\n {\n name: TEST_ERROR_NAMES.WASMRuntimeError,\n message: runtimeError.message\n } satisfies AssemblyScriptTestError,\n file,\n sourceMap,\n false,\n logPrefix,\n threadImports.highlight,\n stack,\n diffOptions\n );\n\n throw createPoolError(\n `${SIG_MISMATCH_ERROR_MSG}\\n Caused by: ${runtimeError.name}: ${runtimeError.message}`,\n POOL_ERROR_NAMES.PoolSyntaxError,\n undefined,\n testError\n );\n }\n\n // Check to see if error came from the discovery abort() handler\n // For discovery abort, test error is set on PoolError's `cause`,\n // and the raw call stack is on PoolError's `rawCallStack`\n if (\n thrownErrAny?.name === POOL_ERROR_NAMES.WASMExecutionAbortError\n && thrownErrAny?.cause?.name === TEST_ERROR_NAMES.WASMRuntimeError\n && (error as AssemblyScriptPoolError).rawCallStack\n ) {\n const thrownPoolErr = thrownErrAny as AssemblyScriptPoolError;\n thrownPoolErr.cause = await enhanceTestError(\n thrownPoolErr.cause as AssemblyScriptTestError,\n file,\n sourceMap,\n false,\n logPrefix,\n threadImports.highlight,\n thrownPoolErr.rawCallStack,\n diffOptions\n );\n thrownPoolErr.causeIsEnhancedError = true;\n\n // delete the raw stack so vitest doesn't complain about unexpected error values\n delete thrownPoolErr.rawCallStack;\n\n // rethrow it with the enhanced test error\n throw thrownPoolErr;\n } else {\n throw createPoolErrorFromAnyError(\n `${testFileBasename} - Unexpected discovery error`,\n POOL_ERROR_NAMES.WASMExecutionHarnessError,\n error\n );\n }\n }\n } else {\n throw createExecutorPoolError(testFileBasename, 'discoverTests', 'no _start() export');\n }\n\n debug(`${logPrefix} - Discovered ${file.tasks.length} top-level tasks`);\n return;\n}\n\n/**\n * Execute a single test with crash isolation\n */\nexport async function executeWASMTest(\n test: Test,\n compilation: WASMCompilation,\n testFileBasename: string,\n poolOptions: ResolvedAssemblyScriptPoolOptions,\n collectCoverage: boolean,\n handleLog: AssemblyScriptConsoleLogHandler,\n moduleLabel: string,\n threadImports: ThreadImports,\n diffOptions?: SerializedDiffOptions,\n): Promise<{ test: Test, testTimings: WASMExecutorPerfTimings }> {\n const testTimings: WASMExecutorPerfTimings = {\n fnInit: performance.now(),\n execStart: 0,\n execEnd: 0,\n fnfinal: 0\n };\n const base = basename(test.file.filepath);\n const fullModuleLabel = `${moduleLabel} Exec`;\n const taskLabel = getTaskLogLabel(base, test);\n const logPrefix = `[${fullModuleLabel}] ${taskLabel}`;\n\n function covDebug(...args: any[]): void {\n if (poolOptions.debugCoverageExtract) {\n debugOverride(...args);\n }\n };\n\n // Compile the binary to usable WASM module\n const wasmModule = await WebAssembly.compile(compilation.binary as BufferSource);\n\n // Create fresh memory for this test instance\n const memory = createMemory(poolOptions.testMemoryPagesInitial, poolOptions.testMemoryPagesMax);\n\n // Create coverage memory if collecting coverage (instrumented binary)\n const coverageMemory = collectCoverage ?\n createMemory(poolOptions.coverageMemoryPagesInitial, poolOptions.coverageMemoryPagesMax)\n : undefined;\n\n // Create import object with pool-side functions for capturing test execution results\n const { imports, provideFunctionTable } = createTestExecutionImports(\n memory,\n wasmModule,\n test,\n handleLog,\n logPrefix,\n coverageMemory,\n threadImports.createUserWasmImports\n );\n\n // Instantiate fresh WASM instance for this test\n const instance = new WebAssembly.Instance(wasmModule, imports);\n const exports = instance.exports as Record<string, unknown>;\n\n // Func table accessable because we're using the AS compiler --exportTable flag\n const table = exports.table as WebAssembly.Table | undefined;\n \n // allow imports to access table\n if (table && typeof table.get === 'function') {\n provideFunctionTable(table);\n }\n\n // Call _start to run top-level code. Test registration is stubbed/noop duing execution,\n // but this call is still needed to initialize any user-defined globals / other top level code.\n if (typeof exports._start === 'function') {\n // Not explicitly handling with try-catch here because failures in _start should be\n // caught during discovery and source-mapped. If this somehow fails, the worker still catches it.\n exports._start();\n } else {\n throw createExecutorPoolError(testFileBasename, 'executeWASMTest', 'no _start() export');\n }\n\n let testFn: (() => void) | null | undefined;\n \n if (table && typeof table.get === 'function') {\n const idx = (test.meta as AssemblyScriptTestTaskMeta).fnIndex;\n testFn = table.get(idx) as (() => void) | null;\n\n if (!testFn) {\n throw createExecutorPoolError(\n testFileBasename,\n 'executeWASMTest',\n `Test function at index ${idx} not found in function table`\n );\n }\n } else {\n throw createExecutorPoolError(\n testFileBasename,\n 'executeWASMTest',\n 'Function table not found in WASM exports (missing --exportTable flag?)'\n );\n }\n\n // try-catch to ensure we capture known test errors to report\n // as AssemblyScriptTestErrors to vitest\n try {\n // Execute this test\n testTimings.execStart = performance.now();\n testFn();\n testTimings.execEnd = performance.now();\n\n // If we reach here, test passed, i.e. No abort occurred.\n // Proceed below to prepare the test result\n } catch (error) {\n testTimings.execEnd = performance.now();\n\n const thrownErrAny = error as any;\n // If this is NOT a WASMExecutionAbort error, it means it did NOT originate from the\n // wasm abort() import and is unexpected, so we throw as a PoolError.\n //\n // Otherwise this IS a WASMExecutionAbort error and the wasm abort() import threw it as a\n // known test error (assertion or wasm runtime), so we continue to prepare the test result \n const isUnexpectedError = thrownErrAny?.name !== POOL_ERROR_NAMES.WASMExecutionAbortError;\n\n if (isUnexpectedError) {\n throw createExecutorPoolError(\n testFileBasename,\n 'executeWASMTest',\n `Unexpected execution error: ${error instanceof Error ? `${error.name}: ${error.message}` : String(error)}`,\n (error as any)?.cause\n );\n }\n }\n\n const meta = test.meta as AssemblyScriptTestTaskMeta;\n \n // If error is present, apply source mapping to make stack locations\n // useful, and add nicely-formatted diffs for reporting through vitest\n if (meta.lastError) {\n const enhancedError = await enhanceTestError(\n meta.lastError,\n test,\n compilation.sourceMap,\n meta.lastErrorValuesProvided ?? false,\n logPrefix,\n threadImports.highlight,\n meta.lastErrorRawCallStack,\n diffOptions\n );\n\n if (test.result) {\n if (test.result.errors) {\n test.result.errors.push(enhancedError);\n } else {\n test.result.errors = [enhancedError];\n }\n }\n\n delete meta.lastError;\n delete meta.lastErrorValuesProvided;\n delete meta.lastErrorRawCallStack;\n }\n\n // Extract coverage hits from coverage memory\n if (collectCoverage && compilation.debugInfo) {\n if (!coverageMemory) {\n throw createExecutorPoolError(\n testFileBasename,\n 'executeWASMTest',\n 'Coverage memory not created despite collectCoverage=true'\n );\n }\n\n const coverage: CoverageData = {\n hitCountsByFileAndPosition: {},\n };\n\n // Read counters from coverage memory\n const extractedHitCounters = new Uint32Array(coverageMemory.buffer, 0, compilation.debugInfo.instrumentedFunctionCount);\n covDebug(`${logPrefix} - Read coverage memory for ${compilation.debugInfo.instrumentedFunctionCount} instrumented functions`);\n\n // Iterate all instrumented functions and build coverage data with hit counts extracted from coverage memory\n let functionsHit = 0;\n for (const [filePath, debugFunctions] of Object.entries(compilation.debugInfo.functionsByFileAndPosition)) {\n if (!coverage.hitCountsByFileAndPosition[filePath]) {\n coverage.hitCountsByFileAndPosition[filePath] = {};\n covDebug(`${logPrefix} - Extracting hits for source file \"${filePath}\"`);\n }\n\n for (const [positionKey, funcInfos] of Object.entries(debugFunctions)) {\n // Sum hit counts across all functions at this position (multiple for generic monomorphizations)\n let positionHitCount = 0;\n for (const funcInfo of funcInfos) {\n if (funcInfo.coverageMemoryIndex === undefined) {\n debug(`${logPrefix} - WARNING: NO COVERAGE MEMORY INDEX`\n + ` - func \"${funcInfo.name}\" (${positionKey}) Skipping hit extraction`\n );\n continue;\n }\n\n const hitCount = extractedHitCounters[funcInfo.coverageMemoryIndex] ?? 0;\n covDebug(`${logPrefix} - func \"${funcInfo.name}\" (${positionKey}) `\n + `[idx: ${funcInfo.coverageMemoryIndex}]: ${hitCount} hits`\n );\n positionHitCount += hitCount;\n }\n\n coverage.hitCountsByFileAndPosition[filePath][positionKey] = positionHitCount;\n\n if (positionHitCount > 0) {\n functionsHit++;\n }\n }\n }\n\n meta.coverageData = coverage;\n debug(`${logPrefix} - Extracted coverage data | ${functionsHit} functions hit`);\n }\n\n testTimings.fnfinal = performance.now();\n\n return { test, testTimings };\n}\n","/**\n * RPC Reporting Helpers\n *\n * This module provides helper functions for reporting test lifecycle events\n * to Vitest via RPC. All helpers are designed to be composable and reusable.\n */\n\nimport type { MessagePort } from 'node:worker_threads';\nimport { createBirpc } from 'birpc';\nimport type { RunnerRPC, RuntimeRPC, UserConsoleLog } from 'vitest';\nimport type {\n File,\n Suite,\n Test,\n Task,\n TaskEventPack, \n TaskResultPack,\n CancelReason,\n} from '@vitest/runner/types';\n\nimport type {\n AssemblyScriptConsoleLog,\n AssemblyScriptCoveragePayload,\n AssemblyScriptSuiteTaskMeta,\n VitestVersion,\n WorkerRPC\n} from '../types/types.js';\nimport { debug } from '../util/debug.js';\nimport { COVERAGE_PAYLOAD_FORMATS } from '../types/constants.js';\nimport {\n createAfterSuiteRunMeta,\n getTaskLogLabel,\n isSuiteOwnFile\n} from '../util/vitest-tasks.js';\n\n// ============================================================================\n// RPC Client Factory\n// ============================================================================\n\n/** Create RPC client from MessagePort */\nexport function createRpcClient(port: MessagePort): WorkerRPC {\n return createBirpc<RuntimeRPC, RunnerRPC>(\n {\n onCancel: (_reason: CancelReason) => void { }\n },\n {\n post: (v) => port.postMessage(v),\n on: (fn) => port.on('message', fn),\n }\n );\n}\n\n// ============================================================================\n// File Task Reporting\n// ============================================================================\n\n/** Report file as queued (before compilation & discovery starts) */\nexport async function reportFileQueued(\n rpc: WorkerRPC,\n fileTask: File,\n logModule: string,\n logLabel: string,\n): Promise<void> {\n await rpc.onQueued(fileTask);\n debug(`[${logModule} RPC] ${logLabel} - Reported onQueued for file \"${fileTask.filepath}\"`\n + ` | mode: \"${fileTask.mode}\" | state: \"${fileTask.result ? fileTask.result.state : '--'}\"`\n );\n}\n\n/** Report file collection complete with full task tree */\nexport async function reportFileCollected(\n rpc: WorkerRPC,\n fileTask: File,\n logModule: string,\n logLabel: string,\n): Promise<void> {\n await rpc.onCollected([fileTask]);\n debug(`[${logModule} RPC] ${logLabel} - Reported onCollected for file \"${fileTask.filepath}\"`\n + ` | ${fileTask.tasks.length} tasks | mode: \"${fileTask.mode}\" | state: \"${fileTask.result?.state}\"`\n );\n}\n\n/** Report file-level error (compilation/discovery failure) as \"suite-failed-early\" */\nexport async function reportFileError(\n rpc: WorkerRPC,\n fileTask: File, \n logModule: string,\n logLabel: string,\n): Promise<void> {\n const taskPack: TaskResultPack = [fileTask.id, fileTask.result, {}];\n const eventPack: TaskEventPack = [fileTask.id, \"suite-failed-early\", undefined];\n await rpc.onTaskUpdate([taskPack], [eventPack]);\n\n debug(`[${logModule} RPC] ${logLabel} - Reported \"suite-failed-early\" task update for \"${fileTask.filepath}\"`);\n}\n\n// ============================================================================\n// Suite Lifecycle Reporting\n// ============================================================================\n\n/** Report suite-prepare event */\nexport async function reportSuitePrepare(\n rpc: WorkerRPC,\n suite: Suite,\n logModule: string,\n base: string,\n): Promise<void> {\n // Report suite event (without the custom task meta so reporters won't log it)\n const taskPack: TaskResultPack = [suite.id, suite.result, {}];\n const eventPack: TaskEventPack = [suite.id, 'suite-prepare', undefined];\n\n await rpc.onTaskUpdate([taskPack], [eventPack]);\n\n debug(`[${logModule} RPC] ${getTaskLogLabel(base, suite)} - Reported \"suite-prepare\" task update`\n + ` | state: \"${suite.result?.state}\"`\n );\n}\n\n/** Report suite-finished event */\nexport async function reportSuiteFinished(\n rpc: WorkerRPC,\n suite: Suite,\n logModule: string,\n base: string,\n vitestVersion: VitestVersion = 'v4',\n): Promise<void> {\n const suiteLabel = getTaskLogLabel(base, suite);\n const rpcLogPrefix = `[${logModule} RPC] ${suiteLabel}`;\n const meta = suite.meta as AssemblyScriptSuiteTaskMeta;\n const coverageKeys: number = Object.keys(meta.coverageData?.hitCountsByFileAndPosition ?? {}).length;\n let coveragePromise: Promise<void> = Promise.resolve();\n \n // Report coverage if this is a file task, and coverage is available\n if (isSuiteOwnFile(suite) && coverageKeys > 0) {\n const coverage: AssemblyScriptCoveragePayload = {\n __format: COVERAGE_PAYLOAD_FORMATS.AssemblyScript,\n coverageData: meta.coverageData!,\n suiteLogLabel: suiteLabel\n };\n \n const afterSuiteMeta = createAfterSuiteRunMeta(\n coverage,\n [suite.file.filepath],\n suite.file.projectName,\n vitestVersion\n );\n coveragePromise = rpc.onAfterSuiteRun(afterSuiteMeta);\n\n debug(`${rpcLogPrefix} - onAfterSuiteRun: Reported suite coverage (${coverageKeys} unique positions)`);\n } else if (coverageKeys === 0) {\n debug(`${rpcLogPrefix} - onAfterSuiteRun: No suite coverage to report`);\n }\n\n // Report suite event (without the custom task meta so reporters won't log it)\n const taskPack: TaskResultPack = [suite.id, suite.result, {}];\n const eventPack: TaskEventPack = [suite.id, \"suite-finished\", undefined];\n\n await Promise.all([\n coveragePromise,\n rpc.onTaskUpdate([taskPack], [eventPack])\n ]);\n\n debug(`${rpcLogPrefix} - Reported \"suite-finished\" task update | state: \"${suite.result?.state}\"`\n + ` | duration: ${suite.result?.duration?.toFixed(2) ?? '--'} ms`\n );\n}\n\n// ============================================================================\n// Test Lifecycle Reporting\n// ============================================================================\n\nasync function reportTestTaskUpdate(\n rpc: WorkerRPC,\n test: Test,\n logModule: string,\n base: string,\n updateEvent: 'test-prepare' | 'test-finished' | 'test-retried'\n): Promise<void> {\n // Report test event (without the custom task meta so reporters won't log it)\n const taskPack: TaskResultPack = [test.id, test.result, {}];\n const eventPack: TaskEventPack = [test.id, updateEvent, undefined];\n\n debug(`[${logModule} RPC] ${getTaskLogLabel(base, test)} - Reporting \"${updateEvent}\" task update...`\n + ` | state: \"${test.result?.state}\"`\n + `${updateEvent === 'test-prepare' ? '' : ` | duration: ${test.result?.duration?.toFixed(2) ?? '--'} ms`}`\n );\n await rpc.onTaskUpdate([taskPack], [eventPack]);\n debug(`[${logModule} RPC] ${getTaskLogLabel(base, test)} - Reported \"${updateEvent}\" task update`\n + ` | state: \"${test.result?.state}\"`\n + `${updateEvent === 'test-prepare' ? '' : ` | duration: ${test.result?.duration?.toFixed(2) ?? '--'} ms`}`\n );\n}\n\n/** Report test starting execution */\nexport async function reportTestPrepare(\n rpc: WorkerRPC,\n test: Test,\n logModule: string,\n base: string,\n): Promise<void> {\n return reportTestTaskUpdate(rpc, test, logModule, base, 'test-prepare');\n}\n\n/** Report test finished execution */\nexport async function reportTestFinished(\n rpc: WorkerRPC,\n test: Test,\n logModule: string,\n base: string,\n): Promise<void> {\n return reportTestTaskUpdate(rpc, test, logModule, base, 'test-finished');\n}\n\n/** Report test retried (sent when test failed and is going to be retried) */\nexport async function reportTestRetried(\n rpc: WorkerRPC,\n test: Test,\n logModule: string,\n base: string,\n): Promise<void> {\n return reportTestTaskUpdate(rpc, test, logModule, base, 'test-retried');\n}\n\n// ============================================================================\n// Other Reporting\n// ============================================================================\n\n/** Report user console log messages */\nexport async function reportUserConsoleLogs(\n rpc: WorkerRPC,\n logs: AssemblyScriptConsoleLog[],\n logModule: string,\n base: string,\n task: Task,\n): Promise<void> {\n if (logs.length === 0) {\n return;\n }\n\n const stdLogs = logs.filter(l => !l.isError);\n const errorLogs = logs.filter(l => l.isError);\n\n const stdContent: string = stdLogs.map(l => `${l.msg}`).join('\\n');\n const errorContent: string = errorLogs.filter(l => l.isError).map(l => `${l.msg}`).join('\\n');\n\n const stdLog: UserConsoleLog = {\n content: `${stdContent}\\n`,\n size: stdContent.length,\n browser: false,\n type: 'stdout',\n time: stdLogs.length > 0 ? stdLogs[0]!.time : Date.now(),\n taskId: task.id,\n origin: task.id\n };\n \n const errorLog: UserConsoleLog = {\n content: `${errorContent}\\n`,\n size: errorContent.length,\n browser: false,\n type: 'stderr',\n time: errorLogs.length > 0 ? errorLogs[0]!.time : Date.now(),\n taskId: task.id,\n origin: task.id\n };\n\n const reportPromises: Promise<void>[] = [];\n if (stdContent.length > 0) {\n reportPromises.push(rpc.onUserConsoleLog(stdLog));\n }\n if (errorContent.length > 0) {\n reportPromises.push(rpc.onUserConsoleLog(errorLog));\n }\n\n await Promise.all(reportPromises);\n\n debug(`[${logModule} RPC] ${getTaskLogLabel(base, task)} - Reported onUserConsoleLog | ${logs.length} messages`);\n}\n\n// ============================================================================\n// Final Flush\n// ============================================================================\n\n/** Flush any pending RPC updates */\nexport async function flushRpcUpdates(\n rpc: WorkerRPC,\n): Promise<void> {\n await rpc.onTaskUpdate([], []);\n}\n","import { resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport type { WasmImportsFactory } from '../types/types.js';\nimport { debug } from '../util/debug.js';\nimport { AS_POOL_ERROR_TYPE_FLAG } from '../types/constants.js';\n\nexport async function loadUserWasmImportsFactory(\n relativePath: string | undefined,\n projectRoot: string,\n logModule: string,\n): Promise<WasmImportsFactory | undefined> {\n if (!relativePath) {\n return undefined;\n }\n\n const path = resolve(projectRoot, relativePath);\n const safeUrl = pathToFileURL(path).href;\n\n try {\n const start = performance.now();\n const createWasmImports = (await import(safeUrl)).default;\n debug(`[${logModule}] TIMING Imported user WasmImportsFactory in ${(performance.now() - start).toFixed(2)} ms`);\n\n if (typeof createWasmImports !== 'function') {\n throw new Error(\n `User config for \\`wasmImportsFactor\\` must be the path to a module with a default export matching () => WebAssembly.Imports `\n + `- Imported: \"${typeof createWasmImports}\": ${String(createWasmImports)}`\n );\n } else {\n return createWasmImports;\n }\n } catch (error) {\n if ((error as any)[AS_POOL_ERROR_TYPE_FLAG]) {\n throw error;\n }\n \n throw new Error(\n `Could not load user WasmImportsFactory from \"${safeUrl}\".`\n + ` Ensure that your module path is relative to the project root (location of shallowest vitest config),`\n + ` and that it has a default export matching () => WebAssembly.Imports`,\n { cause: error }\n );\n }\n};\n"],"mappings":";;;;;;;;;;;AAAA,MAAM,4BAA4B;;;;;;;;;;;;;;;;AAiBlC,SAAgB,WACd,QACA,SACoB;AACpB,KAAI,CAAC,QAAS,QAAO;CAErB,MAAM,WAAW,YAAY;CAM7B,MAAM,kBAJY,WAAW,MAIS;CACtC,MAAM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,OAAO,CACjB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pool-runner-init-BDQtAGwQ.mjs","names":[],"sources":["../src/pool/pool-worker.ts","../src/pool/pool-runner-init.ts"],"sourcesContent":["import { availableParallelism } from 'node:os';\nimport { resolve } from 'node:path';\nimport { access } from 'node:fs/promises';\nimport type { MessagePort } from 'node:worker_threads';\nimport type { Test } from '@vitest/runner/types';\nimport type { SerializedConfig } from 'vitest';\nimport type { PoolWorker, PoolOptions, WorkerRequest, PoolTask, WorkerResponse } from 'vitest/node';\nimport Tinypool from 'tinypool';\n\nimport type {\n AssemblyScriptPoolWorkerMessage,\n ResolvedAssemblyScriptPoolOptions,\n ResolvedHybridProviderOptions,\n RunCompileAndDiscoverTask,\n RunTestsTask,\n TestExecutionEnd,\n TestExecutionStart,\n TestRunRecord,\n ThreadSpec,\n WorkerThreadInitData,\n} from '../types/types.js';\nimport { toForwardSlash } from '../util/path-utils.js';\nimport { createInitialFileTask } from '../util/vitest-file-tasks.js';\nimport { failTestWithTimeoutError, flagTestTerminated } from '../util/vitest-tasks.js';\nimport {\n AS_POOL_WORKER_MSG_FLAG,\n ASSEMBLYSCRIPT_POOL_NAME,\n POOL_ERROR_NAMES,\n VITEST_WORKER_RESPONSE_MSG_FLAG\n} from '../types/constants.js';\nimport { debug, setGlobalDebugMode } from '../util/debug.js';\nimport { createPoolError, createPoolErrorFromAnyError, isAbortError } from '../util/pool-errors.js';\nimport { createWorkerRPCChannel } from './worker-rpc-channel.js';\n\ntype GlobalThreadPools = { compilePool: Tinypool, runPool: Tinypool };\ntype EventCallback = (arg: any) => void;\n\nconst THREAD_RESOLVE_TIMEOUT_MS = 2000 as const;\nconst POOL_THREAD_IDLE_TIMEOUT_MS = 3_600_000 as const;\nconst IDLE_RUN_THREADS_FACTOR = 1 as const;\n// @ts-ignore - see note in getGlobalThreadPools\nconst IDLE_COMPILE_THREADS_FACTOR = 0.25 as const;\n\n// path assumes that we're running from dist/\nconst COMPILE_WORKER_PATH = resolve(import.meta.dirname, 'pool-thread/compile-worker-thread.mjs');\nconst TEST_WORKER_PATH = resolve(import.meta.dirname, 'pool-thread/test-worker-thread.mjs');\n\nvar GLOBAL_POOLS_PROMISE: Promise<GlobalThreadPools> | undefined;\nvar GLOBAL_POOL_ABORT_CONTROLLER: AbortController | undefined;\nvar GLOBAL_RUNNING_POOLWORKER_COUNT: number = 0;\n\nexport class AssemblyScriptPoolWorker implements PoolWorker {\n readonly logModule = 'PoolWorker' as const;\n readonly name: typeof ASSEMBLYSCRIPT_POOL_NAME = ASSEMBLYSCRIPT_POOL_NAME;\n readonly poolOptions: PoolOptions;\n readonly asPoolOptions: ResolvedAssemblyScriptPoolOptions;\n readonly asCoverageOptions: ResolvedHybridProviderOptions;\n\n // for the currently running thread preforming a test run (if any)\n private threadAbortController: AbortController | undefined;\n private threadControlPort: MessagePort | undefined;\n private threadRunPromise: Promise<void> | undefined;\n\n private threadSpecs: ThreadSpec[] = [];\n \n // cached data for possible timeout resume\n private currentTestRun: TestRunRecord | undefined;\n \n // for this particular PoolWorker instance (1 per `maxWorkers`)\n private currentWorkerId: number | undefined;\n private isWorkerRunning: boolean = false;\n private config: SerializedConfig | undefined; // provided with \"start\" message\n\n // registry holding vitest callbacks so we can communicate on behalf of the worker thread\n private listenerRegistry: Map<string, Set<EventCallback>>;\n\n constructor(\n options: PoolOptions,\n resolvedUserPoolOptions: ResolvedAssemblyScriptPoolOptions,\n resolvedCoverageOptions: ResolvedHybridProviderOptions,\n ) {\n const start = performance.now();\n\n this.poolOptions = options;\n this.asPoolOptions = resolvedUserPoolOptions;\n this.asCoverageOptions = resolvedCoverageOptions;\n this.listenerRegistry = new Map<string, Set<EventCallback>>();\n\n setImmediate(async () => {\n const userImportsFactoryPath = resolve(\n this.poolOptions.project.config.root,\n this.asPoolOptions.wasmImportsFactory ?? ''\n );\n\n const results = await Promise.allSettled([\n access(COMPILE_WORKER_PATH),\n access(TEST_WORKER_PATH),\n this.asPoolOptions.wasmImportsFactory ? access(userImportsFactoryPath) : Promise.resolve()\n ]);\n\n const failedThreadAccess: string[] = [];\n if (results[0].status === 'rejected') failedThreadAccess.push(COMPILE_WORKER_PATH);\n if (results[1].status === 'rejected') failedThreadAccess.push(TEST_WORKER_PATH);\n\n if (failedThreadAccess.length) {\n throw new Error(`Cannot access worker thread file(s) at path(s): ${failedThreadAccess}`);\n }\n if (results[2].status === 'rejected') {\n throw new Error(`Cannot access user WasmImportsFactory at path: \"${userImportsFactoryPath}\".`\n + ` Ensure that your module path is relative to the vitest project root (location of shallowest vitest config),`\n + ` and that it has a default export matching () => WebAssembly.Imports`\n );\n }\n });\n \n setGlobalDebugMode(this.asPoolOptions.debug);\n\n debug(`[${this.logModule}] Created AssemblyScriptPoolWorker in ${(performance.now() - start).toFixed(2)} ms`\n + ` | method: \"${this.poolOptions.method}\" | project: \"${this.poolOptions.project.name}\"`\n );\n }\n\n private get isCollectTestsMode(): boolean {\n return this.poolOptions.method === 'collect';\n }\n\n async start(): Promise<void> {\n // do all work in send() message intercept handler so we have access to the config\n }\n\n async stop(): Promise<void> {\n debug(`[${this.logModuleWithId}] stop | running PoolWorker count: ${GLOBAL_RUNNING_POOLWORKER_COUNT}`);\n\n this.listenerRegistry.clear();\n GLOBAL_RUNNING_POOLWORKER_COUNT--;\n this.isWorkerRunning = false;\n\n debug(`[${this.logModuleWithId}] AssemblyScriptPoolWorker STOPPED | running PoolWorker count: ${GLOBAL_RUNNING_POOLWORKER_COUNT}`);\n this.currentWorkerId = undefined;\n }\n\n send(message: WorkerRequest): void {\n switch(message.type) {\n \n // this happens AFTER start() is called (start() is for PoolWorker, \"start\" is for thread)\n case 'start':\n this.currentWorkerId = message.workerId;\n this.config = message.context.config;\n debug(`[${this.logModuleWithId}] send: vitest sent \"start\" message | Captured workerId and config`);\n\n setImmediate(async () => {\n const start = performance.now();\n const { compilePool, runPool } = await this.getGlobalThreadPools(this.config?.maxWorkers);\n \n debug(`[${this.logModuleWithId}] start: fetched global thread pools in ${(performance.now() - start).toFixed(2)} ms`\n + ` | compilePool queueSize: ${compilePool.queueSize} | runPool queueSize: ${runPool.queueSize}`\n );\n \n this.isWorkerRunning = true;\n GLOBAL_RUNNING_POOLWORKER_COUNT++;\n debug(`[${this.logModuleWithId}] start | new running PoolWorker count: ${GLOBAL_RUNNING_POOLWORKER_COUNT}`);\n \n this.notifyVitest('started');\n debug(`[${this.logModuleWithId}] send: responded \"started\" to vitest`);\n });\n \n break;\n \n // this happens BEFORE stop() is called (stop() is for PoolWorker, \"stop\" is for thread)\n case 'stop':\n setImmediate(async () => {\n await this.stopThread();\n this.notifyVitest('stopped');\n });\n break;\n \n case 'cancel':\n debug(`[${this.logModuleWithId}] send: got \"cancel\" unexpectedly`, message);\n break;\n \n case 'collect':\n case 'run':\n this.currentWorkerId = message.context.workerId;\n this.threadSpecs = message.context.files.map((fileSpec): ThreadSpec => ({\n file: createInitialFileTask(\n toForwardSlash(fileSpec.filepath),\n this.config!.name ?? '',\n this.config!.root,\n this.config!.testTimeout,\n this.config!.retry\n )\n }));\n\n debug(`[${this.logModuleWithId}] send: vitest sent \"${message.type}\" message`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n\n setImmediate(async () => {\n debug(`[${this.logModuleWithId}] send: dispatched \"${message.type}\" job to worker thread`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n \n this.threadRunPromise = this.orchestrateFileRuns();\n\n try {\n await this.threadRunPromise;\n this.notifyVitest('testfileFinished');\n debug(`[${this.logModuleWithId}] send: responded \"testfileFinished\" to vitest`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n\n this.threadSpecs = [];\n } catch (error) {\n if (!isAbortError(error)) {\n throw createPoolErrorFromAnyError(`PoolWorker send() \"${message.type}\"`, POOL_ERROR_NAMES.PoolError, error);\n }\n } finally {\n this.threadControlPort?.close();\n this.threadAbortController = undefined;\n this.threadControlPort = undefined;\n this.threadRunPromise = undefined;\n }\n });\n break;\n }\n }\n\n on(event: string, callback: EventCallback): void {\n this.addEventCallback(event, callback);\n debug(`[${this.logModuleWithId}] ON \"${event}\" - saved listener`);\n }\n\n off(event: string, callback: EventCallback): void {\n if (this.removeEventCallback(event, callback)) {\n debug(`[${this.logModuleWithId}] OFF \"${event}\" - removed callback from registry`);\n } else {\n debug(`[${this.logModuleWithId}] OFF \"${event}\" - callback not found in registry`);\n }\n }\n\n deserialize(data: unknown): unknown {\n return data;\n }\n\n canReuse(_task: PoolTask): boolean {\n return true;\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Thread Pool Management\n // ─────────────────────────────────────────────────────────────────────────────\n\n private async getGlobalThreadPools(workerCount?: number): Promise<GlobalThreadPools> {\n if (GLOBAL_POOLS_PROMISE) {\n return GLOBAL_POOLS_PROMISE;\n }\n\n GLOBAL_POOLS_PROMISE = new Promise<GlobalThreadPools>(async (resolve, _reject) => {\n const workers = workerCount ?? availableParallelism();\n\n // TODO - decide which is better when scaling\n // Empirical observations seem to show that minimum parallelization for compilation\n // tends to *dramatically* improve compilation times because of v8 warmpup on repeated calls to asc.main,\n // so much so that this time savings **almost always** outweighs the benefits of speading over many\n // available threads. The **almost** is the key word here- this needs to be tested on platforms with\n // higher available paralellism (> 8) to see if it holds true.\n const actualCompileThreadCount = workers > 1 ? 2 : 1;\n // const actualCompileThreadCount = Math.max(Math.ceil(workers * IDLE_COMPILE_THREADS_FACTOR), 1);\n\n debug(`[${this.logModuleWithId}] Creating global compile thread pool | ${actualCompileThreadCount} threads`);\n \n const start = performance.now();\n \n const compilePool = new Tinypool({\n filename: COMPILE_WORKER_PATH,\n minThreads: 1,\n maxThreads: actualCompileThreadCount,\n isolateWorkers: false,\n idleTimeout: POOL_THREAD_IDLE_TIMEOUT_MS,\n env: this.poolOptions.env as Record<string, string>,\n execArgv: this.poolOptions.execArgv,\n workerData: {\n asPoolOptions: this.asPoolOptions,\n asCoverageOptions: this.asCoverageOptions,\n projectRoot: this.poolOptions.project.config.root,\n } satisfies WorkerThreadInitData\n });\n\n const actualRunThreadCount = Math.max(Math.ceil(workers * IDLE_RUN_THREADS_FACTOR), 1);\n debug(`[${this.logModuleWithId}] Creating global run thread pool | ${actualRunThreadCount} threads`);\n\n const runPool = new Tinypool({\n filename: TEST_WORKER_PATH,\n minThreads: 1,\n maxThreads: actualRunThreadCount,\n isolateWorkers: false,\n idleTimeout: POOL_THREAD_IDLE_TIMEOUT_MS,\n env: this.poolOptions.env as Record<string, string>,\n execArgv: this.poolOptions.execArgv,\n workerData: {\n asPoolOptions: this.asPoolOptions,\n asCoverageOptions: this.asCoverageOptions,\n projectRoot: this.poolOptions.project.config.root\n } satisfies WorkerThreadInitData\n });\n\n debug(`[${this.logModuleWithId}] Created global thread pools in ${(performance.now() - start).toFixed(2)} ms`);\n\n GLOBAL_POOL_ABORT_CONTROLLER = new AbortController();\n resolve({ compilePool, runPool });\n });\n \n return GLOBAL_POOLS_PROMISE;\n }\n\n // @ts-ignore\n // pools are never explicitly destroyed.\n // - vitest processes are short-lived\n // - when PoolWorkers are stopped, they cleanup actively-running thread tasks\n // - in practice stop happens after every run, even in watch mode\n // - keeping pools hot is desirable for watch mode re-runs, so we maintain our pools\n private async destroyGlobalPoolsIfNeeded(): Promise<void> {\n if (GLOBAL_RUNNING_POOLWORKER_COUNT === 0 && GLOBAL_POOLS_PROMISE) {\n const destroyStart = performance.now();\n debug(`[${this.logModuleWithId}] Destroying Tinypools...`);\n\n try {\n const { compilePool, runPool } = await GLOBAL_POOLS_PROMISE;\n await Promise.all([ compilePool.destroy(), runPool.destroy() ]);\n } catch {}\n\n GLOBAL_POOLS_PROMISE = undefined;\n GLOBAL_POOL_ABORT_CONTROLLER = undefined;\n\n debug(`[${this.logModuleWithId}] Destroyed tinypools in ${(performance.now() - destroyStart).toFixed(2)} ms`);\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Listener Registry Helpers\n // ─────────────────────────────────────────────────────────────────────────────\n\n private getEventCallbacks(event: string): Set<EventCallback> {\n let callbacks: Set<EventCallback> | undefined = this.listenerRegistry.get(event);\n if (!callbacks) {\n callbacks = new Set<EventCallback>();\n this.listenerRegistry.set(event, callbacks);\n }\n return callbacks;\n }\n\n private addEventCallback(event: string, callback: EventCallback): void {\n this.getEventCallbacks(event).add(callback);\n }\n \n private removeEventCallback(event: string, callback: EventCallback): boolean {\n const callbacks = this.getEventCallbacks(event);\n if (callbacks) {\n return callbacks.delete(callback);\n } else {\n return false;\n }\n }\n\n private notifyVitest(responseType: WorkerResponse['type']): void {\n const messageCallbacks = this.getEventCallbacks('message');\n for (const cb of messageCallbacks) {\n cb({ type: responseType, [VITEST_WORKER_RESPONSE_MSG_FLAG]: true } satisfies WorkerResponse)\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────────\n // Worker Thread Control/Orchestration\n // ─────────────────────────────────────────────────────────────────────────────\n \n private async dispatchCompile(\n spec: ThreadSpec,\n compilePool: Tinypool,\n ): Promise<void> {\n const { workerPort, poolPort } = createWorkerRPCChannel(this.poolOptions.project, this.isCollectTestsMode);\n this.threadControlPort = poolPort;\n \n const compilePromise: Promise<ThreadSpec> = compilePool.run({\n dispatchStart: Date.now(),\n workerId: this.currentWorkerId!,\n port: workerPort,\n file: spec.file,\n config: this.config!,\n isCollectTestsMode: this.isCollectTestsMode,\n } satisfies RunCompileAndDiscoverTask, {\n name: 'runCompileAndDiscoverSpec',\n transferList: [workerPort],\n signal: GLOBAL_POOL_ABORT_CONTROLLER!.signal,\n });\n\n try {\n const { compilation, file } = await compilePromise;\n spec.file = file;\n spec.compilation = compilation;\n } finally {\n this.threadControlPort.close();\n this.threadControlPort = undefined;\n }\n }\n \n private async dispatchRunTests(\n spec: ThreadSpec,\n runPool: Tinypool,\n timedOutTest?: Test,\n ): Promise<void> {\n const { workerPort, poolPort } = createWorkerRPCChannel(this.poolOptions.project, this.isCollectTestsMode);\n \n this.threadAbortController = new AbortController();\n this.threadControlPort = poolPort;\n this.threadControlPort.on('message', this.getWorkerThreadMessageHandler());\n\n const runPromise: Promise<void> = !spec.compilation ? Promise.resolve() : runPool.run({\n dispatchStart: Date.now(),\n workerId: this.currentWorkerId!,\n port: workerPort,\n file: timedOutTest?.file ?? spec.file,\n compilation: spec.compilation,\n config: this.config!,\n isCollectTestsMode: this.isCollectTestsMode,\n timedOutTest,\n } satisfies RunTestsTask, {\n name: 'runFileSpec',\n transferList: [workerPort],\n signal: AbortSignal.any([this.threadAbortController.signal, GLOBAL_POOL_ABORT_CONTROLLER!.signal]),\n });\n\n try {\n return await runPromise;\n } finally {\n this.threadControlPort.close();\n this.threadControlPort = undefined;\n }\n }\n\n private async orchestrateFileRuns(timedOutTest?: Test): Promise<void> {\n const modeStr = this.isCollectTestsMode ? 'collectTests' : 'runTests';\n const isResume: boolean = !!timedOutTest;\n const desc = `${modeStr} ${isResume ? '(RESUME)' : '(INITIAL)'}`;\n\n debug(`[${this.logModuleWithId}] orchestrateFileRuns: dispatching ${desc} to worker thread`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n\n const { compilePool, runPool } = await this.getGlobalThreadPools(this.config?.maxWorkers);\n\n // compile\n if (!isResume) {\n await Promise.all(\n this.threadSpecs.map(spec => this.dispatchCompile(spec, compilePool))\n );\n }\n\n // test\n if (!this.isCollectTestsMode) {\n await Promise.all(\n this.threadSpecs.map(spec => this.dispatchRunTests(spec, runPool, timedOutTest))\n );\n }\n\n debug(`[${this.logModuleWithId}] orchestrateFileRuns: ${desc} thread work complete`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n }\n\n private async stopThread(): Promise<void> {\n this.clearTestTimeoutTimer(); // if any\n this.currentTestRun = undefined;\n \n const mod = this.logModuleWithId;\n const start = performance.now();\n\n debug('setting graceful resolve timeout');\n const abortTimeout = setTimeout(() => {\n debug(`[${mod}] stop: timed out waiting on pool worker run resolve ${(performance.now() - start).toFixed(2)} ms | Aborting thread`);\n this.threadAbortController?.abort();\n }, THREAD_RESOLVE_TIMEOUT_MS);\n \n try {\n debug(`[${mod}] stop: awaiting pool worker run resolve: ${!!this.threadRunPromise}`);\n await this.threadRunPromise;\n clearTimeout(abortTimeout);\n debug(`[${this.logModuleWithId}] stop: pool worker run resolved cleanly after ${(performance.now() - start).toFixed(2)} ms`);\n } catch {\n } finally {\n this.threadControlPort?.close();\n debug(`[${this.logModuleWithId}] stop: closed pool port`);\n }\n \n this.threadAbortController = undefined;\n this.threadControlPort = undefined;\n this.threadRunPromise = undefined;\n this.threadSpecs = [];\n }\n\n private getWorkerThreadMessageHandler(): EventCallback {\n return (message: any): void => {\n if (message[AS_POOL_WORKER_MSG_FLAG]) {\n const poolMessage = message as AssemblyScriptPoolWorkerMessage;\n\n switch (poolMessage.type) {\n case 'execution-start':\n this.handleTestExecutionStart(message);\n break;\n case 'execution-end':\n this.handleTestExecutionEnd(message);\n break;\n }\n\n return;\n }\n };\n }\n\n private handleTestExecutionStart(msg: TestExecutionStart): void {\n if (!this.isWorkerRunning) return;\n \n const { executionStart, test } = msg;\n const now = Date.now();\n const transitDuration = now - executionStart;\n const adjustedTimeout = Math.max(test.timeout - transitDuration, 0);\n\n this.currentTestRun = {\n test,\n executionStart,\n timeoutId: setTimeout(() => this.handleTimeout(), adjustedTimeout)\n };\n\n debug(`[${this.logModuleWithId}] START test timeout timer for \"${this.currentTestRun.test.name}\"`);\n }\n\n private handleTestExecutionEnd(_msg: TestExecutionEnd): void {\n this.clearTestTimeoutTimer();\n this.currentTestRun = undefined;\n }\n\n private clearTestTimeoutTimer(): void {\n if (this.currentTestRun) {\n const elapsed = Date.now() - this.currentTestRun.executionStart;\n debug(`[${this.logModuleWithId}] CLEAR test timeout timer (${elapsed.toFixed(2)} ms) for \"${this.currentTestRun?.test.name}\"`);\n clearTimeout(this.currentTestRun.timeoutId);\n }\n }\n\n private async handleTimeout(): Promise<void> {\n if (!this.isWorkerRunning) return;\n\n if (!this.threadSpecs.length || !this.currentTestRun || !this.currentTestRun.test) {\n const missingStr = \n + (this.threadSpecs.length ? '' : 'threadSpecs')\n + (this.currentTestRun ? '' : ' currentTestRecord')\n + (this.currentTestRun?.test ? '' : ' currentTestRecord.test')\n throw createPoolError(\n `Cannot timeout/resume worker thread for workerId ${this.currentWorkerId} - missing data: ${missingStr}`,\n POOL_ERROR_NAMES.PoolError\n );\n }\n\n const duration = Date.now() - this.currentTestRun.executionStart;\n failTestWithTimeoutError(this.currentTestRun.test, this.currentTestRun.executionStart, duration);\n\n // set termination time metadata for measuring resume latency\n flagTestTerminated(this.currentTestRun.test);\n\n debug(`[${this.logModuleWithId}] handleTimeout: TEST TIMEOUT \"${this.currentTestRun.test.name}\" after ${duration.toFixed(2)} ms`\n +` - Terminating worker thread job`\n );\n\n const termStart = performance.now();\n \n try {\n this.threadAbortController?.abort();\n await this.threadRunPromise;\n } catch (error) {\n if (!isAbortError(error)) {\n throw createPoolErrorFromAnyError(`PoolWorker handleTimeout`, POOL_ERROR_NAMES.PoolError, error);\n }\n } finally {\n this.threadControlPort?.close();\n this.threadAbortController = undefined;\n this.threadControlPort = undefined;\n this.threadRunPromise = undefined;\n }\n\n debug(`[${this.logModuleWithId}] handleTimeout: Worker thread job aborted for timeout in ${(performance.now() - termStart).toFixed(2)} ms`);\n \n if (!this.isWorkerRunning) return;\n\n // supply timed-out test (includes entire file hierarchy & coverage)\n // to resume testing where we leftoff when aborting for timeout\n this.threadRunPromise = this.orchestrateFileRuns(this.currentTestRun.test);\n\n debug(`[${this.logModuleWithId}] handleTimeout: re-dispatched job to worker thread`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n\n try {\n await this.threadRunPromise;\n this.notifyVitest('testfileFinished');\n debug(`[${this.logModuleWithId}] handleTimeout: file run completed - responded \"testfileFinished\" to vitest`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n \n this.threadSpecs = [];\n } catch (error) {\n if (!isAbortError(error)) {\n throw createPoolErrorFromAnyError(`PoolWorker handleTimeout`, POOL_ERROR_NAMES.PoolError, error);\n } else {\n debug(`[${this.logModuleWithId}] send: caught and ignored timeout awaiting timeout re-run`\n + ` | files: \"${this.threadSpecs.map(s => s.file.filepath).join(',')}\"`\n );\n }\n } finally {\n //@ts-ignore\n this.threadControlPort?.close();\n this.threadControlPort = undefined;\n this.threadAbortController = undefined;\n this.threadRunPromise = undefined;\n }\n }\n\n private get logModuleWithId(): string {\n return `${this.logModule}${this.currentWorkerId === undefined ? '' : ` ${this.currentWorkerId}`}`;\n }\n}\n","import type { PoolOptions, PoolRunnerInitializer } from 'vitest/node';\n\nimport type {\n AssemblyScriptPoolOptions,\n ResolvedHybridProviderOptions\n} from '../types/types.js';\nimport { ASSEMBLYSCRIPT_POOL_NAME } from '../types/constants.js';\nimport { resolvePoolOptions } from '../util/resolve-config.js';\nimport { AssemblyScriptPoolWorker } from './pool-worker.js';\n\nexport function createAssemblyScriptPool(userPoolOptions?: AssemblyScriptPoolOptions): PoolRunnerInitializer {\n const resolvedUserPoolOptions = resolvePoolOptions(userPoolOptions);\n\n return {\n name: ASSEMBLYSCRIPT_POOL_NAME,\n createPoolWorker: (opts: PoolOptions) => {\n const resolvedCoverageOptions = opts.project.config.coverage as ResolvedHybridProviderOptions;\n return new AssemblyScriptPoolWorker(opts, resolvedUserPoolOptions, resolvedCoverageOptions);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,MAAM,4BAA4B;AAClC,MAAM,8BAA8B;AACpC,MAAM,0BAA0B;AAKhC,MAAM,sBAAsB,QAAQ,OAAO,KAAK,SAAS,wCAAwC;AACjG,MAAM,mBAAmB,QAAQ,OAAO,KAAK,SAAS,qCAAqC;AAE3F,IAAI;AACJ,IAAI;AACJ,IAAI,kCAA0C;AAE9C,IAAa,2BAAb,MAA4D;CAC1D,AAAS,YAAY;CACrB,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CAGT,AAAQ;CACR,AAAQ;CACR,AAAQ;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EAAE,KAAK,SAAS,CAAC,KAAK,IAAI,CAAC,GACtE;AAED,QAAK,cAAc,EAAE;WACd,OAAO;AACd,OAAI,CAAC,aAAa,MAAM,CACtB,OAAM,4BAA4B,4BAA4B,iBAAiB,WAAW,MAAM;OAEhG,OAAM,IAAI,KAAK,gBAAgB,uEACb,KAAK,YAAY,KAAI,MAAK,EAAE,KAAK,SAAS,CAAC,KAAK,IAAI,CAAC,GACtE;YAEK;AAER,QAAK,mBAAmB,OAAO;AAC/B,QAAK,oBAAoB;AACzB,QAAK,wBAAwB;AAC7B,QAAK,mBAAmB;;;CAI5B,IAAY,kBAA0B;AACpC,SAAO,GAAG,KAAK,YAAY,KAAK,oBAAoB,SAAY,KAAK,IAAI,KAAK;;;;;;ACxmBlF,SAAgB,yBAAyB,iBAAoE;CAC3G,MAAM,0BAA0B,mBAAmB,gBAAgB;AAEnE,QAAO;EACL;EACA,mBAAmB,SAAsB;GACvC,MAAM,0BAA0B,KAAK,QAAQ,OAAO;AACpD,UAAO,IAAI,yBAAyB,MAAM,yBAAyB,wBAAwB;;EAE9F"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pool-runner-init-CvnB0-iN.d.mts","names":[],"sources":["../src/pool/pool-runner-init.ts"],"mappings":";;;;iBAUgB,wBAAA,CAAyB,eAAA,GAAkB,yBAAA,GAA4B,qBAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolve-config-DhZ4lOSK.mjs","names":[],"sources":["../src/types/types.ts","../src/util/resolve-config.ts"],"sourcesContent":["/*\n * Shared TypeScript types and interfaces\n */\n\nimport type { MessagePort } from 'node:worker_threads';\nimport type { BirpcReturn } from 'birpc';\nimport type { RunnerRPC, RuntimeRPC, SerializedConfig, SerializedCoverageConfig } from 'vitest';\nimport type { TestError } from '@vitest/utils';\nimport type { ResolvedConfig, ResolvedCoverageOptions } from 'vitest/node';\nimport type { File, Test, TaskMeta, TestOptions } from '@vitest/runner/types';\nimport type { Colors } from 'tinyrainbow';\n\nimport {\n AS_POOL_WORKER_MSG_FLAG,\n AS_POOL_ERROR_TYPE_FLAG,\n COVERAGE_PAYLOAD_FORMATS,\n POOL_ERROR_NAMES,\n TEST_ERROR_NAMES,\n} from './constants.js';\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/** Error name type derived from TEST_ERROR_NAMES values */\nexport type TestErrorName = typeof TEST_ERROR_NAMES[keyof typeof TEST_ERROR_NAMES];\n\n/** Error name type derived from POOL_ERROR_NAMES values */\nexport type PoolErrorName = typeof POOL_ERROR_NAMES[keyof typeof POOL_ERROR_NAMES];\n\n/**\n * Conforms to Error interface but with required, strictly-typed name field.\n * Thrown internally for all pool errors.\n * \n * Must be thrown as a POJO (not using the Error() constructor!) to be properly\n * serialized across worker-pool boundery.\n */\nexport interface AssemblyScriptPoolError extends Error {\n readonly [AS_POOL_ERROR_TYPE_FLAG]: true;\n name: PoolErrorName;\n rawCallStack?: NodeJS.CallSite[];\n causeIsEnhancedError?: boolean;\n}\n\n/**\n * Extended vitest TestError with required, strictly-typed name field.\n * This is an explicitly serializable error format constructred to report\n * Test/Suite failures to vitest.\n */\nexport type AssemblyScriptTestError = TestError & { name: TestErrorName | PoolErrorName };\n\n/**\n * Native build error marker file content.\n * Written by install script when native addon compilation fails.\n * Read at runtime to display detailed error information to users.\n */\nexport interface NativeBuildError {\n stage: 'binaryen-download' | 'native-compile';\n error: string;\n platform: string;\n timestamp: string;\n}\n\n// ============================================================================\n// User Configuration\n// ============================================================================\n\n/**\n * AssemblyScript pool configuration options\n */\nexport interface AssemblyScriptPoolOptions {\n /** Enable verbose debug logging */\n debug?: boolean;\n debugNative?: boolean;\n debugCoverageExtract?: boolean;\n\n /** enable to collect coverage instrumentation on the pool's assembly/* files */\n _instrumentPoolInternals?: boolean;\n\n /**\n * Strip `@inline` decorators during compilation to improve error message and coverage accuracy\n *\n * - When true (default): `@inline` decorators removed, functions become visible in coverage\n * and source mapped errors point to the correct lines\n * - When false: `@inline` functions are inlined by compiler, missing from coverage, and \n * error line numbers don't match the non-inlined source\n * @default true\n */\n stripInline?: boolean;\n\n /**\n * Maximum number of worker threads to spawn with vitest 3.x.\n * Defaults to os.availableParallelism() - 1\n * \n * Use project config `test.maxWorkers` with vitest 4.x to control\n * the number of cuncurrently executing tests. \n */\n maxThreadsV3?: number;\n\n coverageMemoryPagesInitial?: number;\n coverageMemoryPagesMax?: number;\n\n testMemoryPagesInitial?: number;\n testMemoryPagesMax?: number;\n\n extraCompilerFlags?: string[];\n\n wasmImportsFactory?: string;\n}\n\n/**\n * HybridCoverageProvider configuration options.\n */\nexport interface HybridProviderOptions {\n provider: 'custom',\n customProviderModule: string;\n\n debugIstanbul?: boolean;\n\n /**\n * Glob patterns for AssemblyScript source files to include in coverage.\n * Used to build the complete AS coverage map.\n *\n * The standard `include` patterns are used by the v8 provider for JS/TS files.\n *\n * @example ['assembly/**\\/*.as.ts']\n */\n assemblyScriptInclude?: string[];\n\n /**\n * Glob patterns for AssemblyScript files to exclude from coverage.\n *\n * @example ['**\\/*.as.test.ts']\n */\n assemblyScriptExclude?: string[];\n}\n\nexport interface WasmImportsFactoryInfo {\n module: WebAssembly.Module;\n memory: WebAssembly.Memory;\n utils: {\n liftString: (stringPtr: number) => string | undefined;\n }\n}\n\nexport type WasmImportsFactory = (moduleInfo: WasmImportsFactoryInfo) => WebAssembly.Imports;\n\n// define these constants here so they make sense in context\nexport const AS_POOL_FIELDS_WITH_DEFAULTS = [\n 'debug',\n 'debugNative',\n 'debugCoverageExtract',\n '_instrumentPoolInternals',\n 'stripInline',\n 'maxThreadsV3',\n 'coverageMemoryPagesInitial',\n 'coverageMemoryPagesMax',\n 'testMemoryPagesInitial',\n 'extraCompilerFlags'\n] as const;\nexport const AS_POOL_OPTIONAL_FIELDS = ['testMemoryPagesMax', 'wasmImportsFactory'] as const;\n\n/** Fields that have default values. Internally these will always be defined. */\nexport type ASPoolOptionsFieldsWithDefaultValues = typeof AS_POOL_FIELDS_WITH_DEFAULTS[number];\n\n/** Fields with optional values and NO defaults */\nexport type ASPoolOptionsOptionalFields = typeof AS_POOL_OPTIONAL_FIELDS[number];\n\nexport type AssemblyScriptProjectConfig = (SerializedConfig & {\n coverage: SerializedCoverageConfig & ResolvedHybridProviderOptions;\n}) | ResolvedConfig & {\n coverage: ResolvedHybridProviderOptions;\n};\n\n /**\n * Pool options resolved so that all fields are filled with user values preferentially, \n * with required fields being guaranteed to be populated with defaults otherwise.\n */\nexport type ResolvedAssemblyScriptPoolOptions =\n Required<Pick<AssemblyScriptPoolOptions, ASPoolOptionsFieldsWithDefaultValues>>\n & Partial<Pick<AssemblyScriptPoolOptions, ASPoolOptionsOptionalFields>>\n & { readonly isResolved: true };\n\nexport type ResolvedHybridProviderOptions = \n Required<HybridProviderOptions>\n & Omit<ResolvedCoverageOptions<'v8'>, 'provider'>\n & {\n globbedAssemblyScriptInclude: GlobResult[],\n globbedAssemblyScriptProjectRelativeExcludeOnly: string[],\n };\n\n// vitest TestOptions fields that are supported by AssemblyScript tests in this pool\nexport type AssemblyScriptTestOptions = Required<Pick<TestOptions, 'timeout' | 'retry' | 'skip' | 'only' | 'fails'>>;\n\n// ============================================================================\n// Utility Types\n// ============================================================================\n\nexport type VitestVersion = 'v3' | 'v4';\n\nexport interface ThreadImports {\n highlight: HighlightFunc;\n createUserWasmImports?: WasmImportsFactory;\n}\n\nexport type HighlightFunc = (code: string, options: { colors: Colors }) => string;\n\nexport interface GlobResult {\n absolute: string;\n projectRootRelative: string;\n}\n\n// ============================================================================\n// Compilation & Results\n// ============================================================================\n\nexport interface AssemblyScriptCompilerOptions {\n shouldInstrument: boolean;\n projectRoot: string;\n instrumentationOptions?: InstrumentationOptions;\n stripInline?: boolean;\n extraFlags?: string[];\n}\n\nexport interface AssemblyScriptCompilerResult {\n binary: Uint8Array;\n sourceMap: string;\n debugInfo?: BinaryDebugInfo;\n isInstrumented: boolean;\n compileTiming: number;\n}\n\nexport interface InstrumentationOptions {\n /** Project root for resolving source map paths to absolute paths */\n projectRoot: string;\n /** List of relative file paths to exclude from instrumentation */\n relativeExcludedFiles: string[];\n excludedLibraryFilePrefix: string;\n coverageMemoryPagesMin: number;\n coverageMemoryPagesMax: number;\n excludedLibraryFileOverridePrefix?: string;\n debug?: boolean;\n}\n\n/**\n * Result of instrumenting a WASM binary for coverage\n */\nexport interface InstrumentationResult {\n /** Instrumented WASM binary with coverage counter increments */\n instrumentedWasm: Buffer;\n /** Regenerated source map (offsets adjusted for instrumentation) */\n sourceMap: string;\n /** Debug info with coverageMemoryIndex assigned to each function */\n debugInfo: BinaryDebugInfo;\n}\n\n// ============================================================================\n// Error Source Mapping\n// ============================================================================\n\n/**\n * Source location in original AssemblyScript code (a point, not a range)\n *\n * All values are 1-based for internal consistency.\n * Conversion to 0-based columns happens at Istanbul output boundary.\n */\nexport interface SourceLocation {\n /** Absolute file path (normalized from source map during debug info extraction) */\n filePath: string;\n line: number;\n column: number;\n}\n\n/**\n * WebAssembly call site with mapped source location\n */\nexport interface WebAssemblyCallSite {\n functionName: string;\n location: SourceLocation;\n}\n\n// ============================================================================\n// Coverage Data (Runtime Hit Counts)\n// ============================================================================\n\n/**\n * Coverage data collected during test execution\n *\n * Simple hit count storage using position-based keys for stable merging.\n * Note: Function source metadata (names, ranges) comes from ParsedSourceInfo.\n *\n * Outer Record: keyed by absolute file path\n * Inner Record: keyed by position (\"line:column\") → hit count\n */\nexport interface CoverageData {\n hitCountsByFileAndPosition: Record<string, Record<string, number>>;\n}\n\n/**\n * Coverage payload sent via RPC from worker to hybrid coverage provider\n *\n * The __format marker distinguishes AS coverage from JS coverage in onAfterSuiteRun.\n */\nexport interface AssemblyScriptCoveragePayload {\n readonly __format: typeof COVERAGE_PAYLOAD_FORMATS.AssemblyScript;\n coverageData: CoverageData;\n suiteLogLabel: string;\n}\n\n\n// ============================================================================\n// Binary Debug Info (returned from native instrumentation addon)\n// ============================================================================\n//\n// These types represent debug information extracted from compiled WASM binaries\n// via the native addon. Binary debug info only has POINTS (from source map),\n// not ranges. Ranges come from source parsing (ParsedSource* types below).\n//\n// Naming convention: *DebugInfo suffix indicates binary-extracted data.\n\n/**\n * Source range in original AssemblyScript code (start and end points)\n *\n * All values are 1-based for internal consistency.\n * Conversion to 0-based columns happens at Istanbul output boundary.\n */\nexport interface SourceRange {\n /** Relative file path */\n filePath: string;\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n}\n\n/**\n * Branch edge in control flow graph\n */\nexport interface BranchEdgeDebugInfo {\n /** Target basic block index */\n targetBlockIndex: number;\n /** Index of the expression that creates this branch (e.g., if condition) */\n sourceExpressionIndex?: number;\n}\n\n/**\n * Expression debug info extracted from WASM binary\n *\n * Expressions are the smallest unit of execution in WASM.\n * In v2, each expression can be mapped to a source statement for line-level coverage.\n */\nexport interface ExpressionDebugInfo {\n /** WASM expression type (e.g., \"call\", \"if\", \"block\") */\n type: string;\n /** Source location (POINT, not range) from source map */\n location?: SourceLocation;\n /** Whether this expression is a branch point (if, switch, select) */\n isBranch: boolean;\n /** Number of branch paths (for branch coverage) */\n branchPaths?: number;\n /**\n * Index into coverage memory counters\n * v2 only: Propagated from containing BasicBlockDebugInfo by TS wrapper\n */\n coverageMemoryIndex?: number;\n}\n\n/**\n * Basic block debug info from CFG analysis\n *\n * Basic blocks are sequences of expressions with single entry/exit points.\n * In v2, counters are placed at basic block boundaries for efficient coverage.\n */\nexport interface BasicBlockDebugInfo {\n /** Block index within the function */\n index: number;\n /** Indices of expressions contained in this block */\n expressionIndices: number[];\n /** Outgoing branch edges */\n branches: BranchEdgeDebugInfo[];\n /**\n * Index into coverage memory counters\n * v2 only: Source of truth for block-level coverage\n */\n coverageMemoryIndex?: number;\n}\n\n/**\n * Function debug info extracted from WASM binary via native addon\n */\nexport interface FunctionDebugInfo {\n /** WASM function index */\n wasmIndex: number;\n /** Function name from WASM (informational) */\n name: string;\n /**\n * Representative source location (a point within the function).\n * Used for containment matching to find the parsedsource function.\n */\n representativeLocation: SourceLocation;\n /** Index into coverage memory counters */\n coverageMemoryIndex: number;\n /** All expressions in this function */\n expressions: ExpressionDebugInfo[];\n /** Basic blocks from CFG analysis */\n basicBlocks: BasicBlockDebugInfo[];\n}\n\n/**\n * Binary debug info extracted from WASM + source map via native addon\n *\n * This is the processed output after TS wrapper transforms NativeDebugInfoOutput.\n * Functions are grouped by file and keyed by position for stable identity.\n */\nexport interface BinaryDebugInfo {\n /** All source files represented in extracted debug info (directly or inlined) */\n debugSourceFiles: string[];\n /**\n * Functions grouped by file path, then keyed by position (\"line:column\").\n * Position key enables stable identity across compilations.\n * Array value accommodates generic monomorphizations that share a source position.\n */\n functionsByFileAndPosition: Record<string, Record<string, FunctionDebugInfo[]>>;\n\n instrumentedFunctionCount: number;\n}\n\n/**\n * Raw output from native addon's instrumentForCoverage() C++ function\n */\nexport interface NativeInstrumentationResult {\n instrumentedWasm: Buffer;\n sourceMap: string;\n debugInfo: NativeDebugInfoOutput;\n errors?: string[];\n}\n\nexport interface NativeDebugInfoOutput {\n /** All source files represented in extracted debug info (directly or inlined) */\n debugSourceFiles: string[];\n /** Flat list of all functions with their debug info */\n functions: NativeFunctionDebugInfo[];\n}\n\nexport interface NativeFunctionDebugInfo extends Omit<FunctionDebugInfo, 'expressions' | 'representativeLocation'> {\n representativeLocation: NativeSourceLocation;\n expressions: NativeExpressionDebugInfo[];\n}\n\nexport interface NativeExpressionDebugInfo extends Omit<ExpressionDebugInfo, 'location'> {\n location?: NativeSourceLocation;\n}\n\nexport interface NativeSourceLocation extends Omit<SourceLocation, 'filePath'> {\n /** Index into NativeDebugInfoOutput.debugSourceFiles */\n fileIndex: number;\n}\n\nexport interface NativeInstrumentationOptions extends Omit<InstrumentationOptions, 'relativeExcludedFiles' | 'projectRoot'> {\n excludedFiles?: string[];\n logPrefix?: string;\n}\n\nexport type InstrumentForCoverageFunc = (\n wasmBuffer: Buffer,\n sourceMapBuffer: Buffer,\n instrumentationOptions: InstrumentationOptions,\n logModule: string,\n logLabel: string,\n) => InstrumentationResult;\n\nexport interface NativeAddonInterface {\n instrumentForCoverage: InstrumentForCoverageFunc;\n}\n\n/**\n * Typed interface for the native addon's exported methods.\n * The addon is loaded via node-gyp-build at runtime (CJS .node binary).\n */\nexport interface NativeAddon {\n instrumentForCoverage(\n wasmBuffer: Buffer,\n sourceMapBuffer: Buffer,\n options: NativeInstrumentationOptions,\n ): NativeInstrumentationResult;\n}\n\n// ============================================================================\n// Parsed Source Info (from AST Parser)\n// ============================================================================\n//\n// These types represent information parsed from source files via AST.\n// Parsed source info has *ranges* (start and end positions) for containment matching.\n\n/**\n * Function info parsed from AssemblyScript source via AST\n */\nexport interface ParsedSourceFunctionInfo {\n /** Fully \"qualified\" (WASM debug) name */\n qualifiedName: string;\n /** Short name for display */\n shortName: string;\n /** Source range for containment matching */\n range: SourceRange;\n}\n\n/**\n * Statement info parsed from AssemblyScript source via AST\n *\n * v2 only: Used for line-level statement coverage.\n * Binary expression points are matched to source statement ranges.\n */\nexport interface ParsedSourceStatementInfo {\n /** Source range for containment matching */\n range: SourceRange;\n /** Statement type (e.g., \"variable\", \"expression\", \"return\") */\n statementType?: string;\n}\n\n/**\n * Branch info parsed from AssemblyScript source via AST\n *\n * v2 only: Used for branch coverage.\n * Binary branch expressions are matched to source branch ranges.\n */\nexport interface ParsedSourceBranchInfo {\n /** Source range for containment matching */\n range: SourceRange;\n /** Type of branch construct */\n branchType: 'if' | 'ternary' | 'switch' | 'logical';\n}\n\n/**\n * Complete parsed source info from AST parser\n *\n * Generated by coverage provider when processing coverage (not during compilation).\n * Provides the \"what SHOULD be covered\" view from source code.\n */\nexport interface ParsedSourceInfo {\n /**\n * Functions grouped by file path, then by start line for containment matching.\n * Multiple functions can start on the same line, but limiting matching to checking\n * only the functions grouped on the input position's line is very performant.\n */\n functionsByFileAndStartLine: Record<string, Record<number, ParsedSourceFunctionInfo[]>>;\n /**\n * Statements grouped by file path, then keyed by position (\"line:column\")\n * v2 only: For line-level statement coverage\n */\n statementsByFileAndPosition: Record<string, Record<string, ParsedSourceStatementInfo>>;\n /**\n * Branches grouped by file path, then keyed by position (\"line:column\")\n * v2 only: For branch coverage\n */\n branchesByFileAndPosition: Record<string, Record<string, ParsedSourceBranchInfo>>;\n}\n\n// ============================================================================\n// Worker Communication & RPC\n// ============================================================================\n\nexport interface AssemblyScriptConsoleLog {\n msg: string;\n time: number;\n isError: boolean;\n}\n\nexport type AssemblyScriptConsoleLogHandler = (msg: string, isError?: boolean) => void;\n\nexport interface FailedAssertion {\n expected?: string;\n actual?: string;\n valuesProvided?: boolean;\n typeName?: string;\n message?: string;\n}\n\nexport interface AssemblyScriptSuiteTaskMeta extends TaskMeta {\n idxInParentTasks: number;\n defaultTestOptions: AssemblyScriptTestOptions;\n suitePreparedSent: boolean;\n resultFinal: boolean;\n coverageData?: CoverageData;\n}\n\nexport interface AssemblyScriptTestTaskMeta extends TaskMeta {\n idxInParentTasks: number;\n fnIndex: number;\n assertionsPassedCount: number;\n assertionsFailed: FailedAssertion[];\n resultFinal: boolean;\n coverageData?: CoverageData;\n lastError?: AssemblyScriptTestError;\n lastErrorValuesProvided?: boolean;\n lastErrorRawCallStack?: NodeJS.CallSite[];\n lastTimeoutTerminationTime?: number;\n};\n\nexport interface WASMExecutorPerfTimings {\n /** function start */\n fnInit: number;\n /** test start: execStart - fnInit = env init time */\n execStart: number;\n /** test end: execEnd - execStart = test duration */\n execEnd: number;\n /** function end: fnFinal - execEnd = error prep and/or coverage extraction time */\n fnfinal: number;\n}\n\nexport type WorkerRPC = BirpcReturn<RuntimeRPC, RunnerRPC>;\n\n/**\n * Worker channel with RPC for suite-level communication\n */\nexport interface WorkerChannel {\n /** Port to send to worker for RPC communication */\n workerPort: MessagePort;\n /** Pool-side port for cleanup */\n poolPort: MessagePort;\n /** RPC client for calling Vitest methods (only remote functions matter for our usage) */\n rpc: WorkerRPC;\n}\n\nexport interface WorkerThreadInitData {\n projectRoot: string,\n asPoolOptions: ResolvedAssemblyScriptPoolOptions;\n asCoverageOptions: ResolvedHybridProviderOptions;\n}\n\nexport interface AssemblyScriptPoolWorkerMessageBase {\n readonly [AS_POOL_WORKER_MSG_FLAG]: true;\n readonly type: string;\n}\n\nexport interface TestFileCompiled extends AssemblyScriptPoolWorkerMessageBase {\n readonly type: 'file-compiled';\n compilation: WASMCompilation;\n}\n\n\nexport interface TestExecutionStart extends AssemblyScriptPoolWorkerMessageBase {\n readonly type: 'execution-start';\n executionStart: number;\n test: Test;\n}\n\nexport interface TestExecutionEnd extends AssemblyScriptPoolWorkerMessageBase {\n readonly type: 'execution-end';\n executionEnd: number;\n testTaskId: string;\n}\n\nexport type AssemblyScriptPoolWorkerMessage = TestExecutionStart | TestExecutionEnd | TestFileCompiled;\n\nexport interface WASMCompilation {\n filePath: string;\n binary: Uint8Array;\n sourceMap: string;\n debugInfo?: BinaryDebugInfo;\n}\n\nexport interface TestRunRecord {\n test: Test;\n executionStart: number;\n timeoutId: NodeJS.Timeout;\n}\n\nexport interface ThreadSpec {\n file: File;\n compilation?: WASMCompilation;\n}\n\nexport interface RunCompileAndDiscoverTask {\n dispatchStart: number;\n workerId: number;\n port: MessagePort;\n file: File;\n config: SerializedConfig;\n isCollectTestsMode: boolean;\n}\n\nexport interface RunTestsTask {\n dispatchStart: number;\n workerId: number;\n port: MessagePort;\n file: File;\n compilation: WASMCompilation;\n config: SerializedConfig;\n isCollectTestsMode: boolean;\n timedOutTest?: Test;\n}\n\nexport interface ProcessPoolRunFileTask {\n dispatchStart: number;\n port: MessagePort;\n file: File;\n config: SerializedConfig;\n isCollectTestsMode: boolean;\n timedOutTest?: Test;\n timedOutCompilation?: WASMCompilation;\n}\n","import type { TestProject, Vitest } from 'vitest/node';\nimport { availableParallelism } from 'node:os';\n\nimport type {\n AssemblyScriptPoolOptions,\n ASPoolOptionsFieldsWithDefaultValues,\n ResolvedAssemblyScriptPoolOptions,\n ResolvedHybridProviderOptions,\n AssemblyScriptProjectConfig,\n} from '../types/types.js';\nimport { AS_POOL_FIELDS_WITH_DEFAULTS } from '../types/types.js';\nimport { ASSEMBLYSCRIPT_POOL_NAME, POOL_ERROR_NAMES } from '../types/constants.js';\nimport { createPoolError } from '../util/pool-errors.js';\n\nconst DEFAULT_ASSEMBLYSCRIPT_POOL_OTIONS: Required<Pick<AssemblyScriptPoolOptions, ASPoolOptionsFieldsWithDefaultValues>> = {\n debug: false,\n debugNative: false,\n debugCoverageExtract: false,\n _instrumentPoolInternals: false,\n stripInline: true,\n maxThreadsV3: availableParallelism() - 1,\n coverageMemoryPagesInitial: 1,\n coverageMemoryPagesMax: 4,\n testMemoryPagesInitial: 1,\n extraCompilerFlags: [],\n} as const;\n\n// v4: used in runner init to parse user-provided param directly\nexport function resolvePoolOptions(userPoolOptions?: any): ResolvedAssemblyScriptPoolOptions {\n const poolOptions: AssemblyScriptPoolOptions = userPoolOptions ?? DEFAULT_ASSEMBLYSCRIPT_POOL_OTIONS;\n\n // resolve fields with defaults if user hasn't provided them\n for (const configKey of AS_POOL_FIELDS_WITH_DEFAULTS) {\n if (poolOptions[configKey] === undefined) {\n poolOptions[configKey] = DEFAULT_ASSEMBLYSCRIPT_POOL_OTIONS[configKey] as any;\n }\n }\n\n const resolved = { ...poolOptions, isResolved: true } as ResolvedAssemblyScriptPoolOptions;\n\n if (resolved.coverageMemoryPagesInitial < 1 || resolved.coverageMemoryPagesMax < 1) {\n throw createPoolError(\n `Coverage memory page size options must be positive - coverageMemoryPagesMin: ${resolved.coverageMemoryPagesInitial}`\n + ` | coverageMemoryPagesMax: ${resolved.coverageMemoryPagesMax}`,\n POOL_ERROR_NAMES.PoolConfigError\n );\n }\n \n if (resolved.testMemoryPagesInitial < 1 || (resolved.testMemoryPagesMax !== undefined && resolved.testMemoryPagesMax < 1)) {\n throw createPoolError(\n `Test memory page size options must be positive - testMemoryPagesMin: ${resolved.testMemoryPagesInitial}`\n + ` | testMemoryPagesMax: ${resolved.testMemoryPagesMax}`,\n POOL_ERROR_NAMES.PoolConfigError\n );\n }\n\n return resolved;\n}\n\n// v3 & hybrid coverage provider: used to get project config & poolOptions, with global coverage on project config\n// poolOptions will be undefined for v4 in coverage provider, but it doesn't need them\nexport function getProjectSerializedOrGlobalConfig(ctx: Vitest): {\n config: AssemblyScriptProjectConfig;\n foundProjectSerializedConfig: boolean;\n v3PoolOptions?: ResolvedAssemblyScriptPoolOptions;\n} {\n let testProject: TestProject | undefined;\n let foundProjectSerializedConfig: boolean = false;\n let v3PoolOptions: ResolvedAssemblyScriptPoolOptions | undefined;\n\n // In multi-project mode, ctx.config is the global config, not the project-specific config\n // We need to find our project in ctx.projects to get project-specific config at the \"pool level\" in v3,\n // and in the hybrid coverage provider regardless of version (specifically the project root)\n if (ctx.projects && ctx.projects.length > 0) {\n // Multi-project mode: find the first project using this pool\n // Use string.includes because project.config.pool resolves to the *path* of the dist file\n const project = ctx.projects.find(p => p.config.pool.includes(ASSEMBLYSCRIPT_POOL_NAME));\n\n if (project) {\n testProject = project;\n foundProjectSerializedConfig = true;\n }\n }\n\n const config = !!testProject ? {\n ...testProject.serializedConfig,\n coverage: {\n ...testProject.serializedConfig.coverage,\n ...(ctx.config.coverage as ResolvedHybridProviderOptions)\n }\n } : {\n ...ctx.config,\n coverage: ctx.config.coverage as ResolvedHybridProviderOptions\n };\n\n // @ts-ignore - we build with v4, but this is correct for v3 (has config.poolOptions)\n const maybeOptions: any = !!testProject ? testProject.config?.poolOptions?.assemblyScript : config?.poolOptions?.assemblyScript;\n if (maybeOptions) {\n v3PoolOptions = resolvePoolOptions(maybeOptions);\n }\n\n return {\n config,\n foundProjectSerializedConfig,\n v3PoolOptions\n };\n}"],"mappings":";;;;;AAoJA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;ACjJD,MAAM,qCAAsH;CAC1H,OAAO;CACP,aAAa;CACb,sBAAsB;CACtB,0BAA0B;CAC1B,aAAa;CACb,cAAc,sBAAsB,GAAG;CACvC,4BAA4B;CAC5B,wBAAwB;CACxB,wBAAwB;CACxB,oBAAoB,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;;;;;UASE,eAAA;;EAEf,gBAAA;;;;;;EAMA,0BAAA,EAA4B,MAAA,SAAe,MAAA,SAAe,iBAAA;EAE1D,yBAAA;AAAA;AAAA,UAsOe,eAAA;EACf,QAAA;EACA,MAAA,EAAQ,UAAA;EACR,SAAA;EACA,SAAA,GAAY,eAAA;AAAA;AAAA,UASG,UAAA;EACf,IAAA,EAAM,IAAA;EACN,WAAA,GAAc,eAAA;AAAA;AAAA,UAGC,yBAAA;EACf,aAAA;EACA,QAAA;EACA,IAAA,EAAM,WAAA;EACN,IAAA,EAAM,IAAA;EACN,MAAA,EAAQ,gBAAA;EACR,kBAAA;AAAA;AAAA,UAGe,YAAA;EACf,aAAA;EACA,QAAA;EACA,IAAA,EAAM,WAAA;EACN,IAAA,EAAM,IAAA;EACN,WAAA,EAAa,eAAA;EACb,MAAA,EAAQ,gBAAA;EACR,kBAAA;EACA,YAAA,GAAe,IAAA;AAAA;AAAA,UAGA,sBAAA;EACf,aAAA;EACA,IAAA,EAAM,WAAA;EACN,IAAA,EAAM,IAAA;EACN,MAAA,EAAQ,gBAAA;EACR,kBAAA;EACA,YAAA,GAAe,IAAA;EACf,mBAAA,GAAsB,eAAA;AAAA"}
@@ -1,61 +0,0 @@
1
- import { calculateSuiteHash, createFileTask, interpretTaskModes, someTasksAreOnly } from "@vitest/runner/utils";
2
-
3
- //#region src/types/typed-constants.ts
4
- const DEFAULT_ASSEMBLYSCRIPT_TEST_OPTIONS = {
5
- fails: false,
6
- skip: false,
7
- only: false
8
- };
9
-
10
- //#endregion
11
- //#region src/util/vitest-file-tasks.ts
12
- function createInitialFileTask(testFile, projectName, projectRoot, configTestTimeout, configRetry) {
13
- const file = createFileTask(testFile, projectRoot, projectName, "assemblyscript");
14
- file.mode = "queued";
15
- file.environmentLoad = 0;
16
- file.setupDuration = 0;
17
- file.meta = {
18
- idxInParentTasks: -1,
19
- defaultTestOptions: {
20
- ...DEFAULT_ASSEMBLYSCRIPT_TEST_OPTIONS,
21
- timeout: configTestTimeout,
22
- retry: configRetry
23
- },
24
- suitePreparedSent: false,
25
- resultFinal: false
26
- };
27
- return file;
28
- }
29
- function prepareFileTaskForCollection(file, testNamePattern, allowOnly) {
30
- calculateSuiteHash(file);
31
- interpretTaskModes(file, testNamePattern, void 0, someTasksAreOnly(file), false, allowOnly);
32
- if (file.mode === "queued") file.mode = "run";
33
- }
34
- function failFile(file, error, runStartPerf) {
35
- file.mode = "run";
36
- if (file.result) {
37
- file.result.state = "fail";
38
- file.result.errors = file.result.errors ? file.result.errors.concat(error) : [error];
39
- } else file.result = {
40
- state: "fail",
41
- errors: [error]
42
- };
43
- file.environmentLoad = file.environmentLoad ?? 0;
44
- file.setupDuration = performance.now() - runStartPerf;
45
- file.collectDuration = file.collectDuration ?? 0;
46
- return file;
47
- }
48
- function getFullTaskHierarchy(file) {
49
- function spacesForLevel(level) {
50
- return new Array(level + 1).fill(" ").join("");
51
- }
52
- function taskStr(task, level) {
53
- if (task.type === "test") return `${spacesForLevel(level)}ID: ${task.id} Mode: "${task.mode}" Test: "${task.name}"`;
54
- else return `${spacesForLevel(level)}ID: ${task.id} Mode: "${task.mode}" Suite: "${task.name}"\n` + task.tasks.map((t) => taskStr(t, level + 1)).join("\n");
55
- }
56
- return taskStr(file, 0);
57
- }
58
-
59
- //#endregion
60
- export { createInitialFileTask, failFile, getFullTaskHierarchy, prepareFileTaskForCollection };
61
- //# sourceMappingURL=vitest-file-tasks-Bn9CrWt_.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vitest-file-tasks-Bn9CrWt_.mjs","names":[],"sources":["../src/types/typed-constants.ts","../src/util/vitest-file-tasks.ts"],"sourcesContent":["/**\n * Typed Constants\n * \n * Constants which require importing ./types\n */\n\nimport { AssemblyScriptTestOptions } from './types.js';\n\n// hard-coded defaults only - timeout and retry defaults always come from vitest config\nexport const DEFAULT_ASSEMBLYSCRIPT_TEST_OPTIONS: Pick<AssemblyScriptTestOptions, 'fails' | 'skip' | 'only'> = {\n fails: false,\n skip: false,\n only: false\n};\n","import type { SerializedConfig } from 'vitest';\nimport type { File, Task } from '@vitest/runner/types';\nimport {\n calculateSuiteHash,\n createFileTask,\n interpretTaskModes,\n someTasksAreOnly\n} from '@vitest/runner/utils';\n\nimport { ASSEMBLYSCRIPT_POOL_NAME } from '../types/constants.js';\nimport { DEFAULT_ASSEMBLYSCRIPT_TEST_OPTIONS } from '../types/typed-constants.js';\nimport type {\n AssemblyScriptSuiteTaskMeta,\n AssemblyScriptTestError,\n AssemblyScriptTestOptions,\n} from '../types/types.js';\n\nexport function createInitialFileTask(\n testFile: string,\n projectName: string,\n projectRoot: string,\n configTestTimeout: number,\n configRetry: number,\n): File {\n const file: File = createFileTask(\n testFile,\n projectRoot,\n projectName,\n ASSEMBLYSCRIPT_POOL_NAME\n );\n\n file.mode = 'queued';\n file.environmentLoad = 0; // AS pool has no environment setup\n file.setupDuration = 0; // AS pool has no setup files\n\n const defaultTestOptions: AssemblyScriptTestOptions = {\n ...DEFAULT_ASSEMBLYSCRIPT_TEST_OPTIONS,\n timeout: configTestTimeout,\n retry: configRetry,\n };\n\n const meta: AssemblyScriptSuiteTaskMeta = {\n idxInParentTasks: -1, // file task has no parent, should never be used anyway\n defaultTestOptions,\n suitePreparedSent: false,\n resultFinal: false,\n }\n file.meta = meta;\n\n return file;\n}\n\nexport function createFailedFileTask(\n testFile: string,\n projectName: string,\n config: SerializedConfig,\n error: AssemblyScriptTestError,\n): File {\n const file: File = createFileTask(\n testFile,\n config.root,\n projectName,\n ASSEMBLYSCRIPT_POOL_NAME\n );\n file.mode = 'run';\n file.result = {\n state: 'fail',\n errors: [error]\n };\n file.environmentLoad = 0;\n file.setupDuration = 0;\n file.collectDuration = 0;\n\n return file;\n}\n\nexport function prepareFileTaskForCollection(\n file: File,\n testNamePattern?: RegExp,\n allowOnly?: boolean,\n): void {\n calculateSuiteHash(file);\n\n // Interpret task modes does the following:\n // 1. If only mode enabled on any test, flip all non-only test.mode to skip\n // 2. Apply test name pattern filtering (from -t flag) to skip if needed\n // 3. If all test modes are skip, set file task mode to skip\n const hasOnly = someTasksAreOnly(file);\n interpretTaskModes(\n file,\n testNamePattern, // user regexp\n undefined, // testLocations\n hasOnly, // onlyMode - true if only is used anywhere\n false, // parentIsOnly - always false for the file task\n allowOnly\n );\n\n // update from queued (onQueued report) to run (onCollected report)\n if (file.mode === 'queued') {\n file.mode = 'run';\n }\n}\n\nexport function failFile(\n file: File,\n error: AssemblyScriptTestError,\n runStartPerf: number,\n): File {\n file.mode = 'run';\n\n if (file.result) {\n file.result.state = 'fail';\n file.result.errors = file.result.errors ? file.result.errors.concat(error) : [error];\n } else {\n file.result = {\n state: 'fail',\n errors: [error]\n };\n }\n file.environmentLoad = file.environmentLoad ?? 0;\n file.setupDuration = performance.now() - runStartPerf;\n file.collectDuration = file.collectDuration ?? 0;\n\n return file;\n}\n\n\n\nexport function getFullTaskHierarchy(file: File): string {\n function spacesForLevel(level: number): string {\n return new Array(level + 1).fill(' ').join('');\n }\n\n function taskStr(task: Task, level: number): string {\n if (task.type === 'test') {\n return `${spacesForLevel(level)}ID: ${task.id} Mode: \"${task.mode}\" Test: \"${task.name}\"`;\n } else {\n const suiteStr = `${spacesForLevel(level)}ID: ${task.id} Mode: \"${task.mode}\" Suite: \"${task.name}\"\\n`;\n return suiteStr + task.tasks.map(t => taskStr(t, level + 1)).join('\\n');\n }\n };\n\n return taskStr(file, 0);\n}\n"],"mappings":";;;AASA,MAAa,sCAAkG;CAC7G,OAAO;CACP,MAAM;CACN,MAAM;CACP;;;;ACID,SAAgB,sBACd,UACA,aACA,aACA,mBACA,aACM;CACN,MAAM,OAAa,eACjB,UACA,aACA,8BAED;AAED,MAAK,OAAO;AACZ,MAAK,kBAAkB;AACvB,MAAK,gBAAgB;AAcrB,MAAK,OANqC;EACxC,kBAAkB;EAClB,oBARoD;GACpD,GAAG;GACH,SAAS;GACT,OAAO;GACR;EAKC,mBAAmB;EACnB,aAAa;EACd;AAGD,QAAO;;AA2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