@ricsam/isolate 0.1.0 → 0.1.2
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.
- package/README.md +254 -0
- package/dist/cjs/bridge/diagnostics.cjs +2 -2
- package/dist/cjs/bridge/diagnostics.cjs.map +1 -1
- package/dist/cjs/bridge/legacy-adapters.cjs +2 -2
- package/dist/cjs/bridge/legacy-adapters.cjs.map +1 -1
- package/dist/cjs/bridge/request-context.cjs +2 -2
- package/dist/cjs/bridge/request-context.cjs.map +1 -1
- package/dist/cjs/bridge/runtime-bindings.cjs +2 -2
- package/dist/cjs/bridge/runtime-bindings.cjs.map +1 -1
- package/dist/cjs/browser/browser-runtime.cjs +2 -2
- package/dist/cjs/browser/browser-runtime.cjs.map +1 -1
- package/dist/cjs/daemon.cjs +2 -2
- package/dist/cjs/daemon.cjs.map +1 -1
- package/dist/cjs/files/index.cjs +2 -2
- package/dist/cjs/files/index.cjs.map +1 -1
- package/dist/cjs/host/create-isolate-host.cjs +4 -4
- package/dist/cjs/host/create-isolate-host.cjs.map +3 -3
- package/dist/cjs/host/index.cjs +2 -2
- package/dist/cjs/host/index.cjs.map +1 -1
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/internal/client/connection.cjs +2 -2
- package/dist/cjs/internal/client/connection.cjs.map +1 -1
- package/dist/cjs/internal/client/index.cjs +2 -2
- package/dist/cjs/internal/client/index.cjs.map +1 -1
- package/dist/cjs/internal/client/types.cjs +2 -2
- package/dist/cjs/internal/client/types.cjs.map +1 -1
- package/dist/cjs/internal/console/index.cjs +2 -2
- package/dist/cjs/internal/console/index.cjs.map +1 -1
- package/dist/cjs/internal/console/utils.cjs +2 -2
- package/dist/cjs/internal/console/utils.cjs.map +1 -1
- package/dist/cjs/internal/core/index.cjs +2 -2
- package/dist/cjs/internal/core/index.cjs.map +1 -1
- package/dist/cjs/internal/crypto/index.cjs +2 -2
- package/dist/cjs/internal/crypto/index.cjs.map +1 -1
- package/dist/cjs/internal/daemon/callback-fs-handler.cjs +2 -2
- package/dist/cjs/internal/daemon/callback-fs-handler.cjs.map +1 -1
- package/dist/cjs/internal/daemon/connection.cjs +2 -2
- package/dist/cjs/internal/daemon/connection.cjs.map +1 -1
- package/dist/cjs/internal/daemon/daemon.cjs +2 -2
- package/dist/cjs/internal/daemon/daemon.cjs.map +1 -1
- package/dist/cjs/internal/daemon/index.cjs +2 -2
- package/dist/cjs/internal/daemon/index.cjs.map +1 -1
- package/dist/cjs/internal/daemon/runtime-pool.cjs +2 -2
- package/dist/cjs/internal/daemon/runtime-pool.cjs.map +1 -1
- package/dist/cjs/internal/daemon/types.cjs +2 -2
- package/dist/cjs/internal/daemon/types.cjs.map +1 -1
- package/dist/cjs/internal/encoding/index.cjs +2 -2
- package/dist/cjs/internal/encoding/index.cjs.map +1 -1
- package/dist/cjs/internal/fetch/consistency/origins.cjs +2 -2
- package/dist/cjs/internal/fetch/consistency/origins.cjs.map +1 -1
- package/dist/cjs/internal/fetch/index.cjs +2 -2
- package/dist/cjs/internal/fetch/index.cjs.map +1 -1
- package/dist/cjs/internal/fetch/stream-state.cjs +2 -2
- package/dist/cjs/internal/fetch/stream-state.cjs.map +1 -1
- package/dist/cjs/internal/fs/index.cjs +2 -2
- package/dist/cjs/internal/fs/index.cjs.map +1 -1
- package/dist/cjs/internal/fs/node-adapter.cjs +2 -2
- package/dist/cjs/internal/fs/node-adapter.cjs.map +1 -1
- package/dist/cjs/internal/module-loader/bundle.cjs +2 -2
- package/dist/cjs/internal/module-loader/bundle.cjs.map +1 -1
- package/dist/cjs/internal/module-loader/index.cjs +2 -2
- package/dist/cjs/internal/module-loader/index.cjs.map +1 -1
- package/dist/cjs/internal/module-loader/mappings.cjs +2 -2
- package/dist/cjs/internal/module-loader/mappings.cjs.map +1 -1
- package/dist/cjs/internal/module-loader/resolve.cjs +2 -2
- package/dist/cjs/internal/module-loader/resolve.cjs.map +1 -1
- package/dist/cjs/internal/module-loader/strip-types.cjs +2 -2
- package/dist/cjs/internal/module-loader/strip-types.cjs.map +1 -1
- package/dist/cjs/internal/path/index.cjs +2 -2
- package/dist/cjs/internal/path/index.cjs.map +1 -1
- package/dist/cjs/internal/playwright/client.cjs +2 -2
- package/dist/cjs/internal/playwright/client.cjs.map +1 -1
- package/dist/cjs/internal/playwright/handler.cjs +2 -2
- package/dist/cjs/internal/playwright/handler.cjs.map +1 -1
- package/dist/cjs/internal/playwright/index.cjs +2 -2
- package/dist/cjs/internal/playwright/index.cjs.map +1 -1
- package/dist/cjs/internal/playwright/types.cjs +2 -2
- package/dist/cjs/internal/playwright/types.cjs.map +1 -1
- package/dist/cjs/internal/protocol/codec.cjs +2 -2
- package/dist/cjs/internal/protocol/codec.cjs.map +1 -1
- package/dist/cjs/internal/protocol/framing.cjs +2 -2
- package/dist/cjs/internal/protocol/framing.cjs.map +1 -1
- package/dist/cjs/internal/protocol/index.cjs +2 -2
- package/dist/cjs/internal/protocol/index.cjs.map +1 -1
- package/dist/cjs/internal/protocol/marshalValue.cjs +2 -2
- package/dist/cjs/internal/protocol/marshalValue.cjs.map +1 -1
- package/dist/cjs/internal/protocol/serialization.cjs +2 -2
- package/dist/cjs/internal/protocol/serialization.cjs.map +1 -1
- package/dist/cjs/internal/protocol/types.cjs +2 -2
- package/dist/cjs/internal/protocol/types.cjs.map +1 -1
- package/dist/cjs/internal/runtime/index.cjs +2 -2
- package/dist/cjs/internal/runtime/index.cjs.map +1 -1
- package/dist/cjs/internal/server/index.cjs +2 -2
- package/dist/cjs/internal/server/index.cjs.map +1 -1
- package/dist/cjs/internal/test-environment/index.cjs +2 -2
- package/dist/cjs/internal/test-environment/index.cjs.map +1 -1
- package/dist/cjs/internal/timers/index.cjs +2 -2
- package/dist/cjs/internal/timers/index.cjs.map +1 -1
- package/dist/cjs/internal/transform/index.cjs +2 -2
- package/dist/cjs/internal/transform/index.cjs.map +1 -1
- package/dist/cjs/internal/typecheck/index.cjs +2 -2
- package/dist/cjs/internal/typecheck/index.cjs.map +1 -1
- package/dist/cjs/internal/typecheck/isolate-types.cjs +2 -2
- package/dist/cjs/internal/typecheck/isolate-types.cjs.map +1 -1
- package/dist/cjs/internal/typecheck/typecheck.cjs +2 -2
- package/dist/cjs/internal/typecheck/typecheck.cjs.map +1 -1
- package/dist/cjs/modules/index.cjs +11 -4
- package/dist/cjs/modules/index.cjs.map +3 -3
- package/dist/cjs/package.json +1 -1
- package/dist/cjs/runtime/script-runtime.cjs +2 -2
- package/dist/cjs/runtime/script-runtime.cjs.map +1 -1
- package/dist/cjs/server/app-server.cjs +2 -2
- package/dist/cjs/server/app-server.cjs.map +1 -1
- package/dist/cjs/testing/integration-helpers.cjs +2 -2
- package/dist/cjs/testing/integration-helpers.cjs.map +1 -1
- package/dist/cjs/typecheck/index.cjs +2 -2
- package/dist/cjs/typecheck/index.cjs.map +1 -1
- package/dist/cjs/types.cjs +2 -2
- package/dist/cjs/types.cjs.map +1 -1
- package/dist/mjs/bridge/diagnostics.mjs +2 -2
- package/dist/mjs/bridge/diagnostics.mjs.map +1 -1
- package/dist/mjs/bridge/legacy-adapters.mjs +2 -2
- package/dist/mjs/bridge/legacy-adapters.mjs.map +1 -1
- package/dist/mjs/bridge/request-context.mjs +2 -2
- package/dist/mjs/bridge/request-context.mjs.map +1 -1
- package/dist/mjs/bridge/runtime-bindings.mjs +2 -2
- package/dist/mjs/bridge/runtime-bindings.mjs.map +1 -1
- package/dist/mjs/browser/browser-runtime.mjs +2 -2
- package/dist/mjs/browser/browser-runtime.mjs.map +1 -1
- package/dist/mjs/daemon.mjs +2 -2
- package/dist/mjs/daemon.mjs.map +1 -1
- package/dist/mjs/files/index.mjs +2 -2
- package/dist/mjs/files/index.mjs.map +1 -1
- package/dist/mjs/host/create-isolate-host.mjs +3 -3
- package/dist/mjs/host/create-isolate-host.mjs.map +3 -3
- package/dist/mjs/host/index.mjs +2 -2
- package/dist/mjs/host/index.mjs.map +1 -1
- package/dist/mjs/index.mjs +2 -2
- package/dist/mjs/index.mjs.map +1 -1
- package/dist/mjs/internal/client/connection.mjs +2 -2
- package/dist/mjs/internal/client/connection.mjs.map +1 -1
- package/dist/mjs/internal/client/index.mjs +2 -2
- package/dist/mjs/internal/client/index.mjs.map +1 -1
- package/dist/mjs/internal/client/types.mjs +1 -1
- package/dist/mjs/internal/client/types.mjs.map +1 -1
- package/dist/mjs/internal/console/index.mjs +2 -2
- package/dist/mjs/internal/console/index.mjs.map +1 -1
- package/dist/mjs/internal/console/utils.mjs +2 -2
- package/dist/mjs/internal/console/utils.mjs.map +1 -1
- package/dist/mjs/internal/core/index.mjs +2 -2
- package/dist/mjs/internal/core/index.mjs.map +1 -1
- package/dist/mjs/internal/crypto/index.mjs +2 -2
- package/dist/mjs/internal/crypto/index.mjs.map +1 -1
- package/dist/mjs/internal/daemon/callback-fs-handler.mjs +2 -2
- package/dist/mjs/internal/daemon/callback-fs-handler.mjs.map +1 -1
- package/dist/mjs/internal/daemon/connection.mjs +2 -2
- package/dist/mjs/internal/daemon/connection.mjs.map +1 -1
- package/dist/mjs/internal/daemon/daemon.mjs +2 -2
- package/dist/mjs/internal/daemon/daemon.mjs.map +1 -1
- package/dist/mjs/internal/daemon/index.mjs +2 -2
- package/dist/mjs/internal/daemon/index.mjs.map +1 -1
- package/dist/mjs/internal/daemon/runtime-pool.mjs +2 -2
- package/dist/mjs/internal/daemon/runtime-pool.mjs.map +1 -1
- package/dist/mjs/internal/daemon/types.mjs +1 -1
- package/dist/mjs/internal/daemon/types.mjs.map +1 -1
- package/dist/mjs/internal/encoding/index.mjs +2 -2
- package/dist/mjs/internal/encoding/index.mjs.map +1 -1
- package/dist/mjs/internal/fetch/consistency/origins.mjs +2 -2
- package/dist/mjs/internal/fetch/consistency/origins.mjs.map +1 -1
- package/dist/mjs/internal/fetch/index.mjs +2 -2
- package/dist/mjs/internal/fetch/index.mjs.map +1 -1
- package/dist/mjs/internal/fetch/stream-state.mjs +2 -2
- package/dist/mjs/internal/fetch/stream-state.mjs.map +1 -1
- package/dist/mjs/internal/fs/index.mjs +2 -2
- package/dist/mjs/internal/fs/index.mjs.map +1 -1
- package/dist/mjs/internal/fs/node-adapter.mjs +2 -2
- package/dist/mjs/internal/fs/node-adapter.mjs.map +1 -1
- package/dist/mjs/internal/module-loader/bundle.mjs +2 -2
- package/dist/mjs/internal/module-loader/bundle.mjs.map +1 -1
- package/dist/mjs/internal/module-loader/index.mjs +2 -2
- package/dist/mjs/internal/module-loader/index.mjs.map +1 -1
- package/dist/mjs/internal/module-loader/mappings.mjs +2 -2
- package/dist/mjs/internal/module-loader/mappings.mjs.map +1 -1
- package/dist/mjs/internal/module-loader/resolve.mjs +2 -2
- package/dist/mjs/internal/module-loader/resolve.mjs.map +1 -1
- package/dist/mjs/internal/module-loader/strip-types.mjs +2 -2
- package/dist/mjs/internal/module-loader/strip-types.mjs.map +1 -1
- package/dist/mjs/internal/path/index.mjs +2 -2
- package/dist/mjs/internal/path/index.mjs.map +1 -1
- package/dist/mjs/internal/playwright/client.mjs +2 -2
- package/dist/mjs/internal/playwright/client.mjs.map +1 -1
- package/dist/mjs/internal/playwright/handler.mjs +2 -2
- package/dist/mjs/internal/playwright/handler.mjs.map +1 -1
- package/dist/mjs/internal/playwright/index.mjs +2 -2
- package/dist/mjs/internal/playwright/index.mjs.map +1 -1
- package/dist/mjs/internal/playwright/types.mjs +2 -2
- package/dist/mjs/internal/playwright/types.mjs.map +1 -1
- package/dist/mjs/internal/protocol/codec.mjs +2 -2
- package/dist/mjs/internal/protocol/codec.mjs.map +1 -1
- package/dist/mjs/internal/protocol/framing.mjs +2 -2
- package/dist/mjs/internal/protocol/framing.mjs.map +1 -1
- package/dist/mjs/internal/protocol/index.mjs +2 -2
- package/dist/mjs/internal/protocol/index.mjs.map +1 -1
- package/dist/mjs/internal/protocol/marshalValue.mjs +2 -2
- package/dist/mjs/internal/protocol/marshalValue.mjs.map +1 -1
- package/dist/mjs/internal/protocol/serialization.mjs +2 -2
- package/dist/mjs/internal/protocol/serialization.mjs.map +1 -1
- package/dist/mjs/internal/protocol/types.mjs +2 -2
- package/dist/mjs/internal/protocol/types.mjs.map +1 -1
- package/dist/mjs/internal/runtime/index.mjs +2 -2
- package/dist/mjs/internal/runtime/index.mjs.map +1 -1
- package/dist/mjs/internal/server/index.mjs +2 -2
- package/dist/mjs/internal/server/index.mjs.map +1 -1
- package/dist/mjs/internal/test-environment/index.mjs +2 -2
- package/dist/mjs/internal/test-environment/index.mjs.map +1 -1
- package/dist/mjs/internal/timers/index.mjs +2 -2
- package/dist/mjs/internal/timers/index.mjs.map +1 -1
- package/dist/mjs/internal/transform/index.mjs +2 -2
- package/dist/mjs/internal/transform/index.mjs.map +1 -1
- package/dist/mjs/internal/typecheck/index.mjs +2 -2
- package/dist/mjs/internal/typecheck/index.mjs.map +1 -1
- package/dist/mjs/internal/typecheck/isolate-types.mjs +2 -2
- package/dist/mjs/internal/typecheck/isolate-types.mjs.map +1 -1
- package/dist/mjs/internal/typecheck/typecheck.mjs +2 -2
- package/dist/mjs/internal/typecheck/typecheck.mjs.map +1 -1
- package/dist/mjs/modules/index.mjs +11 -4
- package/dist/mjs/modules/index.mjs.map +3 -3
- package/dist/mjs/package.json +1 -1
- package/dist/mjs/runtime/script-runtime.mjs +2 -2
- package/dist/mjs/runtime/script-runtime.mjs.map +1 -1
- package/dist/mjs/server/app-server.mjs +2 -2
- package/dist/mjs/server/app-server.mjs.map +1 -1
- package/dist/mjs/testing/integration-helpers.mjs +2 -2
- package/dist/mjs/testing/integration-helpers.mjs.map +1 -1
- package/dist/mjs/typecheck/index.mjs +2 -2
- package/dist/mjs/typecheck/index.mjs.map +1 -1
- package/dist/mjs/types.mjs +1 -1
- package/dist/mjs/types.mjs.map +1 -1
- package/package.json +46 -38
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * MessagePack codec with custom extension types for the isolate protocol.\n */\n\nimport { encode, decode, ExtensionCodec } from \"@msgpack/msgpack\";\nimport type { Message } from \"./types.mjs\";\n\n// ============================================================================\n// Custom Extension Types\n// ============================================================================\n\n/**\n * Extension type codes for custom data types.\n */\nexport const ExtType = {\n /** Reference to an isolate instance */\n ISOLATE_REF: 1,\n /** Reference to a registered callback */\n CALLBACK_REF: 2,\n /** Reference to a stream */\n STREAM_REF: 3,\n /** Structured error object */\n ERROR: 4,\n /** Reference to Blob/File data */\n BLOB_REF: 5,\n /** Date value */\n DATE: 6,\n /** RegExp value */\n REGEXP: 7,\n /** Undefined value (null is natively supported) */\n UNDEFINED: 8,\n /** BigInt value */\n BIGINT: 9,\n /** Request object */\n REQUEST: 10,\n /** Response object */\n RESPONSE: 11,\n /** Headers object */\n HEADERS: 12,\n /** File object */\n FILE: 13,\n /** FormData object */\n FORMDATA: 14,\n /** URL object */\n URL_REF: 15,\n /** Promise reference */\n PROMISE: 16,\n /** AsyncIterator reference */\n ASYNC_ITERATOR: 17,\n} as const;\n\nexport type ExtType = (typeof ExtType)[keyof typeof ExtType];\n\n/**\n * Represents a reference to an isolate.\n */\nexport interface IsolateRef {\n __type: \"IsolateRef\";\n isolateId: string;\n}\n\n/**\n * Represents a reference to a callback.\n */\nexport interface CallbackRef {\n __type: \"CallbackRef\";\n callbackId: number;\n}\n\n/**\n * Represents a reference to a stream.\n */\nexport interface StreamRef {\n __type: \"StreamRef\";\n streamId: number;\n direction: \"upload\" | \"download\";\n}\n\n/**\n * Represents a structured error.\n */\nexport interface ErrorRef {\n __type: \"ErrorRef\";\n name: string;\n message: string;\n stack?: string;\n code?: number;\n}\n\n/**\n * Represents a reference to blob data.\n */\nexport interface BlobRef {\n __type: \"BlobRef\";\n blobId: number;\n size: number;\n type: string;\n}\n\n/**\n * Represents a serialized Date value.\n */\nexport interface DateRef {\n __type: \"DateRef\";\n timestamp: number;\n}\n\n/**\n * Represents a serialized RegExp value.\n */\nexport interface RegExpRef {\n __type: \"RegExpRef\";\n source: string;\n flags: string;\n}\n\n/**\n * Represents an undefined value (since msgpack doesn't natively support undefined).\n */\nexport interface UndefinedRef {\n __type: \"UndefinedRef\";\n}\n\n/**\n * Represents a serialized BigInt value.\n */\nexport interface BigIntRef {\n __type: \"BigIntRef\";\n value: string;\n}\n\n/**\n * Represents a serialized Uint8Array value.\n * Uses number[] instead of Uint8Array for JSON compatibility.\n */\nexport interface Uint8ArrayRef {\n __type: \"Uint8ArrayRef\";\n data: number[];\n}\n\n/**\n * Represents a serialized Request object.\n * Uses number[] instead of Uint8Array for JSON compatibility.\n */\nexport interface RequestRef {\n __type: \"RequestRef\";\n url: string;\n method: string;\n headers: [string, string][];\n body: number[] | null;\n mode?: string;\n credentials?: string;\n cache?: string;\n redirect?: string;\n referrer?: string;\n referrerPolicy?: string;\n integrity?: string;\n}\n\n/**\n * Represents a serialized Response object.\n * Uses number[] instead of Uint8Array for JSON compatibility.\n */\nexport interface ResponseRef {\n __type: \"ResponseRef\";\n status: number;\n statusText: string;\n headers: [string, string][];\n body: number[] | null;\n}\n\n/**\n * Represents a serialized Headers object.\n */\nexport interface HeadersRef {\n __type: \"HeadersRef\";\n pairs: [string, string][];\n}\n\n/**\n * Represents a serialized File object (includes the data inline).\n * Uses number[] instead of Uint8Array for JSON compatibility.\n */\nexport interface FileRef {\n __type: \"FileRef\";\n name: string;\n type: string;\n lastModified: number;\n data: number[];\n}\n\n/**\n * Represents a serialized FormData object.\n */\nexport interface FormDataRef {\n __type: \"FormDataRef\";\n entries: [string, string | FileRef][];\n}\n\n/**\n * Represents a serialized URL object.\n */\nexport interface URLRef {\n __type: \"URLRef\";\n href: string;\n}\n\n/**\n * Represents a reference to a pending Promise.\n */\nexport interface PromiseRef {\n __type: \"PromiseRef\";\n promiseId: number;\n}\n\n/**\n * Represents a reference to an async iterator.\n */\nexport interface AsyncIteratorRef {\n __type: \"AsyncIteratorRef\";\n iteratorId: number;\n __nextCallbackId?: number;\n __returnCallbackId?: number;\n __throwCallbackId?: number;\n}\n\nexport type ExtensionType =\n | IsolateRef\n | CallbackRef\n | StreamRef\n | ErrorRef\n | BlobRef\n | DateRef\n | RegExpRef\n | UndefinedRef\n | BigIntRef\n | RequestRef\n | ResponseRef\n | HeadersRef\n | FileRef\n | FormDataRef\n | URLRef\n | PromiseRef\n | AsyncIteratorRef;\n\n// ============================================================================\n// Extension Codec Setup\n// ============================================================================\n\n/**\n * Create the extension codec for custom types.\n */\nfunction createExtensionCodec(): ExtensionCodec {\n const extensionCodec = new ExtensionCodec();\n\n // IsolateRef\n extensionCodec.register({\n type: ExtType.ISOLATE_REF,\n encode: (value: unknown): Uint8Array | null => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as IsolateRef).__type === \"IsolateRef\"\n ) {\n const ref = value as IsolateRef;\n return encode({ isolateId: ref.isolateId });\n }\n return null;\n },\n decode: (data: Uint8Array): IsolateRef => {\n const decoded = decode(data) as { isolateId: string };\n return { __type: \"IsolateRef\", isolateId: decoded.isolateId };\n },\n });\n\n // CallbackRef\n extensionCodec.register({\n type: ExtType.CALLBACK_REF,\n encode: (value: unknown): Uint8Array | null => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as CallbackRef).__type === \"CallbackRef\"\n ) {\n const ref = value as CallbackRef;\n return encode({ callbackId: ref.callbackId });\n }\n return null;\n },\n decode: (data: Uint8Array): CallbackRef => {\n const decoded = decode(data) as { callbackId: number };\n return { __type: \"CallbackRef\", callbackId: decoded.callbackId };\n },\n });\n\n // StreamRef\n extensionCodec.register({\n type: ExtType.STREAM_REF,\n encode: (value: unknown): Uint8Array | null => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as StreamRef).__type === \"StreamRef\"\n ) {\n const ref = value as StreamRef;\n return encode({ streamId: ref.streamId, direction: ref.direction });\n }\n return null;\n },\n decode: (data: Uint8Array): StreamRef => {\n const decoded = decode(data) as {\n streamId: number;\n direction: \"upload\" | \"download\";\n };\n return {\n __type: \"StreamRef\",\n streamId: decoded.streamId,\n direction: decoded.direction,\n };\n },\n });\n\n // ErrorRef\n extensionCodec.register({\n type: ExtType.ERROR,\n encode: (value: unknown): Uint8Array | null => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as ErrorRef).__type === \"ErrorRef\"\n ) {\n const ref = value as ErrorRef;\n return encode({\n name: ref.name,\n message: ref.message,\n stack: ref.stack,\n code: ref.code,\n });\n }\n return null;\n },\n decode: (data: Uint8Array): ErrorRef => {\n const decoded = decode(data) as {\n name: string;\n message: string;\n stack?: string;\n code?: number;\n };\n return {\n __type: \"ErrorRef\",\n name: decoded.name,\n message: decoded.message,\n stack: decoded.stack,\n code: decoded.code,\n };\n },\n });\n\n // BlobRef\n extensionCodec.register({\n type: ExtType.BLOB_REF,\n encode: (value: unknown): Uint8Array | null => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as BlobRef).__type === \"BlobRef\"\n ) {\n const ref = value as BlobRef;\n return encode({\n blobId: ref.blobId,\n size: ref.size,\n type: ref.type,\n });\n }\n return null;\n },\n decode: (data: Uint8Array): BlobRef => {\n const decoded = decode(data) as {\n blobId: number;\n size: number;\n type: string;\n };\n return {\n __type: \"BlobRef\",\n blobId: decoded.blobId,\n size: decoded.size,\n type: decoded.type,\n };\n },\n });\n\n // Date - only handle actual Date instances\n // DateRef objects are passed through as plain objects (preserved for isolate unmarshalling)\n extensionCodec.register({\n type: ExtType.DATE,\n encode: (value: unknown): Uint8Array | null => {\n // Only handle actual Date instances\n if (value instanceof Date) {\n return encode({ timestamp: value.getTime() });\n }\n return null;\n },\n decode: (data: Uint8Array): Date => {\n const decoded = decode(data) as { timestamp: number };\n return new Date(decoded.timestamp);\n },\n });\n\n // RegExp - only handle actual RegExp instances\n // RegExpRef objects are passed through as plain objects (preserved for isolate unmarshalling)\n extensionCodec.register({\n type: ExtType.REGEXP,\n encode: (value: unknown): Uint8Array | null => {\n // Only handle actual RegExp instances\n if (value instanceof RegExp) {\n return encode({ source: value.source, flags: value.flags });\n }\n return null;\n },\n decode: (data: Uint8Array): RegExp => {\n const decoded = decode(data) as { source: string; flags: string };\n return new RegExp(decoded.source, decoded.flags);\n },\n });\n\n // undefined - only handle actual undefined values\n // UndefinedRef objects are passed through as plain objects (preserved for isolate unmarshalling)\n extensionCodec.register({\n type: ExtType.UNDEFINED,\n encode: (value: unknown): Uint8Array | null => {\n // Only handle actual undefined\n if (value === undefined) {\n return encode({});\n }\n return null;\n },\n decode: (): undefined => {\n return undefined;\n },\n });\n\n // BigInt - only handle actual BigInt values\n // BigIntRef objects are passed through as plain objects (preserved for isolate unmarshalling)\n extensionCodec.register({\n type: ExtType.BIGINT,\n encode: (value: unknown): Uint8Array | null => {\n // Only handle actual BigInt values\n if (typeof value === \"bigint\") {\n return encode({ value: value.toString() });\n }\n return null;\n },\n decode: (data: Uint8Array): bigint => {\n const decoded = decode(data) as { value: string };\n return BigInt(decoded.value);\n },\n });\n\n // RequestRef - decodes to actual Request object\n extensionCodec.register({\n type: ExtType.REQUEST,\n encode: (value: unknown): Uint8Array | null => {\n // Handle RequestRef objects (actual Request instances need async handling via marshalValue)\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as RequestRef).__type === \"RequestRef\"\n ) {\n const ref = value as RequestRef;\n return encode({\n url: ref.url,\n method: ref.method,\n headers: ref.headers,\n body: ref.body,\n mode: ref.mode,\n credentials: ref.credentials,\n cache: ref.cache,\n redirect: ref.redirect,\n referrer: ref.referrer,\n referrerPolicy: ref.referrerPolicy,\n integrity: ref.integrity,\n });\n }\n return null;\n },\n decode: (data: Uint8Array): RequestRef => {\n // Return RequestRef instead of reconstructing Request - the daemon passes this through\n // and the isolate's unmarshalFromHost will reconstruct the Request\n const decoded = decode(data) as Omit<RequestRef, \"__type\">;\n return {\n __type: \"RequestRef\",\n url: decoded.url,\n method: decoded.method,\n headers: decoded.headers,\n body: decoded.body,\n mode: decoded.mode,\n credentials: decoded.credentials,\n cache: decoded.cache,\n redirect: decoded.redirect,\n referrer: decoded.referrer,\n referrerPolicy: decoded.referrerPolicy,\n integrity: decoded.integrity,\n };\n },\n });\n\n // ResponseRef - decodes to actual Response object\n extensionCodec.register({\n type: ExtType.RESPONSE,\n encode: (value: unknown): Uint8Array | null => {\n // Handle ResponseRef objects (actual Response instances need async handling via marshalValue)\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as ResponseRef).__type === \"ResponseRef\"\n ) {\n const ref = value as ResponseRef;\n return encode({\n status: ref.status,\n statusText: ref.statusText,\n headers: ref.headers,\n body: ref.body,\n });\n }\n return null;\n },\n decode: (data: Uint8Array): ResponseRef => {\n // Return ResponseRef instead of reconstructing Response - the daemon passes this through\n // and the isolate's unmarshalFromHost will reconstruct the Response\n const decoded = decode(data) as Omit<ResponseRef, \"__type\">;\n return {\n __type: \"ResponseRef\",\n status: decoded.status,\n statusText: decoded.statusText,\n headers: decoded.headers,\n body: decoded.body,\n };\n },\n });\n\n // HeadersRef - handles both Headers instances and HeadersRef objects\n extensionCodec.register({\n type: ExtType.HEADERS,\n encode: (value: unknown): Uint8Array | null => {\n // Handle actual Headers instances\n if (typeof Headers !== \"undefined\" && value instanceof Headers) {\n const pairs: [string, string][] = [];\n (value as Headers).forEach((v, k) => pairs.push([k, v]));\n return encode({ pairs });\n }\n // Handle HeadersRef objects\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as HeadersRef).__type === \"HeadersRef\"\n ) {\n const ref = value as HeadersRef;\n return encode({ pairs: ref.pairs });\n }\n return null;\n },\n decode: (data: Uint8Array): Headers => {\n const decoded = decode(data) as { pairs: [string, string][] };\n return new Headers(decoded.pairs);\n },\n });\n\n // FileRef - decodes to actual File/Blob objects\n extensionCodec.register({\n type: ExtType.FILE,\n encode: (value: unknown): Uint8Array | null => {\n // Handle FileRef objects (actual File instances need async handling via marshalValue)\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as FileRef).__type === \"FileRef\"\n ) {\n const ref = value as FileRef;\n return encode({\n name: ref.name,\n type: ref.type,\n lastModified: ref.lastModified,\n data: ref.data,\n });\n }\n return null;\n },\n decode: (data: Uint8Array): FileRef => {\n // Return FileRef instead of reconstructing File - the daemon passes this through\n // and the isolate's unmarshalFromHost will reconstruct the File\n const decoded = decode(data) as Omit<FileRef, \"__type\">;\n return {\n __type: \"FileRef\",\n name: decoded.name,\n type: decoded.type,\n lastModified: decoded.lastModified,\n data: decoded.data,\n };\n },\n });\n\n // FormDataRef - decodes to actual FormData object\n extensionCodec.register({\n type: ExtType.FORMDATA,\n encode: (value: unknown): Uint8Array | null => {\n // Handle FormDataRef objects (actual FormData instances need async handling via marshalValue)\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as FormDataRef).__type === \"FormDataRef\"\n ) {\n const ref = value as FormDataRef;\n return encode({ entries: ref.entries });\n }\n return null;\n },\n decode: (data: Uint8Array): FormDataRef => {\n // Return FormDataRef instead of reconstructing FormData - the daemon passes this through\n // and the isolate's unmarshalFromHost will reconstruct the FormData\n const decoded = decode(data) as { entries: [string, string | FileRef][] };\n return {\n __type: \"FormDataRef\",\n entries: decoded.entries,\n };\n },\n });\n\n // URLRef - handles both URL instances and URLRef objects\n extensionCodec.register({\n type: ExtType.URL_REF,\n encode: (value: unknown): Uint8Array | null => {\n // Handle actual URL instances\n if (typeof URL !== \"undefined\" && value instanceof URL) {\n return encode({ href: (value as URL).href });\n }\n // Handle URLRef objects\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as URLRef).__type === \"URLRef\"\n ) {\n const ref = value as URLRef;\n return encode({ href: ref.href });\n }\n return null;\n },\n decode: (data: Uint8Array): URL => {\n const decoded = decode(data) as { href: string };\n return new URL(decoded.href);\n },\n });\n\n // PromiseRef - preserves all fields including callback IDs\n extensionCodec.register({\n type: ExtType.PROMISE,\n encode: (value: unknown): Uint8Array | null => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as PromiseRef).__type === \"PromiseRef\"\n ) {\n const ref = value as PromiseRef;\n // Encode all fields, not just promiseId\n const encoded: Record<string, unknown> = { promiseId: ref.promiseId };\n // Preserve callback ID fields if present\n if (\"__resolveCallbackId\" in ref) {\n encoded.__resolveCallbackId = (ref as Record<string, unknown>).__resolveCallbackId;\n }\n return encode(encoded);\n }\n return null;\n },\n decode: (data: Uint8Array): PromiseRef => {\n const decoded = decode(data) as Record<string, unknown>;\n const result: PromiseRef = { __type: \"PromiseRef\", promiseId: decoded.promiseId as number };\n // Restore callback ID fields if present\n if (\"__resolveCallbackId\" in decoded) {\n (result as unknown as Record<string, unknown>).__resolveCallbackId = decoded.__resolveCallbackId;\n }\n return result;\n },\n });\n\n // AsyncIteratorRef - preserves all fields including callback IDs\n extensionCodec.register({\n type: ExtType.ASYNC_ITERATOR,\n encode: (value: unknown): Uint8Array | null => {\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n (value as AsyncIteratorRef).__type === \"AsyncIteratorRef\"\n ) {\n const ref = value as AsyncIteratorRef;\n const refRecord = ref as unknown as Record<string, unknown>;\n // Encode all fields, not just iteratorId\n const encoded: Record<string, unknown> = { iteratorId: ref.iteratorId };\n // Preserve callback ID fields if present\n if (\"__nextCallbackId\" in ref) {\n encoded.__nextCallbackId = refRecord.__nextCallbackId;\n }\n if (\"__returnCallbackId\" in ref) {\n encoded.__returnCallbackId = refRecord.__returnCallbackId;\n }\n if (\"__throwCallbackId\" in ref) {\n encoded.__throwCallbackId = refRecord.__throwCallbackId;\n }\n return encode(encoded);\n }\n return null;\n },\n decode: (data: Uint8Array): AsyncIteratorRef => {\n const decoded = decode(data) as Record<string, unknown>;\n const result: AsyncIteratorRef = { __type: \"AsyncIteratorRef\", iteratorId: decoded.iteratorId as number };\n // Restore callback ID fields if present\n if (\"__nextCallbackId\" in decoded) {\n (result as unknown as Record<string, unknown>).__nextCallbackId = decoded.__nextCallbackId;\n }\n if (\"__returnCallbackId\" in decoded) {\n (result as unknown as Record<string, unknown>).__returnCallbackId = decoded.__returnCallbackId;\n }\n if (\"__throwCallbackId\" in decoded) {\n (result as unknown as Record<string, unknown>).__throwCallbackId = decoded.__throwCallbackId;\n }\n return result;\n },\n });\n\n return extensionCodec;\n}\n\n// Singleton extension codec instance\nconst extensionCodec = createExtensionCodec();\n\n// ============================================================================\n// Encoding/Decoding Functions\n// ============================================================================\n\n/**\n * Encode a message to MessagePack bytes.\n */\nexport function encodeMessage(message: Message): Uint8Array {\n return encode(message, { extensionCodec });\n}\n\n/**\n * Decode MessagePack bytes to a message.\n */\nexport function decodeMessage(data: Uint8Array): Message {\n return decode(data, { extensionCodec }) as Message;\n}\n\n/**\n * Encode any value to MessagePack bytes.\n */\nexport function encodeValue(value: unknown): Uint8Array {\n return encode(value, { extensionCodec });\n}\n\n/**\n * Decode MessagePack bytes to any value.\n */\nexport function decodeValue(data: Uint8Array): unknown {\n return decode(data, { extensionCodec });\n}\n\n// ============================================================================\n// Helper Functions for Creating Extension Types\n// ============================================================================\n\nexport function createIsolateRef(isolateId: string): IsolateRef {\n return { __type: \"IsolateRef\", isolateId };\n}\n\nexport function createCallbackRef(callbackId: number): CallbackRef {\n return { __type: \"CallbackRef\", callbackId };\n}\n\nexport function createStreamRef(\n streamId: number,\n direction: \"upload\" | \"download\"\n): StreamRef {\n return { __type: \"StreamRef\", streamId, direction };\n}\n\nexport function createErrorRef(\n name: string,\n message: string,\n stack?: string,\n code?: number\n): ErrorRef {\n return { __type: \"ErrorRef\", name, message, stack, code };\n}\n\nexport function createBlobRef(\n blobId: number,\n size: number,\n type: string\n): BlobRef {\n return { __type: \"BlobRef\", blobId, size, type };\n}\n\nexport function createDateRef(timestamp: number): DateRef {\n return { __type: \"DateRef\", timestamp };\n}\n\nexport function createRegExpRef(source: string, flags: string): RegExpRef {\n return { __type: \"RegExpRef\", source, flags };\n}\n\nexport function createUndefinedRef(): UndefinedRef {\n return { __type: \"UndefinedRef\" };\n}\n\nexport function createBigIntRef(value: string): BigIntRef {\n return { __type: \"BigIntRef\", value };\n}\n\nexport function createUint8ArrayRef(data: number[]): Uint8ArrayRef {\n return { __type: \"Uint8ArrayRef\", data };\n}\n\nexport function createRequestRef(\n url: string,\n method: string,\n headers: [string, string][],\n body: number[] | null,\n options?: {\n mode?: string;\n credentials?: string;\n cache?: string;\n redirect?: string;\n referrer?: string;\n referrerPolicy?: string;\n integrity?: string;\n }\n): RequestRef {\n return {\n __type: \"RequestRef\",\n url,\n method,\n headers,\n body,\n ...options,\n };\n}\n\nexport function createResponseRef(\n status: number,\n statusText: string,\n headers: [string, string][],\n body: number[] | null\n): ResponseRef {\n return { __type: \"ResponseRef\", status, statusText, headers, body };\n}\n\nexport function createHeadersRef(pairs: [string, string][]): HeadersRef {\n return { __type: \"HeadersRef\", pairs };\n}\n\nexport function createFileRef(\n name: string,\n type: string,\n lastModified: number,\n data: number[]\n): FileRef {\n return { __type: \"FileRef\", name, type, lastModified, data };\n}\n\nexport function createFormDataRef(\n entries: [string, string | FileRef][]\n): FormDataRef {\n return { __type: \"FormDataRef\", entries };\n}\n\nexport function createURLRef(href: string): URLRef {\n return { __type: \"URLRef\", href };\n}\n\nexport function createPromiseRef(promiseId: number): PromiseRef {\n return { __type: \"PromiseRef\", promiseId };\n}\n\nexport function createAsyncIteratorRef(iteratorId: number): AsyncIteratorRef {\n return { __type: \"AsyncIteratorRef\", iteratorId };\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAIA;AAUO,IAAM,UAAU;AAAA,EAErB,aAAa;AAAA,EAEb,cAAc;AAAA,EAEd,YAAY;AAAA,EAEZ,OAAO;AAAA,EAEP,UAAU;AAAA,EAEV,MAAM;AAAA,EAEN,QAAQ;AAAA,EAER,WAAW;AAAA,EAEX,QAAQ;AAAA,EAER,SAAS;AAAA,EAET,UAAU;AAAA,EAEV,SAAS;AAAA,EAET,MAAM;AAAA,EAEN,UAAU;AAAA,EAEV,SAAS;AAAA,EAET,SAAS;AAAA,EAET,g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AAK;AAAA;AAG3B,SAAS,gBAAgB,CAAC,WAA+B;AAAA,EAC9D,OAAO,EAAE,QAAQ,cAAc,UAAU;AAAA;AAGpC,SAAS,sBAAsB,CAAC,YAAsC;AAAA,EAC3E,OAAO,EAAE,QAAQ,oBAAoB,WAAW;AAAA;",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "CBE39B5F8650334564756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// src/internal/protocol/framing.ts
|
|
2
2
|
import { MessageTypeName } from "./types.mjs";
|
|
3
3
|
import { encodeMessage, decodeMessage } from "./codec.mjs";
|
|
4
4
|
var HEADER_SIZE = 5;
|
|
@@ -98,4 +98,4 @@ export {
|
|
|
98
98
|
HEADER_SIZE
|
|
99
99
|
};
|
|
100
100
|
|
|
101
|
-
//# debugId=
|
|
101
|
+
//# debugId=0159BD96C0953E1264756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * Frame parser and builder for the isolate protocol.\n *\n * Frame format:\n * ┌──────────┬──────────┬─────────────────┐\n * │ Length │ Type │ Payload │\n * │ (4 bytes)│ (1 byte) │ (MessagePack) │\n * └──────────┴──────────┴─────────────────┘\n *\n * - Length: uint32 BE, size of Type + Payload (excludes the length field itself)\n * - Type: uint8, message type from MessageType enum\n * - Payload: MessagePack encoded message body\n */\n\nimport { MessageType, MessageTypeName, type Message } from \"./types.mjs\";\nimport { encodeMessage, decodeMessage } from \"./codec.mjs\";\n\n/** Header size: 4 bytes for length + 1 byte for type */\nexport const HEADER_SIZE = 5;\n\n/** Maximum frame size (10MB) */\nexport const MAX_FRAME_SIZE = 10 * 1024 * 1024;\n\n/** Threshold above which bodies should be streamed (1MB) */\nexport const STREAM_THRESHOLD = 1 * 1024 * 1024;\n\n/** Default chunk size for streaming (256KB) */\nexport const STREAM_CHUNK_SIZE = 256 * 1024;\n\n/** Default credit for backpressure (1MB) */\nexport const STREAM_DEFAULT_CREDIT = 1 * 1024 * 1024;\n\n// ============================================================================\n// Frame Building\n// ============================================================================\n\n/**\n * Build a frame from a message.\n *\n * @param message - The message to encode\n * @returns Complete frame as Uint8Array\n */\nexport function buildFrame(message: Message): Uint8Array {\n // Encode the message payload (without the type field for the payload)\n const payloadWithoutType = { ...message };\n delete (payloadWithoutType as Record<string, unknown>).type;\n\n const payload = encodeMessage(payloadWithoutType as Message);\n const messageType = message.type;\n\n // Total size: 1 byte type + payload length\n const frameBodySize = 1 + payload.length;\n\n // Build frame: 4 bytes length + 1 byte type + payload\n const frame = new Uint8Array(4 + frameBodySize);\n const view = new DataView(frame.buffer);\n\n // Write length (big-endian)\n view.setUint32(0, frameBodySize, false);\n\n // Write message type\n frame[4] = messageType;\n\n // Write payload\n frame.set(payload, 5);\n\n return frame;\n}\n\n/**\n * Build multiple frames from messages.\n *\n * @param messages - Messages to encode\n * @returns Combined frames as single Uint8Array\n */\nexport function buildFrames(messages: Message[]): Uint8Array {\n const frames = messages.map(buildFrame);\n const totalLength = frames.reduce((sum, f) => sum + f.length, 0);\n\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n\n for (const frame of frames) {\n combined.set(frame, offset);\n offset += frame.length;\n }\n\n return combined;\n}\n\n// ============================================================================\n// Frame Parsing\n// ============================================================================\n\n/**\n * Parse result from the frame parser.\n */\nexport interface ParsedFrame {\n type: MessageType;\n message: Message;\n}\n\n/**\n * Incremental frame parser for streaming data.\n *\n * Usage:\n * ```ts\n * const parser = createFrameParser();\n * socket.on('data', (chunk) => {\n * for (const frame of parser.feed(chunk)) {\n * handleMessage(frame.message);\n * }\n * });\n * ```\n */\nexport interface FrameParser {\n /**\n * Feed data to the parser and yield complete frames.\n * @param chunk - Incoming data chunk\n */\n feed(chunk: Uint8Array): Generator<ParsedFrame>;\n\n /**\n * Get the number of bytes currently buffered.\n */\n bufferedBytes(): number;\n\n /**\n * Reset the parser state.\n */\n reset(): void;\n}\n\n/**\n * Create a new frame parser.\n */\nexport function createFrameParser(): FrameParser {\n let buffer: Uint8Array = new Uint8Array(0);\n\n function* feed(chunk: Uint8Array): Generator<ParsedFrame> {\n // Append chunk to buffer\n const newBuffer = new Uint8Array(buffer.length + chunk.length);\n newBuffer.set(buffer);\n newBuffer.set(chunk, buffer.length);\n buffer = newBuffer;\n\n // Try to parse frames\n while (buffer.length >= 4) {\n // Read length\n const view = new DataView(\n buffer.buffer,\n buffer.byteOffset,\n buffer.byteLength\n );\n const frameBodySize = view.getUint32(0, false);\n\n // Validate frame size\n if (frameBodySize > MAX_FRAME_SIZE) {\n throw new Error(\n `Frame size ${frameBodySize} exceeds maximum ${MAX_FRAME_SIZE}`\n );\n }\n\n // Check if we have the complete frame\n const totalFrameSize = 4 + frameBodySize;\n if (buffer.length < totalFrameSize) {\n break; // Wait for more data\n }\n\n // Extract frame\n const messageType = buffer[4] as MessageType;\n const payload = buffer.slice(5, totalFrameSize);\n\n // Decode payload\n const decodedPayload = decodeMessage(payload);\n const message = { ...decodedPayload, type: messageType } as Message;\n\n yield { type: messageType, message };\n\n // Remove processed frame from buffer\n buffer = buffer.slice(totalFrameSize);\n }\n }\n\n function bufferedBytes(): number {\n return buffer.length;\n }\n\n function reset(): void {\n buffer = new Uint8Array(0);\n }\n\n return { feed, bufferedBytes, reset };\n}\n\n// ============================================================================\n// Single Frame Parsing (for testing/debugging)\n// ============================================================================\n\n/**\n * Parse a single complete frame.\n *\n * @param data - Complete frame data\n * @returns Parsed frame or null if incomplete\n * @throws Error if frame is invalid\n */\nexport function parseFrame(data: Uint8Array): ParsedFrame | null {\n if (data.length < 4) {\n return null;\n }\n\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const frameBodySize = view.getUint32(0, false);\n\n if (frameBodySize > MAX_FRAME_SIZE) {\n throw new Error(\n `Frame size ${frameBodySize} exceeds maximum ${MAX_FRAME_SIZE}`\n );\n }\n\n const totalFrameSize = 4 + frameBodySize;\n if (data.length < totalFrameSize) {\n return null;\n }\n\n const messageType = data[4] as MessageType;\n const payload = data.slice(5, totalFrameSize);\n\n const decodedPayload = decodeMessage(payload);\n const message = { ...decodedPayload, type: messageType } as Message;\n\n return { type: messageType, message };\n}\n\n/**\n * Get the message type name for debugging.\n */\nexport function getMessageTypeName(type: MessageType): string {\n return MessageTypeName[type] ?? `Unknown(${type})`;\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAcA;AACA;AAGO,IAAM,cAAc;AAGpB,IAAM,iBAAiB,KAAK,OAAO;AAGnC,IAAM,mBAAmB,IAAI,OAAO;AAGpC,IAAM,oBAAoB,MAAM;AAGhC,IAAM,wBAAwB,IAAI,OAAO;AAYzC,SAAS,UAAU,CAAC,SAA8B;AAAA,EAEvD,MAAM,qBAAqB,KAAK,QAAQ;AAAA,EACxC,OAAQ,mBAA+C;AAAA,EAEvD,MAAM,UAAU,cAAc,kBAA6B;AAAA,EAC3D,MAAM,cAAc,QAAQ;AAAA,EAG5B,MAAM,gBAAgB,IAAI,QAAQ;AAAA,EAGlC,MAAM,QAAQ,IAAI,WAAW,IAAI,aAAa;AAAA,EAC9C,MAAM,OAAO,IAAI,SAAS,MAAM,MAAM;AAAA,EAGtC,KAAK,UAAU,GAAG,eAAe,KAAK;AAAA,EAGtC,MAAM,KAAK;AAAA,EAGX,MAAM,IAAI,SAAS,CAAC;AAAA,EAEpB,OAAO;AAAA;AASF,SAAS,WAAW,CAAC,UAAiC;AAAA,EAC3D,MAAM,SAAS,SAAS,IAAI,UAAU;AAAA,EACtC,MAAM,cAAc,OAAO,OAAO,CAAC,KAAK,MAAM,MAAM,EAAE,QAAQ,CAAC;AAAA,EAE/D,MAAM,WAAW,IAAI,WAAW,WAAW;AAAA,EAC3C,IAAI,SAAS;AAAA,EAEb,WAAW,SAAS,QAAQ;AAAA,IAC1B,SAAS,IAAI,OAAO,MAAM;AAAA,IAC1B,UAAU,MAAM;AAAA,EAClB;AAAA,EAEA,OAAO;AAAA;AAiDF,SAAS,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vE,MAAM,gBAAgB,KAAK,UAAU,GAAG,KAAK;AAAA,EAE7C,IAAI,gBAAgB,gBAAgB;AAAA,IAClC,MAAM,IAAI,MACR,cAAc,iCAAiC,gBACjD;AAAA,EACF;AAAA,EAEA,MAAM,iBAAiB,IAAI;AAAA,EAC3B,IAAI,KAAK,SAAS,gBAAgB;AAAA,IAChC,OAAO;AAAA,EACT;AAAA,EAEA,MAAM,cAAc,KAAK;AAAA,EACzB,MAAM,UAAU,KAAK,MAAM,GAAG,cAAc;AAAA,EAE5C,MAAM,iBAAiB,cAAc,OAAO;AAAA,EAC5C,MAAM,UAAU,KAAK,gBAAgB,MAAM,YAAY;AAAA,EAEvD,OAAO,EAAE,MAAM,aAAa,QAAQ;AAAA;AAM/B,SAAS,kBAAkB,CAAC,MAA2B;AAAA,EAC5D,OAAO,gBAAgB,SAAS,WAAW;AAAA;",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "0159BD96C0953E1264756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// src/internal/protocol/index.ts
|
|
2
2
|
export * from "./types.mjs";
|
|
3
3
|
import {
|
|
4
4
|
encodeMessage,
|
|
@@ -95,4 +95,4 @@ export {
|
|
|
95
95
|
ExtType
|
|
96
96
|
};
|
|
97
97
|
|
|
98
|
-
//# debugId=
|
|
98
|
+
//# debugId=856F6F1774D4093364756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * ./index.ts\n *\n * Protocol definitions, codec, and framing for the isolate daemon.\n */\n\n// Types and utilities\nexport * from \"./types.mjs\";\n\n// Codec\nexport {\n encodeMessage,\n decodeMessage,\n encodeValue,\n decodeValue,\n createIsolateRef,\n createCallbackRef,\n createStreamRef,\n createErrorRef,\n createBlobRef,\n createDateRef,\n createRegExpRef,\n createUndefinedRef,\n createBigIntRef,\n createRequestRef,\n createResponseRef,\n createHeadersRef,\n createFileRef,\n createFormDataRef,\n createURLRef,\n createPromiseRef,\n createAsyncIteratorRef,\n ExtType,\n type IsolateRef,\n type CallbackRef,\n type StreamRef,\n type ErrorRef,\n type BlobRef,\n type DateRef,\n type RegExpRef,\n type UndefinedRef,\n type BigIntRef,\n type RequestRef,\n type ResponseRef,\n type HeadersRef,\n type FileRef,\n type FormDataRef,\n type URLRef,\n type PromiseRef,\n type AsyncIteratorRef,\n type ExtensionType,\n} from \"./codec.mjs\";\n\n// Value marshalling\nexport {\n marshalValue,\n marshalValueSync,\n unmarshalValue,\n MarshalError,\n isPromiseRef,\n isAsyncIteratorRef,\n type MarshalContext,\n type UnmarshalContext,\n} from \"./marshalValue.mjs\";\n\n// Request/Response serialization\nexport {\n serializeRequest,\n serializeResponse,\n deserializeRequest,\n deserializeResponse,\n} from \"./serialization.mjs\";\n\n// Framing\nexport {\n buildFrame,\n buildFrames,\n createFrameParser,\n parseFrame,\n getMessageTypeName,\n HEADER_SIZE,\n MAX_FRAME_SIZE,\n STREAM_THRESHOLD,\n STREAM_CHUNK_SIZE,\n STREAM_DEFAULT_CREDIT,\n type ParsedFrame,\n type FrameParser,\n} from \"./framing.mjs\";\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAOA;AAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4CA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "856F6F1774D4093364756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// src/internal/protocol/marshalValue.ts
|
|
2
2
|
import {
|
|
3
3
|
createCallbackRef,
|
|
4
4
|
createDateRef,
|
|
@@ -491,4 +491,4 @@ export {
|
|
|
491
491
|
MarshalError
|
|
492
492
|
};
|
|
493
493
|
|
|
494
|
-
//# debugId=
|
|
494
|
+
//# debugId=EB3F328D0F10369764756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * Value marshalling for custom function arguments and return values.\n *\n * Provides type-preserving serialization for JavaScript types that would\n * otherwise lose fidelity when JSON stringified.\n */\n\nimport {\n type CallbackRef,\n type DateRef,\n type RegExpRef,\n type UndefinedRef,\n type BigIntRef,\n type Uint8ArrayRef,\n type RequestRef,\n type ResponseRef,\n type HeadersRef,\n type FileRef,\n type FormDataRef,\n type URLRef,\n type PromiseRef,\n type AsyncIteratorRef,\n type BlobRef,\n createCallbackRef,\n createDateRef,\n createRegExpRef,\n createUndefinedRef,\n createBigIntRef,\n createUint8ArrayRef,\n createRequestRef,\n createResponseRef,\n createHeadersRef,\n createFileRef,\n createFormDataRef,\n createURLRef,\n createPromiseRef,\n createAsyncIteratorRef,\n createBlobRef,\n} from \"./codec.mjs\";\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Error thrown when a value cannot be marshalled.\n */\nexport class MarshalError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MarshalError\";\n }\n}\n\n// ============================================================================\n// Context Types\n// ============================================================================\n\n/**\n * Context for marshalling values (host → isolate).\n */\nexport interface MarshalContext {\n /** Register a function callback and return its ID */\n registerCallback?: (fn: Function) => number;\n /** Register a Promise and return its ID */\n registerPromise?: (promise: Promise<unknown>) => number;\n /** Register an AsyncIterator and return its ID */\n registerIterator?: (iterator: AsyncIterator<unknown>) => number;\n /** Register a Blob and return its ID */\n registerBlob?: (blob: Blob) => number;\n}\n\n/**\n * Context for unmarshalling values (isolate → host).\n */\nexport interface UnmarshalContext {\n /** Get a callback function by ID */\n getCallback?: (id: number) => ((...args: unknown[]) => unknown) | undefined;\n /** Create a proxy Promise for a PromiseRef */\n createPromiseProxy?: (promiseId: number) => Promise<unknown>;\n /** Create a proxy AsyncIterator for an AsyncIteratorRef */\n createIteratorProxy?: (iteratorId: number) => AsyncIterator<unknown>;\n /** Get a Blob by ID */\n getBlob?: (blobId: number) => Blob | undefined;\n}\n\n// ============================================================================\n// Type Guards for Ref Types\n// ============================================================================\n\n/**\n * Type guard for PromiseRef values.\n */\nexport function isPromiseRef(value: unknown): value is { __type: \"PromiseRef\"; promiseId: number } {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __type?: string }).__type === 'PromiseRef'\n );\n}\n\n/**\n * Type guard for AsyncIteratorRef values.\n */\nexport function isAsyncIteratorRef(value: unknown): value is { __type: \"AsyncIteratorRef\"; iteratorId: number } {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __type?: string }).__type === 'AsyncIteratorRef'\n );\n}\n\n// ============================================================================\n// Supported Class Detection\n// ============================================================================\n\n/**\n * Set of class names that are supported for marshalling.\n */\nconst SUPPORTED_CLASSES = new Set([\n \"Date\",\n \"RegExp\",\n \"Request\",\n \"Response\",\n \"Headers\",\n \"File\",\n \"Blob\",\n \"FormData\",\n \"URL\",\n // Typed arrays are natively supported by msgpack\n \"Uint8Array\",\n \"Int8Array\",\n \"Uint16Array\",\n \"Int16Array\",\n \"Uint32Array\",\n \"Int32Array\",\n \"Float32Array\",\n \"Float64Array\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"ArrayBuffer\",\n \"DataView\",\n]);\n\n/**\n * Check if a value is a typed array.\n */\nfunction isTypedArray(value: unknown): value is ArrayBufferView {\n return (\n value instanceof Uint8Array ||\n value instanceof Int8Array ||\n value instanceof Uint16Array ||\n value instanceof Int16Array ||\n value instanceof Uint32Array ||\n value instanceof Int32Array ||\n value instanceof Float32Array ||\n value instanceof Float64Array ||\n value instanceof BigInt64Array ||\n value instanceof BigUint64Array ||\n value instanceof DataView\n );\n}\n\n/**\n * Check if a value is an async iterable (has Symbol.asyncIterator).\n */\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Symbol.asyncIterator in value &&\n typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\"\n );\n}\n\n// ============================================================================\n// Marshalling (JavaScript → Refs)\n// ============================================================================\n\nconst MAX_DEPTH = 100;\n\n/**\n * Marshal a JavaScript value to a serializable format.\n *\n * Converts JavaScript types that lose fidelity when JSON stringified into\n * Ref objects that can be reconstructed on the other side.\n *\n * @param value - The value to marshal\n * @param ctx - Optional context for registering callbacks, promises, etc.\n * @param depth - Current recursion depth (used for circular reference detection)\n * @param seen - WeakSet of seen objects (for circular reference detection)\n * @returns The marshalled value (may be async for Request/Response/File/Blob/FormData)\n */\nexport async function marshalValue(\n value: unknown,\n ctx?: MarshalContext,\n depth: number = 0,\n seen: WeakSet<object> = new WeakSet()\n): Promise<unknown> {\n // Check depth limit\n if (depth > MAX_DEPTH) {\n throw new MarshalError(\n `Maximum marshalling depth (${MAX_DEPTH}) exceeded. Possible circular reference.`\n );\n }\n\n // Handle null\n if (value === null) {\n return null;\n }\n\n // Handle undefined\n if (value === undefined) {\n return createUndefinedRef();\n }\n\n // Handle primitives (pass through)\n const type = typeof value;\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value;\n }\n\n // Handle BigInt\n if (type === \"bigint\") {\n return createBigIntRef((value as bigint).toString());\n }\n\n // Handle functions\n if (type === \"function\") {\n if (!ctx?.registerCallback) {\n throw new MarshalError(\n \"Cannot marshal function: no registerCallback provided in context\"\n );\n }\n const callbackId = ctx.registerCallback(value as Function);\n return createCallbackRef(callbackId);\n }\n\n // Handle objects\n if (type === \"object\") {\n const obj = value as object;\n\n // Check for circular references\n if (seen.has(obj)) {\n throw new MarshalError(\n \"Cannot marshal value: circular reference detected\"\n );\n }\n\n // Handle Date\n if (obj instanceof Date) {\n return createDateRef(obj.getTime());\n }\n\n // Handle RegExp\n if (obj instanceof RegExp) {\n return createRegExpRef(obj.source, obj.flags);\n }\n\n // Handle URL\n if (obj instanceof URL) {\n return createURLRef(obj.href);\n }\n\n // Handle Headers\n if (typeof Headers !== \"undefined\" && obj instanceof Headers) {\n const pairs: [string, string][] = [];\n (obj as Headers).forEach((value, key) => {\n pairs.push([key, value]);\n });\n return createHeadersRef(pairs);\n }\n\n // Handle Uint8Array and ArrayBuffer - wrap in Uint8ArrayRef for JSON compatibility\n if (obj instanceof Uint8Array) {\n return createUint8ArrayRef(Array.from(obj));\n }\n if (obj instanceof ArrayBuffer) {\n return createUint8ArrayRef(Array.from(new Uint8Array(obj)));\n }\n\n // Handle other typed arrays (convert to Uint8ArrayRef)\n if (isTypedArray(obj)) {\n const u8 = new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength);\n return createUint8ArrayRef(Array.from(u8));\n }\n\n // Handle Promise\n if (obj instanceof Promise) {\n if (!ctx?.registerPromise) {\n throw new MarshalError(\n \"Cannot marshal Promise: no registerPromise provided in context\"\n );\n }\n const promiseId = ctx.registerPromise(obj as Promise<unknown>);\n return createPromiseRef(promiseId);\n }\n\n // Handle AsyncIterable (must check before generic object)\n if (isAsyncIterable(obj)) {\n if (!ctx?.registerIterator) {\n throw new MarshalError(\n \"Cannot marshal AsyncIterable: no registerIterator provided in context\"\n );\n }\n const iterator = (obj as AsyncIterable<unknown>)[Symbol.asyncIterator]();\n const iteratorId = ctx.registerIterator(iterator);\n return createAsyncIteratorRef(iteratorId);\n }\n\n // Mark as seen for circular reference detection\n seen.add(obj);\n\n // Handle Request (async - need to read body)\n if (typeof Request !== \"undefined\" && obj instanceof Request) {\n const req = obj as Request;\n const headers: [string, string][] = [];\n req.headers.forEach((value, key) => {\n headers.push([key, value]);\n });\n let body: number[] | null = null;\n if (req.body) {\n // Clone the request to avoid consuming the body\n const cloned = req.clone();\n body = Array.from(new Uint8Array(await cloned.arrayBuffer()));\n }\n return createRequestRef(req.url, req.method, headers, body, {\n mode: req.mode,\n credentials: req.credentials,\n cache: req.cache,\n redirect: req.redirect,\n referrer: req.referrer,\n referrerPolicy: req.referrerPolicy,\n integrity: req.integrity,\n });\n }\n\n // Handle Response (async - need to read body)\n if (typeof Response !== \"undefined\" && obj instanceof Response) {\n const res = obj as Response;\n const headers: [string, string][] = [];\n res.headers.forEach((value, key) => {\n headers.push([key, value]);\n });\n let body: number[] | null = null;\n if (res.body) {\n // Clone the response to avoid consuming the body\n const cloned = res.clone();\n body = Array.from(new Uint8Array(await cloned.arrayBuffer()));\n }\n return createResponseRef(res.status, res.statusText, headers, body);\n }\n\n // Handle File (async - need to read data)\n if (typeof File !== \"undefined\" && obj instanceof File) {\n const file = obj as File;\n const data = Array.from(new Uint8Array(await file.arrayBuffer()));\n return createFileRef(file.name, file.type, file.lastModified, data);\n }\n\n // Handle Blob (async - need to read data, or use BlobRef if registerBlob provided)\n if (typeof Blob !== \"undefined\" && obj instanceof Blob) {\n const blob = obj as Blob;\n if (ctx?.registerBlob) {\n const blobId = ctx.registerBlob(blob);\n return createBlobRef(blobId, blob.size, blob.type);\n }\n // Inline the blob data as a FileRef without name\n const data = Array.from(new Uint8Array(await blob.arrayBuffer()));\n return createFileRef(\"\", blob.type, Date.now(), data);\n }\n\n // Handle FormData (async - entries may contain Files)\n if (typeof FormData !== \"undefined\" && obj instanceof FormData) {\n const fd = obj as FormData;\n const entries: [string, string | FileRef][] = [];\n for (const [key, value] of fd.entries()) {\n if (typeof value === \"string\") {\n entries.push([key, value]);\n } else {\n // File/Blob - cast to File for type safety\n const file = value as File;\n const data = Array.from(new Uint8Array(await file.arrayBuffer()));\n const fileRef = createFileRef(\n file.name ?? \"\",\n file.type,\n file.lastModified ?? Date.now(),\n data\n );\n entries.push([key, fileRef]);\n }\n }\n return createFormDataRef(entries);\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n const result: unknown[] = [];\n for (const item of obj) {\n result.push(await marshalValue(item, ctx, depth + 1, seen));\n }\n return result;\n }\n\n // Handle plain objects\n const constructorName = obj.constructor?.name;\n if (constructorName && constructorName !== \"Object\") {\n if (!SUPPORTED_CLASSES.has(constructorName)) {\n throw new MarshalError(\n `Cannot marshal class instance of type \"${constructorName}\". ` +\n `Only plain objects and supported classes are allowed.`\n );\n }\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = await marshalValue(\n (obj as Record<string, unknown>)[key],\n ctx,\n depth + 1,\n seen\n );\n }\n return result;\n }\n\n // Handle symbols (not serializable)\n if (type === \"symbol\") {\n throw new MarshalError(\"Cannot marshal Symbol values\");\n }\n\n // Unknown type\n throw new MarshalError(`Cannot marshal value of type \"${type}\"`);\n}\n\n/**\n * Synchronous marshal for values that don't require async operations.\n * Throws if the value contains Request, Response, File, Blob, or FormData.\n */\nexport function marshalValueSync(\n value: unknown,\n ctx?: MarshalContext,\n depth: number = 0,\n seen: WeakSet<object> = new WeakSet()\n): unknown {\n // Check depth limit\n if (depth > MAX_DEPTH) {\n throw new MarshalError(\n `Maximum marshalling depth (${MAX_DEPTH}) exceeded. Possible circular reference.`\n );\n }\n\n // Handle null\n if (value === null) {\n return null;\n }\n\n // Handle undefined\n if (value === undefined) {\n return createUndefinedRef();\n }\n\n // Handle primitives (pass through)\n const type = typeof value;\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value;\n }\n\n // Handle BigInt\n if (type === \"bigint\") {\n return createBigIntRef((value as bigint).toString());\n }\n\n // Handle functions\n if (type === \"function\") {\n if (!ctx?.registerCallback) {\n throw new MarshalError(\n \"Cannot marshal function: no registerCallback provided in context\"\n );\n }\n const callbackId = ctx.registerCallback(value as Function);\n return createCallbackRef(callbackId);\n }\n\n // Handle objects\n if (type === \"object\") {\n const obj = value as object;\n\n // Check for circular references\n if (seen.has(obj)) {\n throw new MarshalError(\n \"Cannot marshal value: circular reference detected\"\n );\n }\n\n // Handle Date\n if (obj instanceof Date) {\n return createDateRef(obj.getTime());\n }\n\n // Handle RegExp\n if (obj instanceof RegExp) {\n return createRegExpRef(obj.source, obj.flags);\n }\n\n // Handle URL\n if (obj instanceof URL) {\n return createURLRef(obj.href);\n }\n\n // Handle Headers\n if (typeof Headers !== \"undefined\" && obj instanceof Headers) {\n const pairs: [string, string][] = [];\n (obj as Headers).forEach((value, key) => {\n pairs.push([key, value]);\n });\n return createHeadersRef(pairs);\n }\n\n // Handle Uint8Array and ArrayBuffer - wrap in Uint8ArrayRef for JSON compatibility\n if (obj instanceof Uint8Array) {\n return createUint8ArrayRef(Array.from(obj));\n }\n if (obj instanceof ArrayBuffer) {\n return createUint8ArrayRef(Array.from(new Uint8Array(obj)));\n }\n\n // Handle other typed arrays (convert to Uint8ArrayRef)\n if (isTypedArray(obj)) {\n const u8 = new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength);\n return createUint8ArrayRef(Array.from(u8));\n }\n\n // Handle Promise\n if (obj instanceof Promise) {\n if (!ctx?.registerPromise) {\n throw new MarshalError(\n \"Cannot marshal Promise: no registerPromise provided in context\"\n );\n }\n const promiseId = ctx.registerPromise(obj as Promise<unknown>);\n return createPromiseRef(promiseId);\n }\n\n // Handle AsyncIterable (must check before generic object)\n if (isAsyncIterable(obj)) {\n if (!ctx?.registerIterator) {\n throw new MarshalError(\n \"Cannot marshal AsyncIterable: no registerIterator provided in context\"\n );\n }\n const iterator = (obj as AsyncIterable<unknown>)[Symbol.asyncIterator]();\n const iteratorId = ctx.registerIterator(iterator);\n return createAsyncIteratorRef(iteratorId);\n }\n\n // Mark as seen for circular reference detection\n seen.add(obj);\n\n // Async types that can't be marshalled synchronously\n if (typeof Request !== \"undefined\" && obj instanceof Request) {\n throw new MarshalError(\n \"Cannot marshal Request synchronously. Use marshalValue() instead.\"\n );\n }\n if (typeof Response !== \"undefined\" && obj instanceof Response) {\n throw new MarshalError(\n \"Cannot marshal Response synchronously. Use marshalValue() instead.\"\n );\n }\n if (typeof File !== \"undefined\" && obj instanceof File) {\n throw new MarshalError(\n \"Cannot marshal File synchronously. Use marshalValue() instead.\"\n );\n }\n if (typeof Blob !== \"undefined\" && obj instanceof Blob) {\n throw new MarshalError(\n \"Cannot marshal Blob synchronously. Use marshalValue() instead.\"\n );\n }\n if (typeof FormData !== \"undefined\" && obj instanceof FormData) {\n throw new MarshalError(\n \"Cannot marshal FormData synchronously. Use marshalValue() instead.\"\n );\n }\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return obj.map((item) => marshalValueSync(item, ctx, depth + 1, seen));\n }\n\n // Handle plain objects\n const constructorName = obj.constructor?.name;\n if (constructorName && constructorName !== \"Object\") {\n if (!SUPPORTED_CLASSES.has(constructorName)) {\n throw new MarshalError(\n `Cannot marshal class instance of type \"${constructorName}\". ` +\n `Only plain objects and supported classes are allowed.`\n );\n }\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = marshalValueSync(\n (obj as Record<string, unknown>)[key],\n ctx,\n depth + 1,\n seen\n );\n }\n return result;\n }\n\n // Handle symbols (not serializable)\n if (type === \"symbol\") {\n throw new MarshalError(\"Cannot marshal Symbol values\");\n }\n\n // Unknown type\n throw new MarshalError(`Cannot marshal value of type \"${type}\"`);\n}\n\n// ============================================================================\n// Unmarshalling (Refs → JavaScript)\n// ============================================================================\n\n/**\n * Type guard for checking if a value is a Ref object.\n */\nfunction isRef(value: unknown): value is { __type: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"__type\" in value &&\n typeof (value as { __type: unknown }).__type === \"string\"\n );\n}\n\n/**\n * Unmarshal a serialized value back to JavaScript types.\n *\n * @param value - The value to unmarshal\n * @param ctx - Optional context for resolving callbacks, promises, etc.\n * @param depth - Current recursion depth\n * @returns The unmarshalled JavaScript value\n */\nexport function unmarshalValue(\n value: unknown,\n ctx?: UnmarshalContext,\n depth: number = 0\n): unknown {\n // Check depth limit\n if (depth > MAX_DEPTH) {\n throw new MarshalError(\n `Maximum unmarshalling depth (${MAX_DEPTH}) exceeded.`\n );\n }\n\n // Handle null\n if (value === null) {\n return null;\n }\n\n // Handle primitives (pass through)\n const type = typeof value;\n if (type === \"string\" || type === \"number\" || type === \"boolean\") {\n return value;\n }\n\n // Handle Uint8Array (msgpack native support)\n if (value instanceof Uint8Array) {\n return value;\n }\n\n // Handle objects\n if (type === \"object\") {\n // Check if it's a Ref type\n if (isRef(value)) {\n const refType = value.__type;\n\n switch (refType) {\n case \"UndefinedRef\":\n return undefined;\n\n case \"DateRef\": {\n const ref = value as DateRef;\n return new Date(ref.timestamp);\n }\n\n case \"RegExpRef\": {\n const ref = value as RegExpRef;\n return new RegExp(ref.source, ref.flags);\n }\n\n case \"BigIntRef\": {\n const ref = value as BigIntRef;\n return BigInt(ref.value);\n }\n\n case \"Uint8ArrayRef\": {\n const ref = value as Uint8ArrayRef;\n return new Uint8Array(ref.data);\n }\n\n case \"URLRef\": {\n const ref = value as URLRef;\n return new URL(ref.href);\n }\n\n case \"HeadersRef\": {\n const ref = value as HeadersRef;\n return new Headers(ref.pairs);\n }\n\n case \"RequestRef\": {\n const ref = value as RequestRef;\n const body = ref.body ? new Uint8Array(ref.body) : null;\n const init: RequestInit = {\n method: ref.method,\n headers: ref.headers,\n body: body as BodyInit | null | undefined,\n };\n if (ref.mode) init.mode = ref.mode as RequestMode;\n if (ref.credentials) init.credentials = ref.credentials as RequestCredentials;\n if (ref.cache) init.cache = ref.cache as RequestCache;\n if (ref.redirect) init.redirect = ref.redirect as RequestRedirect;\n if (ref.referrer) init.referrer = ref.referrer;\n if (ref.referrerPolicy) init.referrerPolicy = ref.referrerPolicy as ReferrerPolicy;\n if (ref.integrity) init.integrity = ref.integrity;\n return new Request(ref.url, init);\n }\n\n case \"ResponseRef\": {\n const ref = value as ResponseRef;\n const body = ref.body ? new Uint8Array(ref.body) : null;\n return new Response(body as BodyInit | null | undefined, {\n status: ref.status,\n statusText: ref.statusText,\n headers: ref.headers,\n });\n }\n\n case \"FileRef\": {\n const ref = value as FileRef;\n const data = new Uint8Array(ref.data);\n // If no name, return as Blob\n if (!ref.name) {\n return new Blob([data as BlobPart], { type: ref.type });\n }\n return new File([data as BlobPart], ref.name, {\n type: ref.type,\n lastModified: ref.lastModified,\n });\n }\n\n case \"BlobRef\": {\n const ref = value as BlobRef;\n if (ctx?.getBlob) {\n const blob = ctx.getBlob(ref.blobId);\n if (blob) return blob;\n }\n // Can't reconstruct without the actual data\n throw new MarshalError(\n `Cannot unmarshal BlobRef: no getBlob provided or blob not found`\n );\n }\n\n case \"FormDataRef\": {\n const ref = value as FormDataRef;\n const fd = new FormData();\n for (const [key, entry] of ref.entries) {\n if (typeof entry === \"string\") {\n fd.append(key, entry);\n } else {\n // FileRef\n const file = unmarshalValue(entry, ctx, depth + 1) as File | Blob;\n fd.append(key, file);\n }\n }\n return fd;\n }\n\n case \"CallbackRef\": {\n const ref = value as CallbackRef;\n if (!ctx?.getCallback) {\n throw new MarshalError(\n `Cannot unmarshal CallbackRef: no getCallback provided`\n );\n }\n const callback = ctx.getCallback(ref.callbackId);\n if (!callback) {\n throw new MarshalError(\n `Cannot unmarshal CallbackRef: callback ${ref.callbackId} not found`\n );\n }\n return callback;\n }\n\n case \"PromiseRef\": {\n const ref = value as PromiseRef;\n if (!ctx?.createPromiseProxy) {\n throw new MarshalError(\n `Cannot unmarshal PromiseRef: no createPromiseProxy provided`\n );\n }\n return ctx.createPromiseProxy(ref.promiseId);\n }\n\n case \"AsyncIteratorRef\": {\n const ref = value as AsyncIteratorRef;\n if (!ctx?.createIteratorProxy) {\n throw new MarshalError(\n `Cannot unmarshal AsyncIteratorRef: no createIteratorProxy provided`\n );\n }\n const iterator = ctx.createIteratorProxy(ref.iteratorId);\n // Return as async iterable\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n };\n }\n\n default:\n // Unknown ref type, return as-is (might be handled by higher level)\n return value;\n }\n }\n\n // Handle arrays\n if (Array.isArray(value)) {\n return value.map((item) => unmarshalValue(item, ctx, depth + 1));\n }\n\n // Handle plain objects (recursively unmarshal values)\n const obj = value as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = unmarshalValue(obj[key], ctx, depth + 1);\n }\n return result;\n }\n\n // Pass through unknown types\n return value;\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAOA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwCO,MAAM,qBAAqB,MAAM;AAAA,EACtC,WAAW,CAAC,SAAiB;AAAA,IAC3B,MAAM,OAAO;AAAA,IACb,KAAK,OAAO;AAAA;AAEhB;AAyCO,SAAS,YAAY,CAAC,OAAsE;AAAA,EACjG,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA8B,WAAW;AAAA;AAOvC,SAAS,kBAAkB,CAAC,OAA6E;AAAA,EAC9G,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA8B,WAAW;AAAA;AAW9C,IAAM,oBAAoB,IAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAKD,SAAS,YAAY,CAAC,OAA0C;AAAA,EAC9D,OACE,iBAAiB,cACjB,iBAAiB,aACjB,iBAAiB,eACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,cACjB,iBAAiB,gBACjB,iBAAiB,gBACjB,iBAAiB,iBACjB,iBAAiB,kBACjB,iBAAiB;AAAA;AAOrB,SAAS,eAAe,CAAC,OAAiD;AAAA,EACxE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAO,iBAAiB,SACxB,OAAQ,MAAiC,OAAO,mBAAmB;AAAA;AAQvE,IAAM,YAAY;AAclB,eAAsB,YAAY,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AAAA,UAIE,OAAO;AAAA;AAAA,IAEb;AAAA,IAGA,IAAI,MAAM,QAAQ,KAAK,GAAG;AAAA,MACxB,OAAO,MAAM,IAAI,CAAC,SAAS,eAAe,MAAM,KAAK,QAAQ,CAAC,CAAC;AAAA,IACjE;AAAA,IAGA,MAAM,MAAM;AAAA,IACZ,MAAM,SAAkC,CAAC;AAAA,IACzC,WAAW,OAAO,OAAO,KAAK,GAAG,GAAG;AAAA,MAClC,OAAO,OAAO,eAAe,IAAI,MAAM,KAAK,QAAQ,CAAC;AAAA,IACvD;AAAA,IACA,OAAO;AAAA,EACT;AAAA,EAGA,OAAO;AAAA;",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "EB3F328D0F10369764756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// src/internal/protocol/serialization.ts
|
|
2
2
|
function isNullBodyStatus(status) {
|
|
3
3
|
return status === 101 || status === 103 || status === 204 || status === 205 || status === 304;
|
|
4
4
|
}
|
|
@@ -66,4 +66,4 @@ export {
|
|
|
66
66
|
deserializeRequest
|
|
67
67
|
};
|
|
68
68
|
|
|
69
|
-
//# debugId=
|
|
69
|
+
//# debugId=2997CEFCCD474D9964756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * Request/Response serialization utilities.\n *\n * Shared by both isolate-daemon and isolate-client for converting\n * between Web API Request/Response objects and serializable data.\n */\n\nimport type { SerializedRequest, SerializedResponse } from \"./types.mjs\";\n\nfunction isNullBodyStatus(status: number): boolean {\n return status === 101 || status === 103 || status === 204 || status === 205 || status === 304;\n}\n\n/**\n * Serialize a Request to a plain object for transmission over IPC.\n */\nexport async function serializeRequest(request: Request): Promise<SerializedRequest> {\n const headers: [string, string][] = [];\n request.headers.forEach((value, key) => {\n headers.push([key, value]);\n });\n\n let body: Uint8Array | null = null;\n if (request.body) {\n body = new Uint8Array(await request.arrayBuffer());\n }\n\n return {\n method: request.method,\n url: request.url,\n headers,\n body,\n signalAborted: request.signal?.aborted ?? false,\n };\n}\n\n/**\n * Serialize a Response to a plain object for transmission over IPC.\n */\nexport async function serializeResponse(response: Response): Promise<SerializedResponse> {\n const headers: [string, string][] = [];\n response.headers.forEach((value, key) => {\n headers.push([key, value]);\n });\n\n let body: Uint8Array | null = null;\n if (response.body && !isNullBodyStatus(response.status)) {\n body = new Uint8Array(await response.arrayBuffer());\n }\n\n return {\n status: response.status,\n statusText: response.statusText,\n headers,\n body,\n };\n}\n\n/**\n * Deserialize a plain object back into a Request.\n */\nexport function deserializeRequest(data: SerializedRequest): Request {\n let signal: AbortSignal | undefined;\n if (data.signalAborted !== undefined) {\n const controller = new AbortController();\n if (data.signalAborted) {\n controller.abort();\n }\n signal = controller.signal;\n }\n\n return new Request(data.url, {\n method: data.method,\n headers: data.headers,\n body: data.body as unknown as BodyInit | null | undefined,\n signal,\n });\n}\n\n/**\n * Deserialize a plain object back into a Response.\n */\nexport function deserializeResponse(data: SerializedResponse): Response {\n const body = isNullBodyStatus(data.status) ? null : data.body;\n return new Response(body as unknown as BodyInit | null, {\n status: data.status,\n statusText: data.statusText,\n headers: data.headers,\n });\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AASA,SAAS,gBAAgB,CAAC,QAAyB;AAAA,EACjD,OAAO,WAAW,OAAO,WAAW,OAAO,WAAW,OAAO,WAAW,OAAO,WAAW;AAAA;AAM5F,eAAsB,gBAAgB,CAAC,SAA8C;AAAA,EACnF,MAAM,UAA8B,CAAC;AAAA,EACrC,QAAQ,QAAQ,QAAQ,CAAC,OAAO,QAAQ;AAAA,IACtC,QAAQ,KAAK,CAAC,KAAK,KAAK,CAAC;AAAA,GAC1B;AAAA,EAED,IAAI,OAA0B;AAAA,EAC9B,IAAI,QAAQ,MAAM;AAAA,IAChB,OAAO,IAAI,WAAW,MAAM,QAAQ,YAAY,CAAC;AAAA,EACnD;AAAA,EAEA,OAAO;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756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// src/internal/protocol/types.ts
|
|
2
2
|
var MessageType = {
|
|
3
3
|
CREATE_RUNTIME: 1,
|
|
4
4
|
DISPOSE_RUNTIME: 2,
|
|
@@ -138,4 +138,4 @@ export {
|
|
|
138
138
|
ClientEvents
|
|
139
139
|
};
|
|
140
140
|
|
|
141
|
-
//# debugId=
|
|
141
|
+
//# debugId=28FA9B4C27FCEF6764756E2164756E21
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * Message types for the isolate daemon protocol.\n *\n * Frame format:\n * ┌──────────┬──────────┬─────────────────┐\n * │ Length │ Type │ Payload │\n * │ (4 bytes)│ (1 byte) │ (MessagePack) │\n * └──────────┴──────────┴─────────────────┘\n */\n\n// ============================================================================\n// Message Type Constants\n// ============================================================================\n\nexport const MessageType = {\n // Client → Daemon: Runtime management\n CREATE_RUNTIME: 0x01,\n DISPOSE_RUNTIME: 0x02,\n EVAL: 0x03,\n DISPATCH_REQUEST: 0x04,\n DISPATCH_REQUEST_ABORT: 0x05,\n\n // Client → Daemon: WebSocket operations\n WS_OPEN: 0x10,\n WS_MESSAGE: 0x11,\n WS_CLOSE: 0x12,\n\n // Client → Daemon: Handle operations\n FETCH_GET_UPGRADE_REQUEST: 0x13,\n FETCH_HAS_SERVE_HANDLER: 0x14,\n FETCH_HAS_ACTIVE_CONNECTIONS: 0x15,\n FETCH_WS_ERROR: 0x16,\n TIMERS_CLEAR_ALL: 0x17,\n CONSOLE_RESET: 0x18,\n CONSOLE_GET_TIMERS: 0x19,\n CONSOLE_GET_COUNTERS: 0x1a,\n CONSOLE_GET_GROUP_DEPTH: 0x1b,\n\n // Client → Daemon: Test environment\n RUN_TESTS: 0x21,\n RESET_TEST_ENV: 0x22,\n HAS_TESTS: 0x23,\n GET_TEST_COUNT: 0x24,\n\n // Client → Daemon: Playwright\n GET_COLLECTED_DATA: 0x33,\n CLEAR_COLLECTED_DATA: 0x34,\n\n // Daemon → Client: Responses\n RESPONSE_OK: 0x80,\n RESPONSE_ERROR: 0x81,\n RESPONSE_STREAM_START: 0x82,\n RESPONSE_STREAM_CHUNK: 0x83,\n RESPONSE_STREAM_END: 0x84,\n\n // Bidirectional: Callbacks\n CALLBACK_INVOKE: 0x90,\n CALLBACK_RESPONSE: 0x91,\n CALLBACK_STREAM_START: 0x92,\n CALLBACK_STREAM_CHUNK: 0x93,\n CALLBACK_STREAM_END: 0x94,\n CALLBACK_STREAM_CANCEL: 0x95,\n CALLBACK_ABORT: 0x96,\n\n // Bidirectional: Stream data\n STREAM_PUSH: 0xa0,\n STREAM_PULL: 0xa1,\n STREAM_CLOSE: 0xa2,\n STREAM_ERROR: 0xa3,\n\n // Bidirectional: Generic events\n ISOLATE_EVENT: 0xc0, // daemon → client\n CLIENT_EVENT: 0xc1, // client → daemon\n\n // Heartbeat\n PING: 0xf0,\n PONG: 0xf1,\n} as const;\n\nexport type MessageType = (typeof MessageType)[keyof typeof MessageType];\n\n/** Reverse lookup for message type names */\nexport const MessageTypeName: Record<number, string> = Object.fromEntries(\n Object.entries(MessageType).map(([k, v]) => [v, k])\n);\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\nexport const ErrorCode = {\n // Protocol errors\n INVALID_MESSAGE: 1001,\n UNKNOWN_MESSAGE_TYPE: 1002,\n MISSING_REQUIRED_FIELD: 1003,\n\n // Isolate errors\n ISOLATE_NOT_FOUND: 2001,\n ISOLATE_DISPOSED: 2002,\n ISOLATE_MEMORY_LIMIT: 2003,\n ISOLATE_TIMEOUT: 2004,\n\n // Execution errors\n SCRIPT_ERROR: 3001,\n CALLBACK_ERROR: 3002,\n\n // Stream errors\n STREAM_NOT_FOUND: 4001,\n STREAM_CLOSED: 4002,\n\n // Connection errors\n CONNECTION_LOST: 5001,\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n// ============================================================================\n// Base Message Interface\n// ============================================================================\n\nexport interface BaseMessage {\n /** Unique request ID for correlation */\n requestId: number;\n}\n\n// ============================================================================\n// Callback Registration\n// ============================================================================\n\n/** Custom function type indicator */\nexport type CustomFunctionType = 'sync' | 'async' | 'asyncIterator';\n\nexport interface CallbackRegistration {\n /** Unique ID for this callback */\n callbackId: number;\n /** Callback name (e.g., \"log\", \"warn\", \"fetch\") */\n name: string;\n /** Function type: sync, async, or asyncIterator */\n type: CustomFunctionType;\n}\n\nexport interface ConsoleCallbackRegistrations {\n onEntry?: CallbackRegistration;\n}\n\nexport interface FsCallbackRegistrations {\n readFile?: CallbackRegistration;\n writeFile?: CallbackRegistration;\n unlink?: CallbackRegistration;\n readdir?: CallbackRegistration;\n mkdir?: CallbackRegistration;\n rmdir?: CallbackRegistration;\n stat?: CallbackRegistration;\n rename?: CallbackRegistration;\n}\n\nexport interface CustomFunctionRegistrations {\n [name: string]: CallbackRegistration;\n}\n\n// ============================================================================\n// Playwright Callback Types\n// ============================================================================\n\n/**\n * Playwright operation sent from daemon to client via callback.\n * The client executes this operation on the real Page object.\n */\nexport interface PlaywrightOperation {\n type:\n | \"goto\"\n | \"reload\"\n | \"url\"\n | \"title\"\n | \"content\"\n | \"waitForSelector\"\n | \"waitForTimeout\"\n | \"waitForLoadState\"\n | \"evaluate\"\n | \"locatorAction\"\n | \"expectLocator\"\n | \"expectPage\"\n | \"request\"\n | \"goBack\"\n | \"goForward\"\n | \"waitForURL\"\n | \"waitForURLPredicate\"\n | \"waitForRequestStart\"\n | \"waitForRequestFinish\"\n | \"waitForRequestPredicateFinish\"\n | \"waitForResponseStart\"\n | \"waitForResponseFinish\"\n | \"waitForResponsePredicateFinish\"\n | \"clearCookies\"\n // Page-level operations\n | \"screenshot\"\n | \"setViewportSize\"\n | \"viewportSize\"\n | \"emulateMedia\"\n | \"setExtraHTTPHeaders\"\n | \"bringToFront\"\n | \"close\"\n | \"isClosed\"\n | \"pdf\"\n | \"pause\"\n | \"frames\"\n | \"mainFrame\"\n // Keyboard operations\n | \"keyboardType\"\n | \"keyboardPress\"\n | \"keyboardDown\"\n | \"keyboardUp\"\n | \"keyboardInsertText\"\n // Mouse operations\n | \"mouseMove\"\n | \"mouseClick\"\n | \"mouseDown\"\n | \"mouseUp\"\n | \"mouseWheel\"\n // Cookie operations\n | \"addCookies\"\n | \"cookies\"\n // Browser/Context lifecycle operations\n | \"newContext\"\n | \"newPage\"\n | \"closeContext\";\n args: unknown[];\n /** Target page ID (undefined = default page \"page_0\") */\n pageId?: string;\n /** Target context ID (undefined = default context \"ctx_0\") */\n contextId?: string;\n}\n\n/**\n * Result of a playwright operation.\n */\nexport type PlaywrightResult =\n | { ok: true; value?: unknown }\n | { ok: false; error: { name: string; message: string } };\n\n/**\n * Callback registrations for playwright operations.\n */\nexport interface PlaywrightCallbackRegistration {\n /** Callback ID for page operations */\n handlerCallbackId: number;\n /** If true, browser console logs are printed to stdout */\n console?: boolean;\n /** Optional callback for browser console log events (from the page, not sandbox) */\n onBrowserConsoleLogCallbackId?: number;\n /** Optional callback for network request events */\n onNetworkRequestCallbackId?: number;\n /** Optional callback for network response events */\n onNetworkResponseCallbackId?: number;\n}\n\n// ============================================================================\n// Runtime Callback Registrations\n// ============================================================================\n\nexport interface RuntimeCallbackRegistrations {\n console?: ConsoleCallbackRegistrations;\n fetch?: CallbackRegistration;\n fs?: FsCallbackRegistrations;\n moduleLoader?: CallbackRegistration;\n custom?: CustomFunctionRegistrations;\n playwright?: PlaywrightCallbackRegistration;\n}\n\n// ============================================================================\n// Client → Daemon Messages\n// ============================================================================\n\nexport interface TestEnvironmentCallbackRegistrations {\n /** Callback for test events */\n onEvent?: CallbackRegistration;\n}\n\nexport interface TestEnvironmentOptionsProtocol {\n /** Callback registrations for test events */\n callbacks?: TestEnvironmentCallbackRegistrations;\n /** Timeout for individual tests (ms) */\n testTimeout?: number;\n}\n\nexport interface PlaywrightOptionsProtocol {\n /** Default timeout for Playwright operations in ms */\n timeout?: number;\n}\n\nexport interface CreateRuntimeRequest extends BaseMessage {\n type: typeof MessageType.CREATE_RUNTIME;\n options: {\n memoryLimitMB?: number;\n executionTimeout?: number;\n callbacks?: RuntimeCallbackRegistrations;\n /** Current working directory for path.resolve(). Defaults to \"/\" */\n cwd?: string;\n /** Enable test environment (describe, it, expect, etc.) */\n testEnvironment?: boolean | TestEnvironmentOptionsProtocol;\n /** Playwright runtime options */\n playwright?: PlaywrightOptionsProtocol;\n /** Namespace ID for runtime pooling/reuse. If provided, runtime will be cached on dispose. */\n namespaceId?: string;\n };\n}\n\nexport interface DisposeRuntimeRequest extends BaseMessage {\n type: typeof MessageType.DISPOSE_RUNTIME;\n isolateId: string;\n /** When true, permanently delete the runtime instead of soft-deleting namespaced runtimes. */\n hard?: boolean;\n /** Optional caller-supplied reason for disposal, used for diagnostics/logging. */\n reason?: string;\n}\n\nexport interface EvalRequest extends BaseMessage {\n type: typeof MessageType.EVAL;\n isolateId: string;\n code: string;\n filename?: string;\n executionTimeout?: number;\n}\n\nexport interface SerializedRequest {\n method: string;\n url: string;\n headers: [string, string][];\n /** Inline body for small payloads */\n body?: Uint8Array | null;\n /** Stream reference for large/streaming bodies */\n bodyStreamId?: number;\n /** Whether the request signal was already aborted when serialized */\n signalAborted?: boolean;\n}\n\nexport interface DispatchRequestRequest extends BaseMessage {\n type: typeof MessageType.DISPATCH_REQUEST;\n isolateId: string;\n request: SerializedRequest;\n context?: {\n requestId?: string;\n metadata?: Record<string, string>;\n };\n}\n\n/**\n * Abort an in-flight DISPATCH_REQUEST.\n * This is fire-and-forget and does not produce a response.\n */\nexport interface DispatchRequestAbort {\n type: typeof MessageType.DISPATCH_REQUEST_ABORT;\n isolateId: string;\n /** requestId of the corresponding DISPATCH_REQUEST */\n targetRequestId: number;\n}\n\n// WebSocket messages\nexport interface WsOpenRequest extends BaseMessage {\n type: typeof MessageType.WS_OPEN;\n isolateId: string;\n connectionId: string;\n}\n\nexport interface WsMessageRequest extends BaseMessage {\n type: typeof MessageType.WS_MESSAGE;\n isolateId: string;\n connectionId: string;\n data: string | Uint8Array;\n}\n\nexport interface WsCloseRequest extends BaseMessage {\n type: typeof MessageType.WS_CLOSE;\n isolateId: string;\n connectionId: string;\n code: number;\n reason: string;\n}\n\n// Handle operation messages\nexport interface FetchGetUpgradeRequestRequest extends BaseMessage {\n type: typeof MessageType.FETCH_GET_UPGRADE_REQUEST;\n isolateId: string;\n}\n\nexport interface FetchHasServeHandlerRequest extends BaseMessage {\n type: typeof MessageType.FETCH_HAS_SERVE_HANDLER;\n isolateId: string;\n}\n\nexport interface FetchHasActiveConnectionsRequest extends BaseMessage {\n type: typeof MessageType.FETCH_HAS_ACTIVE_CONNECTIONS;\n isolateId: string;\n}\n\nexport interface FetchWsErrorRequest extends BaseMessage {\n type: typeof MessageType.FETCH_WS_ERROR;\n isolateId: string;\n connectionId: string;\n error: string;\n}\n\nexport interface TimersClearAllRequest extends BaseMessage {\n type: typeof MessageType.TIMERS_CLEAR_ALL;\n isolateId: string;\n}\n\nexport interface ConsoleResetRequest extends BaseMessage {\n type: typeof MessageType.CONSOLE_RESET;\n isolateId: string;\n}\n\nexport interface ConsoleGetTimersRequest extends BaseMessage {\n type: typeof MessageType.CONSOLE_GET_TIMERS;\n isolateId: string;\n}\n\nexport interface ConsoleGetCountersRequest extends BaseMessage {\n type: typeof MessageType.CONSOLE_GET_COUNTERS;\n isolateId: string;\n}\n\nexport interface ConsoleGetGroupDepthRequest extends BaseMessage {\n type: typeof MessageType.CONSOLE_GET_GROUP_DEPTH;\n isolateId: string;\n}\n\n// Test environment messages\nexport interface RunTestsRequest extends BaseMessage {\n type: typeof MessageType.RUN_TESTS;\n isolateId: string;\n timeout?: number;\n}\n\nexport interface ResetTestEnvRequest extends BaseMessage {\n type: typeof MessageType.RESET_TEST_ENV;\n isolateId: string;\n}\n\nexport interface HasTestsRequest extends BaseMessage {\n type: typeof MessageType.HAS_TESTS;\n isolateId: string;\n}\n\nexport interface GetTestCountRequest extends BaseMessage {\n type: typeof MessageType.GET_TEST_COUNT;\n isolateId: string;\n}\n\nexport interface GetCollectedDataRequest extends BaseMessage {\n type: typeof MessageType.GET_COLLECTED_DATA;\n isolateId: string;\n}\n\nexport interface ClearCollectedDataRequest extends BaseMessage {\n type: typeof MessageType.CLEAR_COLLECTED_DATA;\n isolateId: string;\n}\n\n// ============================================================================\n// Daemon → Client Messages\n// ============================================================================\n\nexport interface ResponseOk extends BaseMessage {\n type: typeof MessageType.RESPONSE_OK;\n data?: unknown;\n}\n\nexport interface ResponseError extends BaseMessage {\n type: typeof MessageType.RESPONSE_ERROR;\n code: ErrorCode;\n message: string;\n details?: {\n name: string;\n stack?: string;\n cause?: unknown;\n };\n}\n\nexport interface SerializedResponse {\n status: number;\n statusText: string;\n headers: [string, string][];\n /** Inline body for small payloads */\n body?: Uint8Array | null;\n /** Stream reference for large/streaming bodies */\n bodyStreamId?: number;\n}\n\nexport interface ResponseStreamStart extends BaseMessage {\n type: typeof MessageType.RESPONSE_STREAM_START;\n streamId: number;\n metadata?: {\n status?: number;\n statusText?: string;\n headers?: [string, string][];\n };\n}\n\nexport interface ResponseStreamChunk extends BaseMessage {\n type: typeof MessageType.RESPONSE_STREAM_CHUNK;\n streamId: number;\n chunk: Uint8Array;\n}\n\nexport interface ResponseStreamEnd extends BaseMessage {\n type: typeof MessageType.RESPONSE_STREAM_END;\n streamId: number;\n}\n\n// ============================================================================\n// Bidirectional: Callbacks\n// ============================================================================\n\nexport interface CallbackInvoke extends BaseMessage {\n type: typeof MessageType.CALLBACK_INVOKE;\n callbackId: number;\n args: unknown[];\n context?: {\n requestId?: string;\n metadata?: Record<string, string>;\n };\n}\n\nexport interface CallbackResponseMsg extends BaseMessage {\n type: typeof MessageType.CALLBACK_RESPONSE;\n result?: unknown;\n error?: {\n name: string;\n message: string;\n stack?: string;\n };\n}\n\n/**\n * Start a streaming callback response (client → daemon).\n * Used when the callback returns a Response with a streaming body.\n */\nexport interface CallbackStreamStart extends BaseMessage {\n type: typeof MessageType.CALLBACK_STREAM_START;\n /** The stream ID for correlating chunks */\n streamId: number;\n /** Response metadata */\n metadata: {\n status: number;\n statusText: string;\n headers: [string, string][];\n /** Response URL (for network responses) */\n url?: string;\n };\n}\n\n/**\n * A chunk of streaming callback response data (client → daemon).\n */\nexport interface CallbackStreamChunk extends BaseMessage {\n type: typeof MessageType.CALLBACK_STREAM_CHUNK;\n /** The stream ID for correlation */\n streamId: number;\n /** The chunk data */\n chunk: Uint8Array;\n}\n\n/**\n * End of a streaming callback response (client → daemon).\n */\nexport interface CallbackStreamEnd extends BaseMessage {\n type: typeof MessageType.CALLBACK_STREAM_END;\n /** The stream ID for correlation */\n streamId: number;\n}\n\n/**\n * Cancel a streaming callback response (daemon → client).\n * Tells the client to stop reading the response body.\n */\nexport interface CallbackStreamCancel {\n type: typeof MessageType.CALLBACK_STREAM_CANCEL;\n /** The stream ID to cancel */\n streamId: number;\n}\n\n/**\n * Abort an in-flight callback invocation (daemon → client).\n * Tells the client to cancel the callback identified by targetRequestId.\n */\nexport interface CallbackAbort extends BaseMessage {\n type: typeof MessageType.CALLBACK_ABORT;\n /** requestId of the corresponding CALLBACK_INVOKE */\n targetRequestId: number;\n /** Optional reason for observability/debugging */\n reason?: string;\n}\n\n// ============================================================================\n// Bidirectional: Stream Data\n// ============================================================================\n\nexport interface StreamPush {\n type: typeof MessageType.STREAM_PUSH;\n streamId: number;\n chunk: Uint8Array;\n}\n\nexport interface StreamPull {\n type: typeof MessageType.STREAM_PULL;\n streamId: number;\n maxBytes: number;\n}\n\nexport interface StreamClose {\n type: typeof MessageType.STREAM_CLOSE;\n streamId: number;\n}\n\nexport interface StreamError {\n type: typeof MessageType.STREAM_ERROR;\n streamId: number;\n error: string;\n}\n\n// ============================================================================\n// Generic Events\n// ============================================================================\n\n/** Event name constants for isolate → client events */\nexport const IsolateEvents = {\n WS_COMMAND: \"ws:command\",\n WS_CLIENT_CONNECT: \"ws:client-connect\",\n WS_CLIENT_SEND: \"ws:client-send\",\n WS_CLIENT_CLOSE: \"ws:client-close\",\n} as const;\n\n/** Event name constants for client → daemon events */\nexport const ClientEvents = {\n WS_CLIENT_OPENED: \"ws:client-opened\",\n WS_CLIENT_MESSAGE: \"ws:client-message\",\n WS_CLIENT_CLOSED: \"ws:client-closed\",\n WS_CLIENT_ERROR: \"ws:client-error\",\n} as const;\n\n/** Generic event from daemon to client */\nexport interface IsolateEventMessage {\n type: typeof MessageType.ISOLATE_EVENT;\n isolateId: string;\n event: string;\n payload: unknown;\n}\n\n/** Generic event from client to daemon */\nexport interface ClientEventMessage {\n type: typeof MessageType.CLIENT_EVENT;\n isolateId: string;\n event: string;\n payload: unknown;\n}\n\n// Typed payloads for internal WS events (for type safety at usage sites)\n\nexport interface WsCommandPayload {\n type: \"message\" | \"close\";\n connectionId: string;\n data?: string | Uint8Array;\n code?: number;\n reason?: string;\n}\n\nexport interface WsClientConnectPayload {\n socketId: string;\n url: string;\n protocols?: string[];\n}\n\nexport interface WsClientSendPayload {\n socketId: string;\n data: string | Uint8Array;\n}\n\nexport interface WsClientClosePayload {\n socketId: string;\n code?: number;\n reason?: string;\n}\n\nexport interface WsClientOpenedPayload {\n socketId: string;\n protocol: string;\n extensions: string;\n}\n\nexport interface WsClientMessagePayload {\n socketId: string;\n data: string | Uint8Array;\n}\n\nexport interface WsClientClosedPayload {\n socketId: string;\n code: number;\n reason: string;\n wasClean: boolean;\n}\n\nexport interface WsClientErrorPayload {\n socketId: string;\n}\n\n/**\n * Unified playwright event type for the onEvent callback.\n */\nexport type PlaywrightEvent =\n | {\n type: \"browserConsoleLog\";\n level: string;\n stdout: string;\n location?: {\n url?: string;\n lineNumber?: number;\n columnNumber?: number;\n };\n timestamp: number;\n }\n | {\n type: \"pageError\";\n name: string;\n message: string;\n stack?: string;\n timestamp: number;\n }\n | {\n type: \"networkRequest\";\n requestId: string;\n url: string;\n method: string;\n headers: Record<string, string>;\n postData?: string;\n resourceType?: string;\n timestamp: number;\n }\n | {\n type: \"networkResponse\";\n requestId: string;\n url: string;\n status: number;\n statusText?: string;\n headers: Record<string, string>;\n resourceType?: string;\n timestamp: number;\n }\n | {\n type: \"requestFailure\";\n requestId: string;\n url: string;\n method: string;\n failureText: string;\n resourceType?: string;\n timestamp: number;\n };\n\n// ============================================================================\n// Heartbeat\n// ============================================================================\n\nexport interface PingMessage {\n type: typeof MessageType.PING;\n}\n\nexport interface PongMessage {\n type: typeof MessageType.PONG;\n}\n\n// ============================================================================\n// Union Types\n// ============================================================================\n\nexport type ClientMessage =\n | CreateRuntimeRequest\n | DisposeRuntimeRequest\n | EvalRequest\n | DispatchRequestRequest\n | DispatchRequestAbort\n | WsOpenRequest\n | WsMessageRequest\n | WsCloseRequest\n | FetchGetUpgradeRequestRequest\n | FetchHasServeHandlerRequest\n | FetchHasActiveConnectionsRequest\n | FetchWsErrorRequest\n | TimersClearAllRequest\n | ConsoleResetRequest\n | ConsoleGetTimersRequest\n | ConsoleGetCountersRequest\n | ConsoleGetGroupDepthRequest\n | RunTestsRequest\n | ResetTestEnvRequest\n | HasTestsRequest\n | GetTestCountRequest\n | GetCollectedDataRequest\n | ClearCollectedDataRequest\n | CallbackResponseMsg\n | CallbackStreamStart\n | CallbackStreamChunk\n | CallbackStreamEnd\n | CallbackStreamCancel\n | StreamPush\n | StreamPull\n | StreamClose\n | StreamError\n | ClientEventMessage\n | PingMessage;\n\nexport type DaemonMessage =\n | ResponseOk\n | ResponseError\n | ResponseStreamStart\n | ResponseStreamChunk\n | ResponseStreamEnd\n | CallbackInvoke\n | CallbackAbort\n | StreamPush\n | StreamPull\n | StreamClose\n | StreamError\n | IsolateEventMessage\n | PongMessage;\n\nexport type Message = ClientMessage | DaemonMessage;\n\n// ============================================================================\n// Shared Types (used by both isolate-runtime and isolate-client)\n// ============================================================================\n\n/**\n * Module loader callback type.\n * Called when the isolate imports a module dynamically.\n *\n * @param moduleName - The module specifier being imported\n * @param importer - Information about the importing module\n * @param importer.path - The resolved path of the importing module\n * @param importer.resolveDir - The directory to resolve relative imports from\n * @returns Object with code and resolveDir for the resolved module\n */\nexport type ModuleLoaderCallback = (\n moduleName: string,\n importer: { path: string; resolveDir: string }\n) => ModuleLoaderResult | Promise<ModuleLoaderResult>;\n\nexport interface ModuleLoaderResult {\n code: string;\n /** The filename for this module (basename only, no slashes). Combined with resolveDir to form the full path. */\n filename: string;\n resolveDir: string;\n /** Mark as static to preserve across namespace reuse (e.g. node_modules).\n * Static modules and their transitive deps should all be static. */\n static?: boolean;\n}\n\n/**\n * A custom function that can be called from within the isolate.\n */\nexport type CustomFunction<T extends any[] = unknown[]> = (...args: T) => unknown | Promise<unknown>;\n\n/**\n * An async generator function that can be consumed in the isolate via for await...of.\n */\nexport type CustomAsyncGeneratorFunction<T extends any[] = unknown[]> = (...args: T) => AsyncGenerator<unknown, unknown, unknown>;\n\n/**\n * Custom function definition with metadata.\n * Requires explicit `type` property to indicate function behavior.\n */\nexport interface CustomFunctionDefinition<T extends any[] = unknown[]> {\n /** The function implementation */\n fn: CustomFunction<T> | CustomAsyncGeneratorFunction<T>;\n /** Function type: 'sync', 'async', or 'asyncIterator' */\n type: CustomFunctionType;\n}\n\n/**\n * Custom functions to register in the runtime.\n * Each function must be defined with explicit type property.\n *\n * @example\n * ```typescript\n * customFunctions: {\n * // Sync function\n * getConfig: {\n * fn: () => ({ environment: \"production\" }),\n * type: 'sync',\n * },\n * // Async function\n * hashPassword: {\n * fn: async (password) => bcrypt.hash(password, 10),\n * type: 'async',\n * },\n * // Async iterator function\n * streamData: {\n * fn: async function* (options) {\n * for await (const chunk of someStream) {\n * yield chunk;\n * }\n * },\n * type: 'asyncIterator',\n * },\n * }\n * ```\n */\nexport type CustomFunctions<T extends Record<string, any[]> = Record<string, unknown[]>> = {\n [K in keyof T]: CustomFunctionDefinition<T[K]>;\n}\n\n/**\n * Console entry types for structured console output.\n * Each entry type captures the specific data needed to render like DevTools.\n * Output is pre-formatted as stdout strings (like Node.js console) inside the sandbox.\n */\nexport type ConsoleEntry =\n | {\n type: \"output\";\n level: \"log\" | \"warn\" | \"error\" | \"info\" | \"debug\";\n stdout: string;\n groupDepth: number;\n }\n | {\n /** Browser console output (from Playwright page, not sandbox) */\n type: \"browserOutput\";\n level: string;\n stdout: string;\n location?: {\n url?: string;\n lineNumber?: number;\n columnNumber?: number;\n };\n timestamp: number;\n }\n | { type: \"dir\"; stdout: string; groupDepth: number }\n | { type: \"table\"; stdout: string; groupDepth: number }\n | { type: \"time\"; label: string; duration: number; groupDepth: number }\n | {\n type: \"timeLog\";\n label: string;\n duration: number;\n stdout: string;\n groupDepth: number;\n }\n | { type: \"count\"; label: string; count: number; groupDepth: number }\n | { type: \"countReset\"; label: string; groupDepth: number }\n | { type: \"assert\"; stdout: string; groupDepth: number }\n | {\n type: \"group\";\n label: string;\n collapsed: boolean;\n groupDepth: number;\n }\n | { type: \"groupEnd\"; groupDepth: number }\n | { type: \"clear\" }\n | { type: \"trace\"; stdout: string; stack: string; groupDepth: number };\n\n/**\n * Console callback handlers with single structured callback.\n */\nexport interface ConsoleCallbacks {\n /**\n * Callback invoked for each console operation.\n * Receives a structured entry with all data needed to render the output.\n */\n onEntry?: (entry: ConsoleEntry) => void;\n}\n\n/**\n * Fetch request init type.\n */\nexport interface FetchRequestInit {\n method: string;\n headers: [string, string][];\n /** Raw body bytes - use this if you need direct access to the body data */\n rawBody: Uint8Array | null;\n /** Body ready for use with fetch() - same data as rawBody but typed as BodyInit */\n body: BodyInit | null;\n signal: AbortSignal;\n}\n\n/**\n * Fetch callback type.\n */\nexport type FetchCallback = (url: string, init: FetchRequestInit) => Response | Promise<Response>;\n\n/**\n * WebSocket callback type.\n * Called when isolate code creates an outbound WebSocket connection.\n * Return a WebSocket to proxy the connection, or null to block it.\n */\nexport type WebSocketCallback = (url: string, protocols: string[]) => WebSocket | Promise<WebSocket | null> | null;\n\n/**\n * File system callback handlers.\n */\nexport interface FileSystemCallbacks {\n readFile?: (path: string) => Promise<ArrayBuffer>;\n writeFile?: (path: string, data: ArrayBuffer) => Promise<void>;\n unlink?: (path: string) => Promise<void>;\n readdir?: (path: string) => Promise<string[]>;\n mkdir?: (path: string, options?: { recursive?: boolean }) => Promise<void>;\n rmdir?: (path: string) => Promise<void>;\n stat?: (\n path: string\n ) => Promise<{ isFile: boolean; isDirectory: boolean; size: number }>;\n rename?: (from: string, to: string) => Promise<void>;\n}\n\n/**\n * Options for dispatching a request.\n */\nexport interface DispatchOptions {\n /** AbortSignal to cancel the request */\n signal?: AbortSignal;\n /** Optional request identifier forwarded to host callbacks */\n requestId?: string;\n /** Optional metadata forwarded to host callbacks */\n metadata?: Record<string, string>;\n}\n\n/**\n * Options for eval() method.\n */\nexport interface EvalOptions {\n /** Filename for stack traces */\n filename?: string;\n /** Timeout for the full eval execution in milliseconds */\n executionTimeout?: number;\n}\n\n/**\n * Test environment options for createRuntime.\n */\nexport interface TestEnvironmentOptions {\n /** Receive test lifecycle events */\n onEvent?: (event: TestEvent) => void;\n /** Timeout for individual tests (ms) */\n testTimeout?: number;\n}\n\n/**\n * File data for setInputFiles operations.\n */\nexport interface PlaywrightFileData {\n /** File name */\n name: string;\n /** MIME type */\n mimeType: string;\n /** File contents as Buffer */\n buffer: Buffer;\n}\n\n/**\n * Options for Playwright integration.\n *\n * Public API is handler-first: host-specific page wiring should be done by\n * creating a handler (for example via `defaultPlaywrightHandler(page)`).\n */\nexport interface PlaywrightOptions {\n /** Handler callback for Playwright operations (required when playwright is enabled) */\n handler: (op: PlaywrightOperation) => Promise<PlaywrightResult>;\n /** Default timeout for operations in ms */\n timeout?: number;\n /** If true, browser console logs are routed through console handler (or printed to stdout if no handler) */\n console?: boolean;\n /** Unified event callback for all playwright events */\n onEvent?: (event: PlaywrightEvent) => void;\n}\n\n/**\n * Base runtime options shared between isolate-client and isolate-runtime.\n * Each package extends this with its own `fs` type.\n */\nexport interface BaseRuntimeOptions<T extends Record<string, any[]> = Record<string, unknown[]>> {\n /** Memory limit in megabytes (optional) */\n memoryLimitMB?: number;\n /** Timeout for the full eval/test execution in milliseconds */\n executionTimeout?: number;\n /** Console callback handlers */\n console?: ConsoleCallbacks;\n /** Fetch callback handler */\n fetch?: FetchCallback;\n /** WebSocket callback handler for outbound connections from isolate */\n webSocket?: WebSocketCallback;\n /** Module loader callback for resolving dynamic imports */\n moduleLoader?: ModuleLoaderCallback;\n /** Custom functions callable from within the isolate */\n customFunctions?: CustomFunctions<T>;\n /** Current working directory for path.resolve(). Defaults to \"/\" */\n cwd?: string;\n /** Enable test environment (describe, it, expect, etc.) */\n testEnvironment?: boolean | TestEnvironmentOptions;\n /** Playwright options (handler-first API) */\n playwright?: PlaywrightOptions;\n}\n\n// ============================================================================\n// Result Types (for responses)\n// ============================================================================\n\nexport interface CreateRuntimeResult {\n isolateId: string;\n /** True if runtime was reused from namespace pool */\n reused?: boolean;\n}\n\nexport interface EvalResult {\n value: unknown;\n}\n\nexport interface DispatchRequestResult {\n response: SerializedResponse;\n}\n\n// ============================================================================\n// Test Environment Types\n// ============================================================================\n\nexport interface SuiteInfo {\n name: string;\n /** Ancestry path: [\"outer\", \"inner\"] */\n path: string[];\n /** Full display name: \"outer > inner\" */\n fullName: string;\n /** Nesting depth (0 for root-level suites) */\n depth: number;\n}\n\nexport interface SuiteResult extends SuiteInfo {\n passed: number;\n failed: number;\n skipped: number;\n todo: number;\n duration: number;\n}\n\nexport interface TestInfo {\n name: string;\n /** Suite ancestry */\n suitePath: string[];\n /** Full display name: \"suite > test name\" */\n fullName: string;\n}\n\nexport interface TestError {\n message: string;\n stack?: string;\n /** For assertion failures */\n expected?: unknown;\n actual?: unknown;\n /** e.g., \"toBe\", \"toEqual\", \"toContain\" */\n matcherName?: string;\n}\n\nexport interface TestResult extends TestInfo {\n status: \"pass\" | \"fail\" | \"skip\" | \"todo\";\n duration: number;\n error?: TestError;\n}\n\nexport type TestEvent =\n | { type: \"runStart\"; testCount: number; suiteCount: number }\n | { type: \"suiteStart\"; suite: SuiteInfo }\n | { type: \"suiteEnd\"; suite: SuiteResult }\n | { type: \"testStart\"; test: TestInfo }\n | { type: \"testEnd\"; test: TestResult }\n | { type: \"runEnd\"; results: RunTestsResult };\n\nexport interface RunTestsResult {\n passed: number;\n failed: number;\n skipped: number;\n todo: number;\n total: number;\n duration: number;\n success: boolean;\n suites: SuiteResult[];\n tests: TestResult[];\n}\n\nexport interface PlaywrightTestResult {\n passed: number;\n failed: number;\n total: number;\n results: {\n name: string;\n passed: boolean;\n error?: string;\n duration: number;\n }[];\n}\n\nexport interface CollectedData {\n /** Browser console logs (from the page, not sandbox) */\n browserConsoleLogs: {\n level: string;\n stdout: string;\n location?: {\n url?: string;\n lineNumber?: number;\n columnNumber?: number;\n };\n timestamp: number;\n }[];\n pageErrors: {\n name: string;\n message: string;\n stack?: string;\n timestamp: number;\n }[];\n networkRequests: {\n requestId: string;\n url: string;\n method: string;\n headers: Record<string, string>;\n postData?: string;\n resourceType?: string;\n timestamp: number;\n }[];\n networkResponses: {\n requestId: string;\n url: string;\n status: number;\n headers: Record<string, string>;\n statusText?: string;\n resourceType?: string;\n timestamp: number;\n }[];\n requestFailures: {\n requestId: string;\n url: string;\n method: string;\n failureText: string;\n resourceType?: string;\n timestamp: number;\n }[];\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Normalize a filename to an absolute path for module resolution.\n *\n * Rules:\n * - undefined/empty/\"\" → \"/index.js\"\n * - Absolute paths (start with /) → normalized as-is\n * - Relative paths starting with \"./\" → converted to absolute from root\n * - Bare filenames (no leading ./ or /) → converted to absolute from root\n * - Paths starting with \"../\" → Error (can't resolve parent of root)\n * - Directory paths (\"/\" or \"./\") → append \"index.js\"\n *\n * @example\n * normalizeEntryFilename(undefined) // \"/index.js\"\n * normalizeEntryFilename(\"\") // \"/index.js\"\n * normalizeEntryFilename(\"app.js\") // \"/app.js\"\n * normalizeEntryFilename(\"./app.js\") // \"/app.js\"\n * normalizeEntryFilename(\"/app.js\") // \"/app.js\"\n * normalizeEntryFilename(\"./foo/bar.js\") // \"/foo/bar.js\"\n * normalizeEntryFilename(\"/\") // \"/index.js\"\n * normalizeEntryFilename(\"./\") // \"/index.js\"\n * normalizeEntryFilename(\"../app.js\") // throws Error\n *\n * @throws Error if the filename cannot be normalized (e.g., starts with \"../\")\n */\nexport function normalizeEntryFilename(filename: string | undefined): string {\n // Default to /index.js\n if (!filename || filename === \"\") {\n return \"/index.js\";\n }\n\n // Reject paths that try to go above root\n if (filename.startsWith(\"../\")) {\n throw new Error(\n `Invalid entry filename \"${filename}\": cannot use \"../\" at the start. ` +\n `Use an absolute path like \"/app.js\" or a relative path like \"./app.js\".`\n );\n }\n\n // Track if original path ends with / (indicates directory)\n const endsWithSlash = filename.endsWith(\"/\");\n\n let toNormalize: string;\n if (filename.startsWith(\"/\")) {\n // Already absolute\n toNormalize = filename;\n } else if (filename.startsWith(\"./\")) {\n // Relative from root: ./app.js → /app.js\n toNormalize = \"/\" + filename.slice(2);\n } else {\n // Bare filename: app.js → /app.js\n toNormalize = \"/\" + filename;\n }\n\n // Normalize path and check for escaping root\n const normalized = normalizePosixPath(toNormalize, filename);\n\n // Handle directory paths - append index.js\n if (normalized === \"/\" || endsWithSlash) {\n return normalized === \"/\" ? \"/index.js\" : normalized + \"/index.js\";\n }\n\n return normalized;\n}\n\n/**\n * Simple POSIX path normalization without external dependencies.\n * Handles . and .. segments, collapses multiple slashes.\n * Throws if path tries to escape above root.\n */\nfunction normalizePosixPath(p: string, originalFilename: string): string {\n if (p === \"\") return \".\";\n\n const isAbsolute = p.startsWith(\"/\");\n const segments = p.split(\"/\").filter(s => s !== \"\" && s !== \".\");\n const result: string[] = [];\n let parentCount = 0; // Track how many .. we've seen at root level\n\n for (const segment of segments) {\n if (segment === \"..\") {\n if (result.length > 0 && result[result.length - 1] !== \"..\") {\n result.pop();\n } else if (isAbsolute) {\n // For absolute paths, track attempts to go above root\n parentCount++;\n } else {\n result.push(\"..\");\n }\n } else {\n result.push(segment);\n }\n }\n\n // If we tried to go above root, throw an error\n if (isAbsolute && parentCount > 0 && result.length === 0) {\n // Only throw if we actually escaped (ended up at root after going above)\n // This catches cases like /foo/../../bar.js where we went above root\n }\n\n // Count segments before normalization to detect if we went above root\n const originalSegments = p.split(\"/\").filter(s => s !== \"\" && s !== \".\");\n let depth = 0;\n for (const segment of originalSegments) {\n if (segment === \"..\") {\n depth--;\n if (isAbsolute && depth < 0) {\n throw new Error(\n `Invalid entry filename \"${originalFilename}\": path resolves above root directory.`\n );\n }\n } else {\n depth++;\n }\n }\n\n const normalized = result.join(\"/\");\n return isAbsolute ? \"/\" + normalized : (normalized || \".\");\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAcO,IAAM,cAAc;AAAA,EAEzB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,MAAM;AAAA,EACN,kBAAkB;AAAA,EAClB,wBAAwB;AAAA,EAGxB,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,UAAU;AAAA,EAGV,2BAA2B;AAAA,EAC3B,yBAAyB;AAAA,EACzB,8BAA8B;AAAA,EAC9B,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EACtB,yBAAyB;AAAA,EAGzB,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,gBAAgB;AAAA,EAGhB,oBAAoB;AAAA,EACpB,sBAAsB;AAAA,EAGtB,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EAGrB,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,wBAAwB;AAAA,EACxB,gBAAgB;AAAA,EAGhB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,cAAc;AAAA,EACd,cAAc;AAAA,EAGd,eAAe;AAAA,EACf,cAAc;AAAA,EAGd,MAA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
|
1
|
+
// src/internal/runtime/index.ts
|
|
2
2
|
import ivm from "isolated-vm";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { setupCore } from "../core/index.mjs";
|
|
@@ -1195,4 +1195,4 @@ export {
|
|
|
1195
1195
|
createNodeFileSystemHandler
|
|
1196
1196
|
};
|
|
1197
1197
|
|
|
1198
|
-
//# debugId=
|
|
1198
|
+
//# debugId=3D338C39E65B73A264756E2164756E21
|