@snyxex/pipex 1.0.2 → 1.0.3
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/LICENSE +1 -1
- package/README.md +238 -139
- package/dist/compression-2mm0MhWY.mjs +1 -0
- package/dist/compression-CtrHxa9G.d.mts +38 -0
- package/dist/compression-DnVFu8TM.d.cts +38 -0
- package/dist/compression-DrgzribA.cjs +1 -0
- package/dist/compression.cjs +1 -0
- package/dist/compression.d.cts +2 -0
- package/dist/compression.d.mts +2 -0
- package/dist/compression.mjs +1 -0
- package/dist/core-BOdvxKBq.mjs +2 -0
- package/dist/core-B_z1gN5W.cjs +2 -0
- package/dist/dataEngine-4m6GTOLe.mjs +1 -0
- package/dist/dataEngine-Bvl6amzP.cjs +1 -0
- package/dist/dataEngine-D-fIXgE7.d.cts +232 -0
- package/dist/dataEngine-DUEmWp7a.d.mts +232 -0
- package/dist/encryption-BmmNECIc.d.cts +44 -0
- package/dist/encryption-CnSL1BEY.d.mts +44 -0
- package/dist/encryption-CqxtoqAD.mjs +1 -0
- package/dist/encryption-DdP1zFYl.cjs +1 -0
- package/dist/encryption.cjs +1 -0
- package/dist/encryption.d.cts +2 -0
- package/dist/encryption.d.mts +2 -0
- package/dist/encryption.mjs +1 -0
- package/dist/hashing-B6xGcbQR.d.mts +33 -0
- package/dist/hashing-ChrADfcH.mjs +1 -0
- package/dist/hashing-JtOHPybU.cjs +1 -0
- package/dist/hashing-LY-8x66g.d.cts +33 -0
- package/dist/hashing.cjs +1 -0
- package/dist/hashing.d.cts +2 -0
- package/dist/hashing.d.mts +2 -0
- package/dist/hashing.mjs +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +302 -0
- package/dist/index.d.mts +87 -550
- package/dist/index.mjs +1 -3
- package/dist/kms.cjs +1 -0
- package/dist/kms.d.cts +3 -0
- package/dist/kms.d.mts +3 -0
- package/dist/kms.mjs +1 -0
- package/dist/kms_encryption-Da-KqjKI.d.mts +33 -0
- package/dist/kms_encryption-Dh1LEHhk.d.cts +33 -0
- package/dist/kms_encryption-R9auKGW4.mjs +1 -0
- package/dist/kms_encryption-xyWi65rZ.cjs +1 -0
- package/dist/native.cjs +1 -0
- package/dist/native.d.cts +2 -0
- package/dist/native.d.mts +2 -0
- package/dist/native.mjs +1 -0
- package/dist/parallel.cjs +1 -0
- package/dist/parallel.d.cts +2 -0
- package/dist/parallel.d.mts +2 -0
- package/dist/parallel.mjs +1 -0
- package/dist/plugin-C9Kd9coY.d.cts +16 -0
- package/dist/plugin-CE94-p8P.d.mts +16 -0
- package/dist/resourceLimits-C1HHDwXQ.mjs +1 -0
- package/dist/resourceLimits-CI0Qrqdf.cjs +1 -0
- package/dist/types-Bytga6zd.d.mts +155 -0
- package/dist/types-ia4x-Dvp.d.cts +155 -0
- package/dist/validation-CqmhNHdW.d.cts +32 -0
- package/dist/validation-D17IkoHy.d.mts +32 -0
- package/dist/validation-P5WRSAUK.mjs +1 -0
- package/dist/validation-pEeJmCad.cjs +1 -0
- package/dist/validation.cjs +1 -0
- package/dist/validation.d.cts +2 -0
- package/dist/validation.d.mts +2 -0
- package/dist/validation.mjs +1 -0
- package/dist/worker-CbuCpSNc.d.cts +37 -0
- package/dist/worker-CgCC-BWG.d.mts +37 -0
- package/dist/worker-I_kqxWeK.cjs +1 -0
- package/dist/worker-c0_VZ9c7.mjs +1 -0
- package/package.json +120 -23
- package/SECURITY.md +0 -41
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/docs/architecture.md +0 -124
- package/docs/encryption-v4-migration.md +0 -45
- package/docs/enterprise.md +0 -280
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#maxFrameBytes","#maxFrames","#payloadBytes","#extensionTypePending","#consumeBytes","#addChildren","#ensureMinimumRemaining","#invalidInput","#completeIfReady","#frameBytes","#frameTooLarge","#pending","#applyLength","#remainingValues","#readToken","#setPayload","#readLength","#setExtensionPayload","#frames","abortError","#maxInputBytes","#receivedBytes","#engine","#withAtomicOutput","#streamContext","#engine","#trustedTypes","#engine","#streamContext","#into","#bridge","MAX_TIMER_MS","#plugins","#activeRequests","#pendingWork","#finishedRequests","#requestPipelines","#limits","#validateLimits","#dlq","#logger","#tracer","#auditLogger","#registry","#schema","#pluginView","MAGIC","TAG_LENGTH","zlibConstants","MAX_TIMER_MS","abortError","#pool","#processName","#reverseName","#taskTimeoutMs","#maxThreads","#maxQueue","#maxInFlight","#closeTimeoutMs","#reversible","#idleWaiters","#onPoolError","#fatalError","#accepting","#run","#inFlight","#closePromise"],"sources":["../src/core/types.ts","../src/core/errors.ts","../src/core/plugin.ts","../src/core/resourceLimits.ts","../src/core/frameLimits.ts","../src/core/operations.ts","../src/core/observability.ts","../src/core/core.ts","../src/core/secureFiles.ts","../src/core/controllers/FileController.ts","../src/core/controllers/BinaryController.ts","../src/core/controllers/StreamController.ts","../src/core/dataEngine.ts","../src/core/kmsCapabilities.ts","../src/plugin/hashing.ts","../src/plugin/encryptionFormat.ts","../src/plugin/encryption.ts","../src/plugin/compression.ts","../src/plugin/performance.ts","../src/plugin/worker.ts","../src/core/validation.ts","../src/plugin/kms_encryption.ts","../src/index.ts"],"sourcesContent":["import type { Duplex, Writable } from 'node:stream';\nimport { z } from 'zod';\n\n// ─── Observability Types ──────────────────────────────────────────────────────\n\nexport interface Logger {\n info(message: string, context?: Record<string, unknown>): void;\n warn(message: string, context?: Record<string, unknown>): void;\n error(message: string, context?: Record<string, unknown>): void;\n debug(message: string, context?: Record<string, unknown>): void;\n}\n\nexport interface Span {\n setAttribute(key: string, value: unknown): this;\n addEvent(name: string, attributes?: Record<string, unknown>): this;\n end(): void;\n}\n\nexport interface Tracer {\n startSpan(name: string, context?: ProcessorContext): Span;\n}\n\n// ─── Resilience Types ─────────────────────────────────────────────────────────\n\nexport interface RetryOptions {\n attempts: number;\n backoff: 'exponential' | 'fixed';\n delayMs: number;\n}\n\nexport interface EngineLimits {\n maxInputBytes: number;\n maxOutputBytes: number;\n maxFrameBytes: number;\n maxFrames: number;\n maxConcurrentOperations: number;\n operationTimeoutMs: number;\n maxRetryAttempts: number;\n maxRetryDelayMs: number;\n /** Maximum provider-wrapped data-key bytes accepted in a KMS envelope. */\n maxKmsEncryptedKeyBytes: number;\n /** Maximum UTF-8 bytes accepted for a provider key identifier. */\n maxKmsKeyIdBytes: number;\n}\n\nexport interface OperationOptions {\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\n/** expectedType must come from trusted application configuration, never the received result. */\nexport interface BinaryUndoOptions extends OperationOptions {\n expectedType?: string;\n}\n\nexport interface StreamPluginContext {\n /** Engine-owned accounting for work that continues after cancellation. */\n readonly track?: (pending: Promise<unknown>) => void;\n readonly requestId: string;\n readonly signal: AbortSignal;\n readonly limits: Readonly<EngineLimits>;\n readonly logger?: Logger;\n readonly tracer?: Tracer;\n}\n\n// ─── Security & Audit Types ───────────────────────────────────────────────────\n\nexport interface AuditRecord {\n requestId: string;\n operation: 'pack' | 'unpack' | 'process' | 'reverse';\n pluginChain: string[];\n timestamp: number;\n metadata: Record<string, unknown>;\n}\n\nexport interface AuditLogger {\n log(record: AuditRecord): void | Promise<void>;\n}\n\nexport type KmsOperation = 'encrypt' | 'decrypt' | 'generateDataKey';\n\nexport interface KmsProviderCapabilities {\n readonly encrypt: boolean;\n readonly decrypt: boolean;\n readonly generateDataKey: boolean;\n}\n\nexport interface KmsProvider {\n /** Explicit false disables an operation even when a compatibility stub exists. */\n readonly capabilities?: Partial<KmsProviderCapabilities>;\n encrypt?(data: Buffer, keyId: string, options?: KmsRequestOptions): Promise<Buffer>;\n decrypt?(data: Buffer, keyId: string, options?: KmsRequestOptions): Promise<Buffer>;\n generateDataKey?(keyId: string, options?: KmsRequestOptions): Promise<{ plaintext: Buffer; ciphertext: Buffer }>;\n}\n\nexport interface KmsRequestOptions {\n signal?: AbortSignal;\n}\n\nexport interface SchemaRegistry {\n getSchema(subject: string, version?: number): Promise<z.ZodType<any>>;\n}\n\nexport interface EngineConfig {\n plugins?: { name: string; options?: unknown }[];\n limits?: Partial<EngineLimits>;\n logger?: Logger;\n tracer?: Tracer;\n auditLogger?: AuditLogger;\n /** Optional caller-owned failure sink; `dlq` is retained for compatibility. */\n dlq?: Writable;\n schema?: z.ZodType<any>;\n schemaRegistry?: SchemaRegistry;\n}\n\n// ─── Core types ───────────────────────────────────────────────────────────────\n\nexport interface ProcessorContext {\n readonly requestId: string;\n readonly timestamp: number;\n readonly signal?: AbortSignal;\n readonly limits?: Readonly<EngineLimits>;\n metadata: Record<string, unknown>;\n logger?: Logger;\n span?: Span;\n}\n\nexport interface ProcessorPlugin {\n readonly name: string;\n readonly version: string;\n readonly reversible?: boolean;\n readonly streaming?: boolean;\n process(data: Buffer, ctx: ProcessorContext): Promise<Buffer> | Buffer;\n reverse?(data: Buffer, ctx: ProcessorContext): Promise<Buffer> | Buffer;\n createStream?(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex;\n retryOptions?: RetryOptions;\n}\n\nexport type PluginOperation = 'process' | 'reverse' | 'stream';\n\n/** Normalized, runtime-validated operations exposed by a plugin. */\nexport interface PluginCapabilities {\n readonly process: true;\n readonly reverse: boolean;\n readonly streaming: boolean;\n readonly streamMode: 'native' | 'fallback' | 'none';\n}\n\n/** Capability view for a plugin registered with a DataEngine. */\nexport interface RegisteredPluginCapabilities extends PluginCapabilities {\n readonly plugin: string;\n}\n\nexport interface EngineResult {\n readonly data: Buffer;\n readonly originalType: string;\n readonly pipeline: string[];\n readonly metrics: { durationMs: number; steps: Record<string, number> };\n}\n\n// ─── Manifest — written as first msgpack frame in every binary output ─────────\n\nexport interface PipeXManifest {\n readonly __pipex_v: 1;\n readonly plugins: string[]; // name@version in execution order\n readonly ts: number; // unix ms\n}\n\nexport function isManifest(value: unknown): value is PipeXManifest {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Record<string, unknown>;\n return record['__pipex_v'] === 1\n && Array.isArray(record['plugins'])\n && record['plugins'].length <= 256\n && record['plugins'].every(plugin => typeof plugin === 'string' && plugin.length <= 256)\n && typeof record['ts'] === 'number'\n && Number.isSafeInteger(record['ts'])\n && record['ts'] >= 0;\n}\n\n// ─── Engine events ────────────────────────────────────────────────────────────\n\nexport interface EngineEvents {\n start: [requestId: string];\n 'plugin:after': [name: string, durationMs: number];\n progress: [bytes: number, requestId: string];\n error: [err: Error, requestId: string];\n end: [requestId: string, durationMs: number];\n}\n","export type PipeXErrorCode =\n | 'UNSUPPORTED_REVERSE'\n | 'UNSUPPORTED_STREAMING'\n | 'INVALID_PLUGIN_CAPABILITY'\n | 'OPERATION_ABORTED'\n | 'OPERATION_TIMEOUT'\n | 'KMS_PROVIDER_FAILURE'\n | 'KMS_AUTHENTICATION_FAILED'\n | 'KMS_PROVIDER_AUTHENTICATION_FAILED'\n | 'KMS_PROVIDER_UNAVAILABLE'\n | 'UNSUPPORTED_KMS_OPERATION'\n | 'INVALID_KMS_PROVIDER_CAPABILITY'\n | 'WORKER_POOL_CLOSED'\n | 'WORKER_QUEUE_FULL'\n | 'WORKER_POOL_CLOSE_FAILURE'\n | 'WORKER_TASK_FAILURE';\n\nexport class PipeXError extends Error {\n public override readonly name: string = 'PipeXError';\n\n constructor(\n public readonly code: PipeXErrorCode,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n }\n}\n\nexport class UnsupportedReverseError extends PipeXError {\n public override readonly name: string = 'UnsupportedReverseError';\n\n constructor(public readonly plugin: string) {\n super('UNSUPPORTED_REVERSE', `[PipeX] Plugin ${plugin} does not support reverse operations`);\n }\n}\n\nexport class UnsupportedStreamingError extends PipeXError {\n public override readonly name: string = 'UnsupportedStreamingError';\n constructor(public readonly plugin: string) {\n super('UNSUPPORTED_STREAMING', `[PipeX] Plugin ${plugin} does not support stream operations`);\n }\n}\n\nexport type InvalidPluginCapabilityIssue =\n | 'MUST_BE_BOOLEAN'\n | 'MISSING_IMPLEMENTATION'\n | 'CONFLICTING_IMPLEMENTATION';\n\nexport class InvalidPluginCapabilityError extends PipeXError {\n public override readonly name: string = 'InvalidPluginCapabilityError';\n\n constructor(\n public readonly plugin: string,\n public readonly capability: 'reversible' | 'streaming',\n public readonly issue: InvalidPluginCapabilityIssue,\n ) {\n const details = issue === 'MUST_BE_BOOLEAN'\n ? 'must be a boolean when declared'\n : issue === 'MISSING_IMPLEMENTATION'\n ? 'is declared but its implementation is missing'\n : 'is disabled but its implementation is present';\n super(\n 'INVALID_PLUGIN_CAPABILITY',\n `[PipeX] Plugin ${plugin} has an invalid ${capability} capability: ${details}`,\n );\n }\n}\n\nexport class OperationAbortedError extends PipeXError {\n public override readonly name: string = 'OperationAbortedError';\n constructor(options?: ErrorOptions) {\n super('OPERATION_ABORTED', '[PipeX] Operation aborted', options);\n }\n}\n\nexport class OperationTimeoutError extends PipeXError {\n public override readonly name: string = 'OperationTimeoutError';\n constructor(options?: ErrorOptions) {\n super('OPERATION_TIMEOUT', '[PipeX] Operation timed out', options);\n }\n}\n\nexport class KmsProviderError extends PipeXError {\n public override readonly name: string = 'KmsProviderError';\n constructor(public readonly operation: 'generateDataKey' | 'decrypt' | 'encrypt', options?: ErrorOptions) {\n super('KMS_PROVIDER_FAILURE', `[PipeX] KMS ${operation} failed`, options);\n }\n}\n\nexport class KmsAuthenticationError extends PipeXError {\n public override readonly name: string = 'KmsAuthenticationError';\n constructor() {\n super('KMS_AUTHENTICATION_FAILED', '[PipeX] KMS envelope authentication failed');\n }\n}\n\nexport class KmsProviderAuthenticationError extends PipeXError {\n public override readonly name: string = 'KmsProviderAuthenticationError';\n constructor(public readonly operation: 'generateDataKey' | 'decrypt' | 'encrypt') {\n super('KMS_PROVIDER_AUTHENTICATION_FAILED', `[PipeX] KMS ${operation} authentication failed`);\n }\n}\n\nexport class KmsProviderUnavailableError extends PipeXError {\n public override readonly name: string = 'KmsProviderUnavailableError';\n constructor(public readonly operation: 'generateDataKey' | 'decrypt' | 'encrypt') {\n super('KMS_PROVIDER_UNAVAILABLE', `[PipeX] KMS ${operation} provider unavailable`);\n }\n}\n\nexport class UnsupportedKmsOperationError extends PipeXError {\n public override readonly name: string = 'UnsupportedKmsOperationError';\n constructor(public readonly operation: 'generateDataKey' | 'decrypt' | 'encrypt') {\n super('UNSUPPORTED_KMS_OPERATION', `[PipeX] KMS provider does not support ${operation}`);\n }\n}\n\nexport type InvalidKmsProviderCapabilityIssue = 'MUST_BE_BOOLEAN' | 'MISSING_IMPLEMENTATION';\n\nexport class InvalidKmsProviderCapabilityError extends PipeXError {\n public override readonly name: string = 'InvalidKmsProviderCapabilityError';\n constructor(\n public readonly operation: 'generateDataKey' | 'decrypt' | 'encrypt',\n public readonly issue: InvalidKmsProviderCapabilityIssue,\n ) {\n const details = issue === 'MUST_BE_BOOLEAN'\n ? 'must be a boolean when declared'\n : 'is declared but its implementation is missing';\n super('INVALID_KMS_PROVIDER_CAPABILITY', `[PipeX] Invalid KMS ${operation} capability: ${details}`);\n }\n}\n\nexport class WorkerPoolClosedError extends PipeXError {\n public override readonly name: string = 'WorkerPoolClosedError';\n constructor() {\n super('WORKER_POOL_CLOSED', '[PipeX] Worker pool is closed');\n }\n}\n\nexport class WorkerQueueFullError extends PipeXError {\n public override readonly name: string = 'WorkerQueueFullError';\n constructor(public readonly maxQueue: number) {\n super('WORKER_QUEUE_FULL', `[PipeX] Worker queue is full (maximum ${maxQueue} waiting tasks)`);\n }\n}\n\nexport class WorkerPoolCloseError extends PipeXError {\n public override readonly name: string = 'WorkerPoolCloseError';\n constructor(options?: ErrorOptions) {\n super('WORKER_POOL_CLOSE_FAILURE', '[PipeX] Worker pool failed to close cleanly', options);\n }\n}\n\nexport class WorkerTaskError extends PipeXError {\n public override readonly name: string = 'WorkerTaskError';\n constructor(public readonly taskName: string, options?: ErrorOptions) {\n super('WORKER_TASK_FAILURE', `[PipeX] Worker task ${taskName} failed`, options);\n }\n}\n","import type { ProcessorPlugin, ProcessorContext, RetryOptions } from './types.js';\nimport { UnsupportedReverseError } from './errors.js';\n\nexport abstract class BasePlugin implements ProcessorPlugin {\n abstract readonly name: string;\n abstract readonly version: string;\n public retryOptions?: RetryOptions;\n\n public get reversible(): boolean {\n return this.reverse !== BasePlugin.prototype.reverse;\n }\n\n constructor(protected options: any = {}) {}\n\n abstract process(data: Buffer, context: ProcessorContext): Promise<Buffer> | Buffer;\n\n /** Unsupported by default. Subclasses must implement reverse explicitly. */\n reverse(_data: Buffer, _context: ProcessorContext): Promise<Buffer> | Buffer {\n throw new UnsupportedReverseError(`${this.name}@${this.version}`);\n }\n}\n","import type { EngineLimits, ProcessorContext, StreamPluginContext } from './types.js';\n\nexport const DEFAULT_LIMITS: Readonly<EngineLimits> = Object.freeze({\n maxInputBytes: 64 * 1024 * 1024,\n maxOutputBytes: 256 * 1024 * 1024,\n maxFrameBytes: 8 * 1024 * 1024,\n maxFrames: 100_000,\n maxConcurrentOperations: 32,\n operationTimeoutMs: 5 * 60_000,\n maxRetryAttempts: 5,\n maxRetryDelayMs: 30_000,\n maxKmsEncryptedKeyBytes: 64 * 1024,\n maxKmsKeyIdBytes: 512,\n});\n\ntype LimitContext = Pick<ProcessorContext | StreamPluginContext, 'limits'>;\n\n/** Maximum buffer a plugin can receive: external input or prior plugin output. */\nexport function pluginInputLimit(context?: LimitContext): number {\n const limits = context?.limits ?? DEFAULT_LIMITS;\n return Math.max(limits.maxInputBytes, limits.maxOutputBytes);\n}\n\n/** Maximum buffer a plugin may produce. */\nexport function pluginOutputLimit(context?: LimitContext): number {\n return context?.limits?.maxOutputBytes ?? DEFAULT_LIMITS.maxOutputBytes;\n}\n","import { Transform, type TransformCallback } from 'node:stream';\n\ntype LengthKind = 'array' | 'map' | 'payload' | 'extension';\n\ninterface PendingLength {\n readonly kind: LengthKind;\n readonly bytes: number;\n read: number;\n value: number;\n}\n\n/**\n * Incremental MessagePack structural scanner. It finds top-level frame\n * boundaries without decoding values and rejects impossible oversized frames\n * as soon as their length header is complete.\n */\nclass MessagePackFrameScanner {\n readonly #maxFrameBytes: number;\n readonly #maxFrames: number;\n #frameBytes = 0;\n #remainingValues = 1;\n #payloadBytes = 0;\n #extensionTypePending = false;\n #pending?: PendingLength;\n #frames = 0;\n\n constructor(maxFrameBytes: number, maxFrames: number) {\n this.#maxFrameBytes = maxFrameBytes;\n this.#maxFrames = maxFrames;\n }\n\n scan(chunk: Buffer): number[] {\n const boundaries: number[] = [];\n let offset = 0;\n\n while (offset < chunk.length) {\n if (this.#payloadBytes > 0) {\n if (this.#extensionTypePending) {\n this.#consumeBytes(1);\n const extensionType = chunk[offset]!;\n offset++;\n this.#payloadBytes--;\n this.#extensionTypePending = false;\n // These msgpackr extensions consume one subsequent value. Include it\n // in this frame, including when the extension or child is fragmented.\n if (extensionType === 0x65 || extensionType === 0x73 || extensionType === 0x78) {\n this.#addChildren(1);\n this.#ensureMinimumRemaining(this.#payloadBytes);\n } else if (extensionType !== 0x00 && extensionType !== 0x42\n && extensionType !== 0x74 && extensionType !== 0xff) {\n // Records, bundles, references and unknown/custom extensions are\n // outside the profile implemented by our scanner and encoders.\n this.#invalidInput();\n }\n if (this.#payloadBytes === 0) this.#completeIfReady(offset, boundaries);\n continue;\n }\n const consumed = Math.min(this.#payloadBytes, chunk.length - offset);\n this.#consumeBytes(consumed);\n this.#payloadBytes -= consumed;\n offset += consumed;\n if (this.#payloadBytes > 0 && this.#frameBytes === this.#maxFrameBytes) this.#frameTooLarge();\n if (this.#payloadBytes === 0) this.#completeIfReady(offset, boundaries);\n continue;\n }\n\n if (this.#pending) {\n const pending = this.#pending;\n this.#consumeBytes(1);\n pending.value = pending.value * 256 + chunk[offset]!;\n offset++;\n pending.read++;\n if (pending.read === pending.bytes) {\n const { kind, value } = pending;\n this.#pending = undefined;\n this.#applyLength(kind, value);\n this.#completeIfReady(offset, boundaries);\n }\n continue;\n }\n\n this.#consumeBytes(1);\n const token = chunk[offset]!;\n offset++;\n this.#remainingValues--;\n if (this.#remainingValues < 0) this.#invalidInput();\n this.#readToken(token);\n this.#completeIfReady(offset, boundaries);\n }\n\n return boundaries;\n }\n\n finish(): void {\n if (this.#frameBytes !== 0 || this.#pending || this.#payloadBytes !== 0) {\n throw new Error('[PipeX] Invalid MessagePack input: incomplete frame');\n }\n }\n\n #consumeBytes(count: number): void {\n if (count > this.#maxFrameBytes - this.#frameBytes) this.#frameTooLarge();\n this.#frameBytes += count;\n }\n\n #ensureMinimumRemaining(additionalBytes = 0): void {\n const capacity = this.#maxFrameBytes - this.#frameBytes;\n if (additionalBytes > capacity || this.#remainingValues > capacity - additionalBytes) {\n this.#frameTooLarge();\n }\n }\n\n #addChildren(count: number): void {\n if (!Number.isSafeInteger(count) || count < 0\n || count > Number.MAX_SAFE_INTEGER - this.#remainingValues) this.#invalidInput();\n this.#remainingValues += count;\n this.#ensureMinimumRemaining();\n }\n\n #setPayload(length: number): void {\n if (!Number.isSafeInteger(length) || length < 0) this.#invalidInput();\n this.#ensureMinimumRemaining(length);\n this.#payloadBytes = length;\n }\n\n #setExtensionPayload(length: number): void {\n this.#setPayload(length + 1);\n this.#extensionTypePending = true;\n }\n\n #readLength(kind: LengthKind, bytes: number): void {\n this.#pending = { kind, bytes, read: 0, value: 0 };\n }\n\n #applyLength(kind: LengthKind, value: number): void {\n if (kind === 'array') this.#addChildren(value);\n else if (kind === 'map') this.#addChildren(value * 2);\n else {\n this.#setPayload(value + (kind === 'extension' ? 1 : 0));\n this.#extensionTypePending = kind === 'extension';\n }\n }\n\n #readToken(token: number): void {\n if (token <= 0x7f || token >= 0xe0 || (token >= 0xc0 && token <= 0xc3)) {\n if (token === 0xc1) this.#invalidInput();\n return;\n }\n if (token >= 0x80 && token <= 0x8f) return this.#addChildren((token & 0x0f) * 2);\n if (token >= 0x90 && token <= 0x9f) return this.#addChildren(token & 0x0f);\n if (token >= 0xa0 && token <= 0xbf) return this.#setPayload(token & 0x1f);\n\n switch (token) {\n case 0xc4: return this.#readLength('payload', 1);\n case 0xc5: return this.#readLength('payload', 2);\n case 0xc6: return this.#readLength('payload', 4);\n case 0xc7: return this.#readLength('extension', 1);\n case 0xc8: return this.#readLength('extension', 2);\n case 0xc9: return this.#readLength('extension', 4);\n case 0xca: return this.#setPayload(4);\n case 0xcb: return this.#setPayload(8);\n case 0xcc:\n case 0xd0: return this.#setPayload(1);\n case 0xcd:\n case 0xd1: return this.#setPayload(2);\n case 0xce:\n case 0xd2: return this.#setPayload(4);\n case 0xcf:\n case 0xd3: return this.#setPayload(8);\n case 0xd4: return this.#setExtensionPayload(1);\n case 0xd5: return this.#setExtensionPayload(2);\n case 0xd6: return this.#setExtensionPayload(4);\n case 0xd7: return this.#setExtensionPayload(8);\n case 0xd8: return this.#setExtensionPayload(16);\n case 0xd9: return this.#readLength('payload', 1);\n case 0xda: return this.#readLength('payload', 2);\n case 0xdb: return this.#readLength('payload', 4);\n case 0xdc: return this.#readLength('array', 2);\n case 0xdd: return this.#readLength('array', 4);\n case 0xde: return this.#readLength('map', 2);\n case 0xdf: return this.#readLength('map', 4);\n default: return this.#invalidInput();\n }\n }\n\n #completeIfReady(offset: number, boundaries: number[]): void {\n if (this.#pending || this.#payloadBytes > 0 || this.#remainingValues !== 0) return;\n this.#frames++;\n if (this.#frames > this.#maxFrames) {\n throw new Error(`[PipeX] Frame count exceeds ${this.#maxFrames}`);\n }\n boundaries.push(offset);\n this.#frameBytes = 0;\n this.#remainingValues = 1;\n this.#extensionTypePending = false;\n }\n\n #frameTooLarge(): never {\n throw new Error(`[PipeX] MessagePack frame exceeds ${this.#maxFrameBytes} bytes`);\n }\n\n #invalidInput(): never {\n throw new Error('[PipeX] Invalid MessagePack input');\n }\n}\n\nexport function assertMessagePackFrameLimits(\n input: Buffer | Uint8Array,\n maxFrameBytes: number,\n maxFrames = Number.MAX_SAFE_INTEGER,\n): number {\n const scanner = new MessagePackFrameScanner(maxFrameBytes, maxFrames);\n const boundaries = scanner.scan(Buffer.isBuffer(input)\n ? input\n : Buffer.from(input.buffer, input.byteOffset, input.byteLength));\n scanner.finish();\n return boundaries.length;\n}\n\nexport function buildFrameLimitTransform(maxFrameBytes: number, maxFrames: number): Transform {\n const scanner = new MessagePackFrameScanner(maxFrameBytes, maxFrames);\n let frameChunks: Buffer[] = [];\n let frameBytes = 0;\n\n return new Transform({\n transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {\n try {\n const input = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n const boundaries = scanner.scan(input);\n let start = 0;\n for (const boundary of boundaries) {\n const part = input.subarray(start, boundary);\n if (part.length > 0) {\n frameChunks.push(part);\n frameBytes += part.length;\n }\n this.push(frameChunks.length === 1 ? frameChunks[0] : Buffer.concat(frameChunks, frameBytes));\n frameChunks = [];\n frameBytes = 0;\n start = boundary;\n }\n if (start < input.length) {\n const part = input.subarray(start);\n frameChunks.push(part);\n frameBytes += part.length;\n }\n callback();\n } catch (error) {\n callback(error as Error);\n }\n },\n flush(callback: TransformCallback) {\n try {\n scanner.finish();\n callback();\n } catch (error) {\n callback(error as Error);\n }\n },\n });\n}\n","import { OperationAbortedError, OperationTimeoutError } from './errors.js';\n\nconst deadlines = new WeakMap<AbortSignal, number>();\n\nexport function registerDeadline(signal: AbortSignal, timeoutMs: number): void {\n if (timeoutMs > 0) deadlines.set(signal, Date.now() + timeoutMs);\n}\n\nfunction abortError(signal: AbortSignal): Error {\n if (signal.reason instanceof OperationTimeoutError || signal.reason instanceof OperationAbortedError) return signal.reason;\n if (signal.reason instanceof Error && signal.reason.name === 'TimeoutError') return new OperationTimeoutError();\n return new OperationAbortedError();\n}\n\nexport function throwIfAborted(signal?: AbortSignal): void {\n if (!signal) return;\n if (signal.aborted) throw abortError(signal);\n const deadline = deadlines.get(signal);\n // Synchronous work can keep the event loop from delivering its abort event.\n if (deadline !== undefined && Date.now() >= deadline) throw new OperationTimeoutError();\n}\n\n/** Stop waiting promptly, but account for non-cooperative work until it settles. */\nexport async function awaitOperation<T>(\n value: T | PromiseLike<T>,\n signal?: AbortSignal,\n track?: (pending: Promise<unknown>) => void,\n): Promise<T> {\n const promise = Promise.resolve(value);\n track?.(promise);\n if (!signal) return promise;\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const cleanup = () => {\n signal.removeEventListener('abort', onAbort);\n if (timer) clearTimeout(timer);\n };\n const fail = (error: unknown) => {\n if (settled) return;\n settled = true;\n cleanup();\n reject(error);\n };\n const onAbort = () => fail(abortError(signal));\n signal.addEventListener('abort', onAbort, { once: true });\n const deadline = deadlines.get(signal);\n if (deadline !== undefined) {\n // Referenced: a pending plugin promise may own no other event-loop handle.\n timer = setTimeout(() => fail(new OperationTimeoutError()), Math.max(0, deadline - Date.now()));\n }\n promise.then(result => {\n if (settled) return; // Late results are discarded, never forwarded or retried.\n try { throwIfAborted(signal); } catch (error) { fail(error); return; }\n settled = true;\n cleanup();\n resolve(result);\n }, fail);\n try { throwIfAborted(signal); } catch (error) { fail(error); }\n });\n}\n","import type { Logger, Span, Tracer, ProcessorContext } from './types.js';\n\n// Integrations may throw synchronously or return a rejected promise despite\n// their synchronous TypeScript contract. Neither may escape an observer.\nexport function observe(callback: () => unknown): void {\n try { void Promise.resolve(callback()).catch(() => undefined); } catch { /* observer isolation */ }\n}\n\nexport function safeLogger(logger: Logger | undefined): Logger | undefined {\n if (!logger) return undefined;\n return {\n info: (message, context) => observe(() => logger.info(message, context)),\n warn: (message, context) => observe(() => logger.warn(message, context)),\n error: (message, context) => observe(() => logger.error(message, context)),\n debug: (message, context) => observe(() => logger.debug(message, context)),\n };\n}\n\nexport function safeTracer(tracer: Tracer | undefined): Tracer | undefined {\n if (!tracer) return undefined;\n return {\n startSpan(name: string, context?: ProcessorContext): Span {\n let span: Span | undefined;\n try {\n const candidate = tracer.startSpan(name, context);\n if (candidate && typeof (candidate as unknown as { then?: unknown }).then === 'function') {\n observe(() => candidate);\n } else span = candidate;\n } catch { /* observer isolation */ }\n let ended = false;\n const wrapper: Span = {\n setAttribute(key, value) { observe(() => span?.setAttribute(key, value)); return wrapper; },\n addEvent(event, attributes) { observe(() => span?.addEvent(event, attributes)); return wrapper; },\n end() { if (!ended) { ended = true; observe(() => span?.end()); } },\n };\n return wrapper;\n },\n };\n}\n","/**\n * core.ts — stateless pipeline primitives\n *\n * No class, no EventEmitter, no file I/O.\n * Everything here is a pure function or a stream factory.\n * Controllers and the Engine import from here — never the other way around.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { pipeline } from 'node:stream/promises';\nimport { Readable, Writable, Transform, Duplex, type TransformCallback } from 'node:stream';\nimport { Packr, Unpackr, PackrStream, UnpackrStream } from 'msgpackr';\nimport { \n type ProcessorPlugin, \n type ProcessorContext, \n type PipeXManifest,\n type Logger,\n type Tracer,\n type Span,\n type RetryOptions,\n type EngineLimits,\n type StreamPluginContext,\n type PluginCapabilities,\n type PluginOperation,\n isManifest \n} from './types.js';\nimport {\n InvalidPluginCapabilityError,\n UnsupportedReverseError,\n UnsupportedStreamingError,\n} from './errors.js';\nimport { BasePlugin } from './plugin.js';\nimport { DEFAULT_LIMITS } from './resourceLimits.js';\nimport { assertMessagePackFrameLimits } from './frameLimits.js';\nimport { awaitOperation, throwIfAborted } from './operations.js';\nimport { safeLogger, safeTracer } from './observability.js';\n\nexport { assertMessagePackFrameLimits, buildFrameLimitTransform } from './frameLimits.js';\nexport { DEFAULT_LIMITS } from './resourceLimits.js';\n\nexport { isManifest };\n\n// ─── Resilience Helpers ───────────────────────────────────────────────────────\n\n/**\n * Executes a function with automatic retries and backoff.\n */\nexport async function withRetry<T>(\n fn: () => Promise<T> | T,\n options?: RetryOptions,\n logger?: Logger,\n control?: { signal?: AbortSignal; limits?: Pick<EngineLimits, 'maxRetryAttempts' | 'maxRetryDelayMs'>; track?: (pending: Promise<unknown>) => void },\n): Promise<T> {\n logger = safeLogger(logger);\n const { attempts = 1, backoff = 'fixed', delayMs = 0 } = options ?? {};\n const maxAttempts = control?.limits?.maxRetryAttempts ?? 5;\n const maxDelay = control?.limits?.maxRetryDelayMs ?? 30_000;\n if (!Number.isSafeInteger(attempts) || attempts < 1 || attempts > maxAttempts) {\n throw new Error(`[PipeX] Invalid retry attempts: ${attempts}`);\n }\n if (!Number.isSafeInteger(delayMs) || delayMs < 0 || delayMs > maxDelay) {\n throw new Error(`[PipeX] Invalid retry delay: ${delayMs}`);\n }\n let lastError: Error | undefined;\n\n for (let i = 0; i < attempts; i++) {\n throwIfAborted(control?.signal);\n try {\n return await awaitOperation(fn(), control?.signal, control?.track);\n } catch (err: unknown) {\n throwIfAborted(control?.signal);\n lastError = err instanceof Error ? err : new Error(String(err));\n if (i < attempts - 1) {\n const nextDelay = backoff === 'exponential' ? delayMs * Math.pow(2, i) : delayMs;\n logger?.debug(`[PipeX] Retry ${i + 1}/${attempts} after ${nextDelay}ms`, { error: lastError.message });\n if (nextDelay > 0) {\n await new Promise<void>((resolve, reject) => {\n const cleanup = () => control?.signal?.removeEventListener('abort', onAbort);\n const timer = setTimeout(() => { cleanup(); resolve(); }, Math.min(nextDelay, maxDelay));\n const onAbort = () => {\n clearTimeout(timer);\n cleanup();\n reject(control?.signal?.reason ?? new Error('[PipeX] Operation aborted'));\n };\n control?.signal?.addEventListener('abort', onAbort, { once: true });\n if (control?.signal?.aborted) onAbort();\n });\n }\n }\n }\n }\n\n throw lastError;\n}\n\n// Sentinel key constant — single source of truth, importable by controllers\nexport const PIPEX_MANIFEST_KEY = '__pipex_v' as const;\n\n// ─── Singletons ───────────────────────────────────────────────────────────────\nexport const PACKR = new Packr({ useRecords: false, moreTypes: true, structuredClone: false, bundleStrings: false });\nexport const UNPACKR = new Unpackr({ useRecords: false, structuredClone: false });\n\n/** @deprecated Use `DEFAULT_LIMITS.maxFrameBytes` or an engine-specific limit. */\nexport const MAX_FRAME_BYTES = 256 * 1024 * 1024;\nexport const DEFAULT_HIGH_WATER = 64 * 1024;\n// ─── Type helpers ─────────────────────────────────────────────────────────────\n\ntype PluginWithStream = ProcessorPlugin & {\n createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex;\n};\n\nexport function hasStreamSupport(p: ProcessorPlugin): p is PluginWithStream {\n return typeof p['createStream'] === 'function';\n}\n\n/**\n * Returns the effective capabilities of a plugin after validating declarations.\n * Explicit `false` declarations are authoritative, which supports plugins whose\n * implementation is present but disabled by configuration (for example workers).\n */\nexport function getPluginCapabilities(plugin: ProcessorPlugin): Readonly<PluginCapabilities> {\n const pluginId = `${plugin.name}@${plugin.version}`;\n const reversible = plugin.reversible;\n const streaming = plugin.streaming;\n const reverseImplementation = plugin.reverse;\n const streamImplementation = plugin.createStream;\n const hasReverseImplementation = typeof reverseImplementation === 'function'\n && reverseImplementation !== BasePlugin.prototype.reverse;\n\n if (reversible !== undefined && typeof reversible !== 'boolean') {\n throw new InvalidPluginCapabilityError(pluginId, 'reversible', 'MUST_BE_BOOLEAN');\n }\n if (streaming !== undefined && typeof streaming !== 'boolean') {\n throw new InvalidPluginCapabilityError(pluginId, 'streaming', 'MUST_BE_BOOLEAN');\n }\n if (reversible === true && !hasReverseImplementation) {\n throw new InvalidPluginCapabilityError(pluginId, 'reversible', 'MISSING_IMPLEMENTATION');\n }\n if (streaming === false && typeof streamImplementation === 'function') {\n throw new InvalidPluginCapabilityError(pluginId, 'streaming', 'CONFLICTING_IMPLEMENTATION');\n }\n\n const canReverse = reversible !== false && hasReverseImplementation;\n const canStream = streaming !== false;\n return Object.freeze({\n process: true,\n reverse: canReverse,\n streaming: canStream,\n streamMode: canStream\n ? (typeof streamImplementation === 'function' ? 'native' : 'fallback')\n : 'none',\n });\n}\n\n/** Query an operation without attempting to execute it. Invalid declarations fail closed. */\nexport function supportsOperation(plugin: ProcessorPlugin, operation: PluginOperation): boolean {\n const capabilities = getPluginCapabilities(plugin);\n switch (operation) {\n case 'process': return capabilities.process;\n case 'reverse': return capabilities.reverse;\n case 'stream': return capabilities.streaming;\n default: throw new TypeError('[PipeX] Unknown plugin operation');\n }\n}\n\nexport function supportsReverse(plugin: ProcessorPlugin): plugin is ProcessorPlugin & Required<Pick<ProcessorPlugin, 'reverse'>> {\n return supportsOperation(plugin, 'reverse');\n}\n\nexport function assertReversiblePipeline(plugins: readonly ProcessorPlugin[]): void {\n const unsupported = plugins.find(plugin => !supportsReverse(plugin));\n if (unsupported) throw new UnsupportedReverseError(`${unsupported.name}@${unsupported.version}`);\n}\n\nexport function assertStreamingPipeline(plugins: readonly ProcessorPlugin[]): void {\n const unsupported = plugins.find(plugin => !supportsOperation(plugin, 'stream'));\n if (unsupported) throw new UnsupportedStreamingError(`${unsupported.name}@${unsupported.version}`);\n}\n\n// ─── Buffer helpers ───────────────────────────────────────────────────────────\n\nexport function detectType(input: unknown): string {\n if (input === null) return 'null';\n if (Buffer.isBuffer(input)) return 'buffer';\n if (Array.isArray(input)) return 'array';\n if (typeof input === 'object') return 'object';\n return typeof input;\n}\n\nexport function toBuffer(input: unknown): Buffer {\n if (Buffer.isBuffer(input)) return input;\n if (input instanceof ArrayBuffer) return Buffer.from(input);\n if (typeof input === 'object' && input !== null) return PACKR.pack(input);\n if (typeof input === 'number' || typeof input === 'boolean') return Buffer.from(String(input));\n return Buffer.from(String(input ?? ''), 'utf-8');\n}\n\nexport const ORIGINAL_TYPES = Object.freeze([\n 'buffer', 'object', 'array', 'string', 'number', 'boolean', 'null', 'undefined', 'bigint', 'json',\n] as const);\n\nexport function assertOriginalType(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !(ORIGINAL_TYPES as readonly string[]).includes(value)) {\n throw new Error('[PipeX] Unsupported original type');\n }\n}\n\nexport function fromBuffer(\n buffer: Buffer,\n targetType: string,\n maxFrameBytes = DEFAULT_LIMITS.maxFrameBytes,\n): unknown {\n assertOriginalType(targetType);\n if (!Buffer.isBuffer(buffer)) throw new Error('[PipeX] Invalid binary payload');\n switch (targetType) {\n case 'array':\n case 'object': {\n assertMessagePackFrameLimits(buffer, maxFrameBytes, 1);\n let decoded: unknown;\n try { decoded = UNPACKR.unpack(buffer); }\n catch { throw new Error('[PipeX] fromBuffer: invalid MessagePack input'); }\n if (targetType === 'array' ? !Array.isArray(decoded) : decoded === null || typeof decoded !== 'object' || Array.isArray(decoded)) {\n throw new Error('[PipeX] Decoded value does not match the expected type');\n }\n return decoded;\n }\n case 'json': {\n try { return JSON.parse(buffer.toString('utf-8')); }\n catch { throw new Error('[PipeX] fromBuffer: invalid JSON input'); }\n }\n case 'number': {\n const n = Number(buffer.toString('utf-8'));\n if (Number.isNaN(n)) throw new Error('[PipeX] fromBuffer: invalid number');\n return n;\n }\n case 'bigint': {\n try { return BigInt(buffer.toString('utf-8')); }\n catch { throw new Error('[PipeX] fromBuffer: invalid bigint'); }\n }\n case 'boolean': {\n const value = buffer.toString('utf-8');\n if (value !== 'true' && value !== 'false') throw new Error('[PipeX] fromBuffer: invalid boolean');\n return value === 'true';\n }\n case 'string': return buffer.toString('utf-8');\n case 'null':\n case 'undefined':\n if (buffer.length !== 0) throw new Error('[PipeX] Payload does not match the expected empty type');\n return targetType === 'null' ? null : undefined;\n default: return buffer;\n }\n}\n// ─── Context factory ──────────────────────────────────────────────────────────\n\nexport function makeContext(\n requestId: string,\n extra: Record<string, unknown> = {},\n logger?: Logger,\n span?: Span,\n signal?: AbortSignal,\n limits?: Readonly<EngineLimits>,\n): ProcessorContext {\n return { requestId, timestamp: Date.now(), metadata: extra, logger, span, signal, limits };\n}\n\n// ─── Manifest ─────────────────────────────────────────────────────────────────\n\nexport function buildManifest(plugins: readonly ProcessorPlugin[]): PipeXManifest {\n return {\n __pipex_v: 1,\n plugins: plugins.map(p => `${p.name}@${p.version}`),\n ts: Date.now(),\n };\n}\n\n/**\n * A passthrough Transform that prepends a single msgpack-encoded manifest frame\n * to the byte stream before forwarding any data chunks.\n * Inserted between PackrStream output and the file destination.\n */\nexport function buildManifestHeaderTransform(manifest: PipeXManifest): Transform {\n let sent = false;\n const frame = Buffer.from(PACKR.pack(manifest));\n\n return new Transform({\n transform(chunk: Buffer, _enc: BufferEncoding, cb: TransformCallback) {\n if (!sent) {\n sent = true;\n this.push(frame);\n }\n cb(null, chunk);\n },\n flush(cb: TransformCallback) {\n if (!sent) this.push(frame);\n cb();\n },\n });\n}\n\n/**\n * Object-mode Transform that sits after UnpackrStream.\n * Intercepts the first decoded frame: if it is a PipeXManifest, captures it\n * via onManifest() and drops it from the output; all other frames pass through.\n */\nexport function buildManifestExtractTransform(\n onManifest: (m: PipeXManifest) => void,\n): Transform {\n let seen = false;\n return new Transform({\n writableObjectMode: true,\n readableObjectMode: true,\n transform(frame: unknown, _enc: BufferEncoding, cb: TransformCallback) {\n if (!seen) {\n seen = true;\n if (isManifest(frame)) {\n try { onManifest(frame); cb(); } catch (error) { cb(error as Error); }\n return;\n }\n }\n cb(null, frame);\n },\n });\n}\n\n// ─── Stream factories ─────────────────────────────────────────────────────────\n\n/** DoS-safe UnpackrStream subclass — rejects oversized raw chunks before decode. */\nexport class GuardedUnpackrStream extends UnpackrStream {\n #receivedBytes = 0;\n readonly #maxInputBytes: number;\n\n constructor(options: Record<string, unknown> = {}, maxInputBytes = DEFAULT_LIMITS.maxInputBytes) {\n super(options);\n this.#maxInputBytes = maxInputBytes;\n }\n\n override _transform(chunk: Buffer, enc: BufferEncoding, cb: TransformCallback): void {\n if (chunk.length > this.#maxInputBytes - this.#receivedBytes) {\n cb(new Error(`[PipeX] Serialized input exceeds ${this.#maxInputBytes} bytes`));\n return;\n }\n this.#receivedBytes += chunk.length;\n super._transform(chunk, enc, error => {\n cb(error ? new Error('[PipeX] Invalid MessagePack input') : undefined);\n });\n }\n}\n\n/** PackrStream with useRecords disabled (safe default). */\nexport function createPackrStream(): PackrStream {\n return new PackrStream({ useRecords: false, moreTypes: true, structuredClone: false, bundleStrings: false });\n}\n\n/** GuardedUnpackrStream with useRecords disabled. */\nexport function createUnpackrStream(maxInputBytes = DEFAULT_LIMITS.maxInputBytes): GuardedUnpackrStream {\n return new GuardedUnpackrStream({ useRecords: false, structuredClone: false }, maxInputBytes);\n}\n\nexport function buildByteLimitTransform(maxBytes: number, label: string): Transform {\n let total = 0;\n return new Transform({\n transform(chunk: Buffer, _enc: BufferEncoding, cb: TransformCallback) {\n if (chunk.length > maxBytes - total) {\n cb(new Error(`[PipeX] ${label} exceeds ${maxBytes} bytes`));\n return;\n }\n total += chunk.length;\n cb(null, chunk);\n },\n });\n}\n\nexport function buildObjectLimitTransform(maxFrames: number): Transform {\n let count = 0;\n return new Transform({\n writableObjectMode: true,\n readableObjectMode: true,\n transform(value: unknown, _enc: BufferEncoding, cb: TransformCallback) {\n if (count >= maxFrames) {\n cb(new Error(`[PipeX] Application frame count exceeds ${maxFrames}`));\n return;\n }\n count++;\n cb(null, value);\n },\n });\n}\n\n/** Rejects known byte-backed values before MessagePack copies their payload. */\nexport function assertKnownValueByteLimit(value: unknown, maxBytes: number, label: string): void {\n const byteLength = typeof value === 'string'\n ? Buffer.byteLength(value)\n : Buffer.isBuffer(value) || ArrayBuffer.isView(value)\n ? value.byteLength\n : value instanceof ArrayBuffer\n ? value.byteLength\n : undefined;\n if (byteLength !== undefined && byteLength > maxBytes) {\n throw new Error(`[PipeX] ${label} exceeds ${maxBytes} bytes`);\n }\n}\n\nexport function buildKnownValueByteLimitTransform(maxBytes: number, label: string): Transform {\n return new Transform({\n writableObjectMode: true,\n readableObjectMode: true,\n transform(value: unknown, _encoding: BufferEncoding, callback: TransformCallback) {\n try {\n assertKnownValueByteLimit(value, maxBytes, label);\n callback(null, value);\n } catch (error) {\n callback(error as Error);\n }\n },\n });\n}\n\n/**\n * Wraps a plugin's process/reverse call in a Transform.\n * requestId is fixed per stream instance — not per chunk — to avoid\n * 60× randomUUID() overhead on high-throughput paths.\n */\nexport function buildFallbackTransform(\n plugin: ProcessorPlugin,\n reverse: boolean,\n emitProgress?: (bytes: number) => void,\n logger?: Logger,\n tracer?: Tracer,\n dlq?: Writable,\n streamContext?: StreamPluginContext,\n): Transform {\n logger = safeLogger(logger);\n tracer = safeTracer(tracer);\n const requestId = streamContext?.requestId ?? `stream-${randomUUID()}`;\n return new Transform({\n async transform(chunk: Buffer, _enc: BufferEncoding, cb: TransformCallback) {\n const span = tracer?.startSpan(`plugin:${plugin.name}`, { requestId } as any);\n span?.setAttribute('plugin.version', plugin.version);\n span?.setAttribute('mode', reverse ? 'reverse' : 'process');\n\n try {\n streamContext?.signal.throwIfAborted();\n const ctx = makeContext(requestId, {}, logger, span, streamContext?.signal, streamContext?.limits);\n if (reverse && !supportsReverse(plugin)) {\n throw new UnsupportedReverseError(`${plugin.name}@${plugin.version}`);\n }\n const fn = reverse ? plugin.reverse!.bind(plugin) : plugin.process.bind(plugin);\n \n const out = await withRetry(\n () => fn(chunk, ctx),\n plugin.retryOptions,\n logger,\n { signal: streamContext?.signal, limits: streamContext?.limits, track: streamContext?.track },\n );\n const maxOutputBytes = streamContext?.limits.maxOutputBytes ?? DEFAULT_LIMITS.maxOutputBytes;\n if (!Buffer.isBuffer(out) || out.length > maxOutputBytes) {\n throw new Error(`[PipeX] Plugin output exceeds ${maxOutputBytes} bytes`);\n }\n emitProgress?.(out.length);\n span?.addEvent('processed', { bytes: out.length });\n cb(null, out);\n } catch (err: unknown) {\n const error = err instanceof Error ? err : new Error(String(err));\n logger?.error(`[PipeX] Plugin ${plugin.name} failed after retries`, { requestId, error: error.message });\n span?.setAttribute('error', true);\n span?.addEvent('error', { message: error.message });\n\n if (dlq && dlq.writable) {\n logger?.warn(`[PipeX] Diverting failed chunk to DLQ`, { requestId, plugin: plugin.name });\n try {\n if (!dlq.write(chunk)) await new Promise<void>((resolve, reject) => {\n const onDrain = () => { cleanup(); resolve(); };\n const onError = (writeError: Error) => { cleanup(); reject(writeError); };\n const onAbort = () => {\n cleanup();\n reject(streamContext?.signal.reason instanceof Error\n ? streamContext.signal.reason\n : new Error('[PipeX] Operation aborted'));\n };\n const onClose = () => { cleanup(); reject(new Error('[PipeX] Stream closed while writing to DLQ')); };\n const cleanup = () => {\n dlq.off('drain', onDrain);\n dlq.off('error', onError);\n streamContext?.signal.removeEventListener('abort', onAbort);\n this.off('close', onClose);\n };\n dlq.once('drain', onDrain);\n dlq.once('error', onError);\n this.once('close', onClose);\n if (streamContext?.signal.aborted) onAbort();\n else streamContext?.signal.addEventListener('abort', onAbort, { once: true });\n });\n cb(error);\n } catch (dlqError) {\n cb(dlqError as Error);\n }\n } else {\n cb(error);\n }\n } finally {\n span?.end();\n }\n },\n });\n}\n\n/** Serialises JS objects to NDJSON lines. */\nexport function buildNdjsonTransform(): Transform {\n return new Transform({\n writableObjectMode: true,\n readableObjectMode: false,\n transform(chunk: unknown, _enc: BufferEncoding, cb: TransformCallback) {\n try { cb(null, JSON.stringify(chunk) + '\\n'); }\n catch (e: unknown) {\n cb(new Error(`[PipeX] NDJSON: ${(e as Error).message}`));\n }\n },\n });\n}\n\n/**\n * Builds the ordered Transform chain from a plugin list.\n * Uses native createStream() when available; falls back to buildFallbackTransform.\n */\nexport function buildTransformChain(\n plugins: readonly ProcessorPlugin[],\n mode: 'compress' | 'decompress',\n reverse = false,\n onProgress?: (bytes: number) => void,\n logger?: Logger,\n tracer?: Tracer,\n dlq?: Writable,\n streamContext?: StreamPluginContext,\n): (Duplex | Transform | PackrStream | GuardedUnpackrStream)[] {\n logger = safeLogger(logger);\n tracer = safeTracer(tracer);\n assertStreamingPipeline(plugins);\n if (reverse) assertReversiblePipeline(plugins);\n const ordered = reverse ? [...plugins].reverse() : plugins;\n return ordered.flatMap((plugin, index) => {\n const transform = hasStreamSupport(plugin)\n ? plugin.createStream(mode, streamContext)\n : buildFallbackTransform(plugin, reverse, onProgress, logger, tracer, dlq, streamContext);\n const limit = buildByteLimitTransform(\n streamContext?.limits.maxOutputBytes ?? DEFAULT_LIMITS.maxOutputBytes,\n `output after plugin ${plugin.name}#${index}`,\n );\n if (!hasStreamSupport(plugin)) return [transform, limit];\n\n const span = tracer?.startSpan(`plugin:${plugin.name}`, { requestId: streamContext?.requestId ?? 'stream' } as ProcessorContext);\n let spanEnded = false;\n const endSpan = (error?: Error | null) => {\n if (spanEnded) return;\n spanEnded = true;\n if (error) span?.setAttribute('error', true);\n span?.end();\n };\n const observe = new Transform({\n transform(chunk: Buffer, _enc: BufferEncoding, cb: TransformCallback) {\n onProgress?.(chunk.length);\n span?.addEvent('processed', { bytes: chunk.length });\n cb(null, chunk);\n },\n final(cb) {\n endSpan();\n cb();\n },\n destroy(error, cb) {\n endSpan(error);\n cb(error);\n },\n });\n return [transform, observe, limit];\n });\n}\n\n// ─── Central pipeline runner ──────────────────────────────────────────────────\n\n/**\n * Runs an arbitrary pipeline: Source → [...Transforms] → Destination.\n * The `any` cast is scoped to this single call site — nowhere else.\n */\nexport async function runPipeline(\n source: Readable,\n transforms: (Duplex | Transform | PackrStream | GuardedUnpackrStream)[],\n destination: Writable,\n options?: { signal?: AbortSignal },\n): Promise<void> {\n await (pipeline as (...args: unknown[]) => Promise<void>)(\n source, ...transforms, destination, options ?? {}\n );\n}\n\n// ─── Path safety ──────────────────────────────────────────────────────────────\n\nimport path from 'node:path';\nimport { existsSync, realpathSync } from 'node:fs';\n\nfunction assertWithinRoot(target: string, allowedRoot: string): void {\n const relative = path.relative(allowedRoot, target);\n if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {\n throw new Error('[PipeX] Path is outside the allowed root');\n }\n}\n\nexport function assertExists(inputPath: string, allowedRoot?: string): string {\n const abs = path.resolve(inputPath);\n if (!existsSync(abs)) throw new Error(`[PipeX] File not found: ${abs}`);\n const root = realpathSync.native(path.resolve(allowedRoot ?? process.cwd()));\n const canonical = realpathSync.native(abs);\n assertWithinRoot(canonical, root);\n return canonical;\n}\n\nexport function resolveOutputPath(outputPath: string, allowedRoot?: string): string {\n const root = realpathSync.native(path.resolve(allowedRoot ?? process.cwd()));\n const absolute = path.resolve(outputPath);\n const parent = realpathSync.native(path.dirname(absolute));\n assertWithinRoot(parent, root);\n const candidate = path.join(parent, path.basename(absolute));\n if (existsSync(candidate)) {\n assertWithinRoot(realpathSync.native(candidate), root);\n }\n return candidate;\n}\n","import { constants, openSync, closeSync, fstatSync, realpathSync } from 'node:fs';\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport { Readable, Writable } from 'node:stream';\nimport { createRequire } from 'node:module';\nimport type * as Koffi from 'koffi';\n\nlet ffi: typeof Koffi | undefined;\nconst native = (): typeof Koffi => ffi ??= createRequire(import.meta.url)('koffi') as typeof Koffi;\nimport { assertExists, resolveOutputPath, DEFAULT_HIGH_WATER } from './core.js';\n\nexport interface AtomicFileSession {\n readonly source: Readable;\n readonly destination: Writable;\n commit(): void;\n dispose(): Promise<void>;\n}\n\nconst fail = (operation: string): never => { throw new Error('[PipeX] Secure file ' + operation + ' failed'); };\nconst components = (absolute: string): string[] => {\n const base = path.parse(absolute).root;\n return absolute.slice(base.length).split(path.sep).filter(Boolean);\n};\n\n/** Acquire capabilities before invoking any plugin or beginning asynchronous I/O. */\nexport function openAtomicFileSession(inputPath: string, outputPath: string, allowedRoot?: string): AtomicFileSession {\n const root = realpathSync.native(path.resolve(allowedRoot ?? process.cwd()));\n const input = assertExists(inputPath, root);\n const output = resolveOutputPath(outputPath, root);\n if (input === output) throw new Error('[PipeX] Input and output must be different files');\n return process.platform === 'win32' ? openWindows(input, output, root) : openPosix(input, output);\n}\n\nlet windows: ReturnType<typeof loadWindows> | undefined;\nfunction loadWindows() {\n const koffi = native();\n const lib = koffi.load('kernel32.dll');\n const ntdll = koffi.load('ntdll.dll');\n const unicode = koffi.struct({ Length: 'uint16_t', MaximumLength: 'uint16_t', Buffer: 'str16' });\n const attributes = koffi.struct({ Length: 'uint32_t', RootDirectory: 'intptr_t', ObjectName: koffi.pointer(unicode), Attributes: 'uint32_t', SecurityDescriptor: 'void *', SecurityQualityOfService: 'void *' });\n const status = koffi.struct({ Status: 'intptr_t', Information: 'uintptr_t' });\n return {\n setRelativeInfo: ntdll.func('__stdcall', 'NtSetInformationFile', 'int32_t', ['intptr_t', koffi.out(koffi.pointer(status)), 'void *', 'uint32_t', 'int']),\n relativeOpen: ntdll.func('__stdcall', 'NtCreateFile', 'int32_t', ['_Out_ intptr_t *', 'uint32_t', koffi.pointer(attributes), koffi.out(koffi.pointer(status)), 'void *', 'uint32_t', 'uint32_t', 'uint32_t', 'uint32_t', 'void *', 'uint32_t']),\n attributesSize: koffi.sizeof(attributes),\n pointerBytes: koffi.sizeof('void *'),\n finalPath: lib.func('__stdcall', 'GetFinalPathNameByHandleW', 'uint32_t', ['intptr_t', '_Out_ void *', 'uint32_t', 'uint32_t']),\n open: lib.func('__stdcall', 'CreateFileW', 'intptr_t', ['str16', 'uint32_t', 'uint32_t', 'void *', 'uint32_t', 'uint32_t', 'void *']),\n info: lib.func('__stdcall', 'GetFileInformationByHandle', 'int', ['intptr_t', '_Out_ void *']),\n type: lib.func('__stdcall', 'GetFileType', 'uint32_t', ['intptr_t']),\n read: lib.func('__stdcall', 'ReadFile', 'int', ['intptr_t', '_Out_ void *', 'uint32_t', '_Out_ uint32_t *', 'void *']),\n write: lib.func('__stdcall', 'WriteFile', 'int', ['intptr_t', 'void *', 'uint32_t', '_Out_ uint32_t *', 'void *']),\n setInfo: lib.func('__stdcall', 'SetFileInformationByHandle', 'int', ['intptr_t', 'int', 'void *', 'uint32_t']),\n close: lib.func('__stdcall', 'CloseHandle', 'int', ['intptr_t']),\n };\n}\n\nfunction openWindows(input: string, output: string, root: string): AtomicFileSession {\n const api = windows ??= loadWindows();\n const handles: (number | bigint)[] = [];\n const directories = new Map<string, number | bigint>();\n const pending = new Set<Promise<unknown>>();\n let committed = false;\n let disposed = false;\n let inputHandle: number | bigint;\n let outputHandle: number | bigint | undefined;\n const information = (handle: number | bigint): Buffer => {\n const buffer = Buffer.alloc(52); // BY_HANDLE_FILE_INFORMATION, fixed Win32 layout\n if (!api.info(handle, buffer)) fail('handle inspection');\n return buffer;\n };\n const acquire = (name: string, access: number, share: number, disposition: number, directory: boolean): number | bigint => {\n // OPEN_REPARSE_POINT prevents following a last-component junction/symlink.\n const handle = api.open(name, access, share, null, disposition, 0x00200000 | (directory ? 0x02000000 : 0x80), null) as number | bigint;\n if (BigInt(handle) === -1n) fail('open');\n handles.push(handle);\n const attributes = information(handle).readUInt32LE(0);\n if ((attributes & 0x400) || Boolean(attributes & 0x10) !== directory || api.type(handle) !== 1) fail('file type validation');\n return handle;\n };\n const relativeOpen = (parent: number | bigint, name: string, access: number, create: boolean, directory: boolean, optional = false): number | bigint | undefined => {\n if (!name || name === '.' || name === '..' || /[\\\\/:]/.test(name)) fail('relative name validation');\n const opened: (number | bigint)[] = [0];\n const result = api.relativeOpen(opened, (access | 0x100000) >>> 0, {\n Length: api.attributesSize, RootDirectory: parent,\n ObjectName: { Length: Buffer.byteLength(name, 'utf16le'), MaximumLength: Buffer.byteLength(name, 'utf16le') + 2, Buffer: name },\n Attributes: 0x40, SecurityDescriptor: null, SecurityQualityOfService: null,\n }, {}, null, 0x80, directory ? 3 : 1, create ? 2 : 1, 0x200020 | (directory ? 1 : 0x40), null, 0) as number;\n if (result < 0) {\n if (optional && (result >>> 0) === 0xc0000034) return undefined;\n fail('relative open');\n }\n const handle = opened[0]!;\n handles.push(handle);\n if (create) outputHandle = handle;\n const flags = information(handle).readUInt32LE(0);\n if ((flags & 0x400) || Boolean(flags & 0x10) !== directory || api.type(handle) !== 1) fail('relative type validation');\n return handle;\n };\n const openParent = (filename: string, rootHandle: number | bigint): number | bigint => {\n let current = '';\n let handle = rootHandle;\n for (const part of components(path.relative(root, path.dirname(filename)))) {\n current = path.join(current, part);\n const existing = directories.get(current.toLowerCase());\n if (existing !== undefined) handle = existing;\n else {\n handle = relativeOpen(handle, part, 0x80000000, false, true)!;\n directories.set(current.toLowerCase(), handle);\n }\n }\n return handle;\n };\n let outputParent: number | bigint;\n const closeAll = () => { for (const handle of handles.reverse()) api.close(handle); handles.length = 0; };\n try {\n const rootHandle = acquire(root, 0x80000000, 3, 3, true);\n // Verify the object actually opened, including any ancestor reparse points.\n // All subsequent lookup is relative to this capability, never to root's path.\n const rootName = Buffer.alloc(65536);\n const chars = api.finalPath(rootHandle, rootName, rootName.length / 2, 0) as number;\n if (!chars || chars >= rootName.length / 2) fail('root identity validation');\n const stripPrefix = (name: string) => name.startsWith('\\\\\\\\?\\\\UNC\\\\') ? '\\\\\\\\' + name.slice(8) : name.startsWith('\\\\\\\\?\\\\') ? name.slice(4) : name;\n if (path.normalize(stripPrefix(rootName.subarray(0, chars * 2).toString('utf16le'))).toLowerCase() !== path.normalize(root).toLowerCase()) fail('root identity validation');\n const inputParent = openParent(input, rootHandle);\n outputParent = openParent(output, rootHandle);\n inputHandle = relativeOpen(inputParent, path.basename(input), 0x80000000, false, false)!;\n // Compare file identities as well as names, including hard-link aliases.\n const other = relativeOpen(outputParent, path.basename(output), 0x80000000, false, false, true);\n if (other !== undefined) {\n try {\n const a = information(inputHandle);\n const b = information(other);\n if (a.readUInt32LE(28) === b.readUInt32LE(28) && a.subarray(44, 52).equals(b.subarray(44, 52))) {\n throw new Error('[PipeX] Input and output must be different files');\n }\n if (b.readUInt32LE(0) & 0x400) fail('output reparse validation');\n } finally { api.close(other); handles.pop(); }\n }\n const temporary = '.pipex-' + randomUUID() + '.tmp';\n // DELETE access permits rename/disposal through this exact handle. No\n // WRITE/DELETE sharing means another process cannot replace the temp file.\n outputHandle = relativeOpen(outputParent, temporary, 0x40010080, true, false)!;\n } catch (error) {\n if (outputHandle !== undefined) api.setInfo(outputHandle, 4, Buffer.from([1]), 1);\n closeAll();\n throw error;\n }\n\n const io = (write: boolean, buffer: Buffer): Promise<number> => {\n const count = [0];\n const task = new Promise<number>((resolve, reject) => {\n const fn = write ? api.write : api.read;\n fn.async(write ? outputHandle : inputHandle, buffer, buffer.length, count, null, (error: unknown, ok: number) => {\n if (error || !ok) reject(new Error('[PipeX] Secure file ' + (write ? 'write' : 'read') + ' failed'));\n else resolve(count[0]!);\n });\n });\n pending.add(task);\n void task.then(() => pending.delete(task), () => pending.delete(task));\n return task;\n };\n let reading = false;\n const source = new Readable({\n highWaterMark: DEFAULT_HIGH_WATER,\n read() {\n if (reading) return;\n reading = true;\n const buffer = Buffer.allocUnsafe(DEFAULT_HIGH_WATER);\n void io(false, buffer).then(count => {\n reading = false;\n if (!this.destroyed) this.push(count ? buffer.subarray(0, count) : null);\n }, error => { reading = false; this.destroy(error as Error); });\n },\n });\n const destination = new Writable({\n highWaterMark: DEFAULT_HIGH_WATER,\n write(chunk: Buffer, _encoding, callback) {\n const work = (async () => {\n let offset = 0;\n while (offset < chunk.length) {\n if (disposed) fail('write after disposal');\n const count = await io(true, chunk.subarray(offset));\n if (!count) fail('write progress');\n offset += count;\n }\n })();\n pending.add(work);\n void work.then(() => { pending.delete(work); callback(); }, error => { pending.delete(work); callback(error as Error); });\n },\n });\n return {\n source, destination,\n commit() {\n if (disposed || committed) fail('commit state');\n // FILE_RENAME_INFO: offsets depend on HANDLE width, not filename length.\n const pointerBytes = api.pointerBytes;\n const rootOffset = pointerBytes === 8 ? 8 : 4;\n const lengthOffset = rootOffset + pointerBytes;\n const nameOffset = lengthOffset + 4;\n const name = Buffer.from(path.basename(output) + '\\0', 'utf16le');\n const info = Buffer.alloc(nameOffset + name.length);\n info[0] = 1; // ReplaceIfExists, relative to the pinned output directory.\n if (pointerBytes === 8) info.writeBigUInt64LE(BigInt(outputParent), rootOffset);\n else info.writeUInt32LE(Number(outputParent), rootOffset);\n info.writeUInt32LE(name.length - 2, lengthOffset);\n name.copy(info, nameOffset);\n const status = api.setRelativeInfo(outputHandle, {}, info, info.length, 10) as number;\n if (status < 0) fail('atomic rename status ' + (status >>> 0).toString(16));\n committed = true;\n },\n async dispose() {\n if (disposed) return;\n disposed = true;\n source.destroy();\n destination.destroy();\n await Promise.allSettled([...pending]);\n if (!committed) {\n // FILE_DISPOSITION_INFO deletes the opened temp object, never a path\n // that could have been exchanged by another process.\n api.setInfo(outputHandle, 4, Buffer.from([1]), 1);\n }\n closeAll();\n },\n };\n}\n\nlet posix: ReturnType<typeof loadPosix> | undefined;\nfunction loadPosix() {\n const lib = native().load(null);\n return {\n read: lib.func('intptr_t read(int fd, _Out_ void *buffer, size_t count)'),\n write: lib.func('intptr_t write(int fd, const void *buffer, size_t count)'),\n fcntl: lib.func('int fcntl(int fd, int command, int argument)'),\n openat: lib.func('int openat(int dirfd, const char *path, int flags, unsigned int mode)'),\n mkdirat: lib.func('int mkdirat(int dirfd, const char *path, unsigned int mode)'),\n renameat: lib.func('int renameat(int oldfd, const char *oldname, int newfd, const char *newname)'),\n unlinkat: lib.func('int unlinkat(int dirfd, const char *path, int flags)'),\n };\n}\n\nfunction openPosix(input: string, output: string): AtomicFileSession {\n const api = posix ??= loadPosix();\n const descriptors: number[] = [];\n const nofollow = constants.O_NOFOLLOW;\n const directory = constants.O_DIRECTORY;\n if (!nofollow || !directory) fail('platform support');\n const closeAll = () => { for (const fd of descriptors.reverse()) { try { closeSync(fd); } catch {} } descriptors.length = 0; };\n const openChild = (parent: number, name: string, flags: number, mode = 0): number => {\n const fd = api.openat(parent, name, flags | nofollow, mode) as number;\n if (fd < 0) fail('relative open');\n descriptors.push(fd);\n if (api.fcntl(fd, 2, 1) < 0) fail('descriptor inheritance protection');\n return fd;\n };\n const openParent = (filename: string): number => {\n let fd = openSync(path.parse(filename).root, constants.O_RDONLY | directory);\n descriptors.push(fd);\n for (const part of components(path.dirname(filename))) fd = openChild(fd, part, constants.O_RDONLY | directory);\n return fd;\n };\n const temporary = '.pipex-' + randomUUID();\n let outputParent: number | undefined;\n let temporaryParent: number | undefined;\n let inputFD: number;\n let outputFD: number;\n let committed = false;\n let disposed = false;\n let temporaryCreated = false;\n const pending = new Set<Promise<unknown>>();\n const removeDirectory = process.platform === 'linux' ? 0x200\n : process.platform === 'darwin' ? 0x80\n : process.platform === 'openbsd' ? 0x08 : 0x800; // AT_REMOVEDIR\n const cleanup = () => {\n if (temporaryParent !== undefined && !committed) api.unlinkat(temporaryParent, 'data', 0);\n if (outputParent !== undefined && temporaryCreated) api.unlinkat(outputParent, temporary, removeDirectory);\n closeAll();\n };\n try {\n const inputParent = openParent(input);\n outputParent = openParent(output);\n inputFD = openChild(inputParent, path.basename(input), constants.O_RDONLY | constants.O_NONBLOCK);\n const sourceStat = fstatSync(inputFD, { bigint: true });\n if (!sourceStat.isFile()) fail('input type validation');\n const existing = api.openat(outputParent, path.basename(output), constants.O_RDONLY | nofollow | constants.O_NONBLOCK, 0) as number;\n if (existing >= 0) {\n try {\n const targetStat = fstatSync(existing, { bigint: true });\n if (sourceStat.dev === targetStat.dev && sourceStat.ino === targetStat.ino) throw new Error('[PipeX] Input and output must be different files');\n } finally { closeSync(existing); }\n }\n // A private directory prevents another directory writer from substituting\n // the temporary entry. Subsequent operations use this exact directory FD.\n if (api.mkdirat(outputParent, temporary, 0o700) !== 0) fail('temporary directory creation');\n temporaryCreated = true;\n temporaryParent = openChild(outputParent, temporary, constants.O_RDONLY | directory);\n const tempStat = fstatSync(temporaryParent);\n if ((tempStat.mode & 0o077) !== 0 || tempStat.uid !== process.geteuid?.()) fail('temporary directory permissions');\n outputFD = openChild(temporaryParent, 'data', constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);\n } catch (error) { cleanup(); throw error; }\n const io = (write: boolean, buffer: Buffer): Promise<number> => {\n const task = new Promise<number>((resolve, reject) => {\n (write ? api.write : api.read).async(write ? outputFD : inputFD, buffer, buffer.length, (error: unknown, count: number | bigint) => {\n if (error || count < 0) reject(new Error('[PipeX] Secure relative file I/O failed'));\n else resolve(Number(count));\n });\n });\n pending.add(task);\n void task.then(() => pending.delete(task), () => pending.delete(task));\n return task;\n };\n let reading = false;\n const source = new Readable({\n highWaterMark: DEFAULT_HIGH_WATER,\n read() {\n if (reading) return;\n reading = true;\n const buffer = Buffer.allocUnsafe(DEFAULT_HIGH_WATER);\n void io(false, buffer).then(count => {\n reading = false;\n if (!this.destroyed) this.push(count ? buffer.subarray(0, count) : null);\n }, error => { reading = false; this.destroy(error as Error); });\n },\n });\n const destination = new Writable({\n highWaterMark: DEFAULT_HIGH_WATER,\n write(chunk: Buffer, _encoding, callback) {\n const work = (async () => {\n let offset = 0;\n while (offset < chunk.length) {\n if (disposed) fail('write after disposal');\n const count = await io(true, chunk.subarray(offset));\n if (!count) fail('relative write progress');\n offset += count;\n }\n })();\n pending.add(work);\n void work.then(() => { pending.delete(work); callback(); }, error => { pending.delete(work); callback(error as Error); });\n },\n });\n return {\n source, destination,\n commit() {\n if (disposed || committed) fail('commit state');\n if (api.renameat(temporaryParent, 'data', outputParent, path.basename(output)) !== 0) fail('atomic relative rename');\n committed = true;\n },\n async dispose() {\n if (disposed) return;\n disposed = true;\n // Wait for native I/O before closing descriptors, including cancellation.\n source.destroy();\n destination.destroy();\n await Promise.allSettled([...pending]);\n cleanup();\n },\n };\n}\n","/**\n * FileController — file-to-file operations\n *\n * engine.file.process(input, output)\n * engine.file.reverse(input, output)\n * engine.file.pack(input, output) → write msgpack + manifest header\n * engine.file.unpack(input, output) → read msgpack, write NDJSON\n */\n\nimport { Transform, type Readable, type Writable } from 'node:stream';\nimport { openAtomicFileSession } from '../secureFiles.js';\nimport { awaitOperation, throwIfAborted } from '../operations.js';\nimport type { DataEngine } from '../dataEngine.js';\nimport {\n buildManifest,\n buildManifestHeaderTransform,\n buildManifestExtractTransform,\n buildNdjsonTransform,\n buildTransformChain,\n createPackrStream,\n createUnpackrStream,\n runPipeline,\n buildByteLimitTransform,\n buildFrameLimitTransform,\n buildObjectLimitTransform,\n buildKnownValueByteLimitTransform,\n} from '../core.js';\nimport type { OperationOptions, PipeXManifest, StreamPluginContext } from '../types.js';\n\nexport class FileController {\n readonly #engine: DataEngine;\n\n constructor(engine: DataEngine) {\n this.#engine = engine;\n }\n\n async #withAtomicOutput(\n inputPath: string,\n outputPath: string,\n allowedRoot: string | undefined,\n signal: AbortSignal,\n run: (source: Readable, destination: Writable) => Promise<void>,\n ): Promise<void> {\n const session = openAtomicFileSession(inputPath, outputPath, allowedRoot);\n try {\n await run(session.source, session.destination);\n throwIfAborted(signal);\n session.commit();\n } finally { await session.dispose(); }\n }\n\n #streamContext(requestId: string, signal: AbortSignal): StreamPluginContext {\n return { requestId, signal, track: pending => this.#engine.trackWork(requestId, pending), limits: this.#engine.limits, logger: this.#engine.logger, tracer: this.#engine.tracer };\n }\n\n /**\n * Source file → Plugin pipeline (compress) → Destination file.\n */\n async process(inputPath: string, outputPath: string, allowedRoot?: string, options: OperationOptions = {}): Promise<void> {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const requestId = this.#engine.startRequest();\n try {\n if (this.#engine.schema) throw new Error('[PipeX] Global object schemas cannot validate raw file streams');\n await this.#withAtomicOutput(inputPath, outputPath, allowedRoot, signal, async (src, dst) => {\n const context = this.#streamContext(requestId, signal);\n const transforms = [\n buildByteLimitTransform(this.#engine.limits.maxInputBytes, 'input'),\n ...buildTransformChain(this.#engine.plugins, 'compress', false, bytes => this.#engine.emitProgress(bytes, requestId), this.#engine.logger, this.#engine.tracer, this.#engine.dlq, context),\n buildByteLimitTransform(this.#engine.limits.maxOutputBytes, 'output'),\n ];\n await runPipeline(src, transforms, dst, { signal });\n });\n await awaitOperation(this.#engine.emitAudit({ requestId, operation: 'process', metadata: { controller: 'file' } }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n } catch (err: unknown) {\n this.#engine.emitError(err, requestId);\n throw err;\n }\n }\n\n /**\n * Source file → Plugin pipeline (decompress, reversed) → Destination file.\n */\n async reverse(inputPath: string, outputPath: string, allowedRoot?: string, options: OperationOptions = {}): Promise<void> {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const requestId = this.#engine.startRequest();\n try {\n if (this.#engine.schema) throw new Error('[PipeX] Global object schemas cannot validate raw file streams');\n await this.#withAtomicOutput(inputPath, outputPath, allowedRoot, signal, async (src, dst) => {\n const context = this.#streamContext(requestId, signal);\n const transforms = [\n buildByteLimitTransform(this.#engine.limits.maxInputBytes, 'input'),\n ...buildTransformChain(this.#engine.plugins, 'decompress', true, bytes => this.#engine.emitProgress(bytes, requestId), this.#engine.logger, this.#engine.tracer, this.#engine.dlq, context),\n buildByteLimitTransform(this.#engine.limits.maxOutputBytes, 'output'),\n ];\n await runPipeline(src, transforms, dst, { signal });\n });\n await awaitOperation(this.#engine.emitAudit({ requestId, operation: 'reverse', metadata: { controller: 'file' } }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n } catch (err: unknown) {\n this.#engine.emitError(err, requestId);\n throw err;\n }\n }\n\n /**\n * Source file → PackrStream → manifest header → Destination msgpack file.\n *\n * Output format: [ PipeXManifest frame ][ ...data frames ]\n * The serialization-only manifest declares an empty plugin chain.\n */\n async pack(inputPath: string, outputPath: string, allowedRoot?: string, options: OperationOptions = {}): Promise<void> {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const requestId = this.#engine.startRequest();\n try {\n await this.#withAtomicOutput(inputPath, outputPath, allowedRoot, signal, async (src, dst) => {\n const transforms = [\n buildByteLimitTransform(this.#engine.limits.maxInputBytes, 'input'),\n buildObjectLimitTransform(this.#engine.limits.maxFrames),\n buildKnownValueByteLimitTransform(this.#engine.limits.maxFrameBytes, 'MessagePack frame'),\n createPackrStream(),\n buildManifestHeaderTransform(buildManifest([])),\n buildFrameLimitTransform(\n this.#engine.limits.maxFrameBytes,\n Math.min(Number.MAX_SAFE_INTEGER, this.#engine.limits.maxFrames + 1),\n ),\n buildByteLimitTransform(this.#engine.limits.maxOutputBytes, 'output'),\n ];\n await runPipeline(src, transforms, dst, { signal });\n });\n await awaitOperation(this.#engine.emitAudit({ requestId, operation: 'pack', metadata: { controller: 'file' } }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n } catch (err: unknown) {\n this.#engine.emitError(err, requestId);\n throw err;\n }\n }\n\n /**\n * Source msgpack file → UnpackrStream → manifest extraction → NDJSON → Destination file.\n *\n * Fires 'manifest' event with the recovered PipeXManifest before streaming data.\n */\n async unpack(inputPath: string, outputPath: string, allowedRoot?: string, options: OperationOptions = {}): Promise<void> {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const requestId = this.#engine.startRequest();\n try {\n await this.#withAtomicOutput(inputPath, outputPath, allowedRoot, signal, async (src, dst) => {\n const unpacker = createUnpackrStream(this.#engine.limits.maxInputBytes);\n const extract = buildManifestExtractTransform((manifest: PipeXManifest) => {\n const expected: string[] = [];\n if (manifest.plugins.length !== expected.length || manifest.plugins.some((plugin, index) => plugin !== expected[index])) {\n throw new Error('[PipeX] Manifest plugin chain does not match the configured engine');\n }\n this.#engine.emit('manifest', manifest, requestId);\n });\n const ndjson = buildNdjsonTransform();\n const validate = new Transform({\n writableObjectMode: true,\n readableObjectMode: true,\n transform: (value: unknown, _encoding, callback) => {\n try { this.#engine.validate(value); callback(null, value); }\n catch (error) { callback(error as Error); }\n },\n });\n await runPipeline(src, [\n buildByteLimitTransform(this.#engine.limits.maxInputBytes, 'input'),\n buildFrameLimitTransform(\n this.#engine.limits.maxFrameBytes,\n Math.min(Number.MAX_SAFE_INTEGER, this.#engine.limits.maxFrames + 1),\n ),\n unpacker,\n extract,\n buildObjectLimitTransform(this.#engine.limits.maxFrames),\n validate,\n ndjson,\n buildByteLimitTransform(this.#engine.limits.maxOutputBytes, 'output'),\n ], dst, { signal });\n });\n await awaitOperation(this.#engine.emitAudit({ requestId, operation: 'unpack', metadata: { controller: 'file' } }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n } catch (err: unknown) {\n this.#engine.emitError(err, requestId);\n throw err;\n }\n }\n}\n","/**\n * BinaryController — in-memory binary operations\n *\n * engine.binary.pack(data) → Buffer (msgpack)\n * engine.binary.unpack(buf) → T\n * engine.binary.run(input) → EngineResult (plugin pipeline)\n * engine.binary.undo(result) → T (trusted-type round-trip)\n */\n\nimport type { DataEngine } from '../dataEngine.js';\nimport {\n PACKR,\n UNPACKR,\n detectType,\n toBuffer,\n fromBuffer,\n makeContext,\n withRetry,\n buildManifest,\n isManifest,\n assertReversiblePipeline,\n assertMessagePackFrameLimits,\n assertKnownValueByteLimit,\n assertOriginalType,\n} from '../core.js';\nimport type { EngineResult, PipeXManifest, OperationOptions, BinaryUndoOptions } from '../types.js';\n\nimport { awaitOperation, throwIfAborted } from '../operations.js';\n\nexport class BinaryController {\n readonly #engine: DataEngine;\n\n constructor(engine: DataEngine) {\n this.#engine = engine;\n }\n\n /**\n * Serialise a supported JS value to a msgpack Buffer (synchronous).\n * For streaming large datasets use engine.stream or engine.file.pack instead.\n */\n pack(data: unknown): Buffer {\n try {\n assertKnownValueByteLimit(\n data,\n Math.min(this.#engine.limits.maxInputBytes, this.#engine.limits.maxFrameBytes),\n 'Serialization input',\n );\n const packed = PACKR.pack(data) as Buffer;\n if (packed.length > this.#engine.limits.maxInputBytes) throw new Error('[PipeX] Packed input exceeds configured limit');\n assertMessagePackFrameLimits(packed, this.#engine.limits.maxFrameBytes, 1);\n if (packed.length > this.#engine.limits.maxOutputBytes) throw new Error('[PipeX] Packed output exceeds configured limit');\n return packed;\n } catch (err: unknown) {\n if (err instanceof Error && err.message.startsWith('[PipeX]')) throw err;\n throw new Error('[PipeX] binary.pack failed');\n }\n }\n\n /**\n * Deserialise a msgpack Buffer back to T (synchronous).\n */\n unpack<T = unknown>(input: Buffer | Uint8Array): T {\n try {\n if (input.byteLength > this.#engine.limits.maxInputBytes) throw new Error('[PipeX] Serialized input exceeds configured limit');\n assertMessagePackFrameLimits(input, this.#engine.limits.maxFrameBytes, 1);\n return UNPACKR.unpack(input as Buffer) as T;\n } catch (err: unknown) {\n if (err instanceof Error && err.message.startsWith('[PipeX]')) throw err;\n throw new Error('[PipeX] binary.unpack failed: invalid MessagePack input');\n }\n }\n\n // Only locally produced buffers carry a trusted implicit type. Transported\n // results must be decoded using an application-owned expectedType.\n readonly #trustedTypes = new WeakMap<Buffer, string>();\n\n async run(input: unknown, options: OperationOptions = {}): Promise<EngineResult> {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const originalType = detectType(input);\n assertOriginalType(originalType);\n const plugins = this.#engine.plugins;\n const pipeline = [...this.#engine.pipeline];\n const limits = this.#engine.limits;\n const requestId = this.#engine.startRequest({ operation: 'run' });\n const startTime = Date.now();\n const span = this.#engine.tracer?.startSpan('binary:run', { requestId } as any);\n try {\n span?.setAttribute('input.type', originalType);\n this.#engine.validate(input);\n assertKnownValueByteLimit(input, limits.maxInputBytes, 'Input');\n let data = toBuffer(input);\n if (data.length > limits.maxInputBytes) throw new Error('[PipeX] Input exceeds configured limit');\n if (originalType === 'object' || originalType === 'array') {\n assertMessagePackFrameLimits(data, limits.maxFrameBytes, 1);\n }\n const metrics: Record<string, number> = Object.create(null);\n for (const plugin of plugins) {\n const t0 = Date.now();\n const pSpan = this.#engine.tracer?.startSpan(`plugin:${plugin.name}`, { requestId } as any);\n try {\n pSpan?.setAttribute('mode', 'process');\n const ctx = makeContext(requestId, { originalType }, this.#engine.logger, pSpan, signal, limits);\n data = await withRetry(() => plugin.process(data, ctx), plugin.retryOptions, this.#engine.logger, {\n signal, limits, track: pending => this.#engine.trackWork(requestId, pending),\n });\n if (!Buffer.isBuffer(data) || data.length > limits.maxOutputBytes) throw new Error('[PipeX] Plugin output exceeds configured limit');\n } catch (error) {\n pSpan?.setAttribute('error', true);\n throw error;\n } finally { pSpan?.end(); }\n metrics[plugin.name] = Date.now() - t0;\n this.#engine.emit('plugin:after', plugin.name, metrics[plugin.name]!);\n }\n if (data.length > limits.maxOutputBytes) throw new Error('[PipeX] Output exceeds configured limit');\n throwIfAborted(signal);\n const durationMs = Date.now() - startTime;\n await awaitOperation(this.#engine.emitAudit({\n requestId, operation: 'process', metadata: { inputType: originalType, durationMs },\n }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#trustedTypes.set(data, originalType);\n const result: EngineResult = { data, originalType, pipeline, metrics: { durationMs, steps: metrics } };\n span?.setAttribute('duration_ms', durationMs);\n this.#engine.endRequest(requestId, durationMs);\n return result;\n } catch (error) {\n span?.setAttribute('error', true);\n this.#engine.emitError(error, requestId);\n throw error;\n } finally {\n span?.end();\n this.#engine.releaseRequest(requestId);\n }\n }\n\n async undo<T = unknown>(result: EngineResult, options?: BinaryUndoOptions): Promise<T>;\n async undo<T = unknown>(input: Buffer, forceType: string, options?: OperationOptions): Promise<T>;\n async undo<T = unknown>(\n inputOrResult: Buffer | EngineResult,\n forceTypeOrOptions?: string | BinaryUndoOptions,\n operationOptions: OperationOptions = {},\n ): Promise<T> {\n const raw = Buffer.isBuffer(inputOrResult);\n let data: Buffer;\n let origType: string;\n let options: OperationOptions;\n if (raw) {\n assertOriginalType(forceTypeOrOptions);\n data = inputOrResult;\n origType = forceTypeOrOptions;\n options = operationOptions;\n } else {\n const result = inputOrResult;\n if (!result || typeof result !== 'object' || !Buffer.isBuffer(result.data)\n || !Array.isArray(result.pipeline) || result.pipeline.length > 256\n || !result.pipeline.every(p => typeof p === 'string' && p.length <= 512)\n || !result.metrics || !Number.isFinite(result.metrics.durationMs) || result.metrics.durationMs < 0\n || !result.metrics.steps || typeof result.metrics.steps !== 'object' || Array.isArray(result.metrics.steps)\n || !Object.values(result.metrics.steps).every(n => typeof n === 'number' && Number.isFinite(n) && n >= 0)) {\n throw new Error('[PipeX] Invalid EngineResult');\n }\n assertOriginalType(result.originalType);\n if (forceTypeOrOptions !== undefined && (forceTypeOrOptions === null || typeof forceTypeOrOptions !== 'object')) {\n throw new Error('[PipeX] Invalid undo options');\n }\n const undoOptions = forceTypeOrOptions as BinaryUndoOptions | undefined;\n const trustedType = undoOptions?.expectedType ?? this.#trustedTypes.get(result.data);\n if (trustedType === undefined) throw new Error('[PipeX] Transported EngineResult requires a trusted expectedType');\n assertOriginalType(trustedType);\n if (trustedType !== result.originalType) throw new Error('[PipeX] Result type does not match the expected type');\n data = result.data;\n origType = trustedType;\n options = undoOptions ?? {};\n }\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const plugins = this.#engine.plugins;\n assertReversiblePipeline(plugins);\n const limits = this.#engine.limits;\n if (data.length > limits.maxInputBytes) throw new Error('[PipeX] Undo input exceeds configured limit');\n const requestId = this.#engine.startRequest({ operation: 'undo', originalType: origType });\n const span = this.#engine.tracer?.startSpan('binary:undo', { requestId } as any);\n try {\n // Serialization manifests are never parsed ahead of cryptographic checks.\n if (raw && plugins.length === 0 && data.length > 0) {\n let parsed: { manifest: PipeXManifest; data: unknown } | undefined;\n try { parsed = this.unpackWithManifest(data); } catch { /* raw input */ }\n if (parsed) {\n if (parsed.manifest.plugins.length !== 0) throw new Error('[PipeX] Manifest plugin chain does not match the configured engine');\n if (detectType(parsed.data) !== origType) throw new Error('[PipeX] Manifest data does not match the expected type');\n data = toBuffer(parsed.data);\n }\n }\n for (const plugin of [...plugins].reverse()) {\n const pSpan = this.#engine.tracer?.startSpan(`plugin:${plugin.name}`, { requestId } as any);\n try {\n pSpan?.setAttribute('mode', 'reverse');\n const ctx = makeContext(requestId, { originalType: origType }, this.#engine.logger, pSpan, signal, limits);\n data = await withRetry(() => plugin.reverse!(data, ctx), plugin.retryOptions, this.#engine.logger, {\n signal, limits, track: pending => this.#engine.trackWork(requestId, pending),\n });\n if (!Buffer.isBuffer(data) || data.length > limits.maxOutputBytes) throw new Error('[PipeX] Plugin output exceeds configured limit');\n } catch (error) {\n pSpan?.setAttribute('error', true);\n throw error;\n } finally { pSpan?.end(); }\n this.#engine.emit('plugin:after', plugin.name, 0);\n }\n if (data.length > limits.maxOutputBytes) throw new Error('[PipeX] Output exceeds configured limit');\n throwIfAborted(signal);\n const restored = fromBuffer(data, origType, limits.maxFrameBytes) as T;\n this.#engine.validate(restored);\n throwIfAborted(signal);\n await awaitOperation(this.#engine.emitAudit({\n requestId, operation: 'reverse', metadata: { originalType: origType },\n }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n return restored;\n } catch (error) {\n span?.setAttribute('error', true);\n this.#engine.emitError(error, requestId);\n throw error;\n } finally {\n span?.end();\n this.#engine.releaseRequest(requestId);\n }\n }\n\n /**\n * Pack data AND embed a manifest header as the first msgpack frame.\n * Mirrors what file.pack writes to disk — useful for in-memory transport.\n */\n packWithManifest(data: unknown): Buffer {\n if (this.#engine.plugins.length > 0) {\n throw new Error('[PipeX] packWithManifest is serialization-only; use binary.run for plugin transforms');\n }\n const manifest = buildManifest([]);\n assertKnownValueByteLimit(\n data,\n Math.min(this.#engine.limits.maxInputBytes, this.#engine.limits.maxFrameBytes),\n 'Serialization input',\n );\n const mFrame = PACKR.pack(manifest);\n const dFrame = PACKR.pack(data);\n assertMessagePackFrameLimits(mFrame, this.#engine.limits.maxFrameBytes, 1);\n assertMessagePackFrameLimits(dFrame, this.#engine.limits.maxFrameBytes, 1);\n if (mFrame.length + dFrame.length > Math.min(this.#engine.limits.maxInputBytes, this.#engine.limits.maxOutputBytes)) {\n throw new Error('[PipeX] Serialized input exceeds configured limit');\n }\n return Buffer.concat([mFrame, dFrame]);\n }\n\n /**\n * Unpack a buffer that begins with a PipeXManifest frame.\n * Returns { manifest, data } — callers can inspect the manifest to verify\n * the pipeline that produced the buffer before consuming data.\n */\n unpackWithManifest<T = unknown>(input: Buffer): { manifest: PipeXManifest; data: T } {\n if (input.length > this.#engine.limits.maxInputBytes) throw new Error('[PipeX] Serialized input exceeds configured limit');\n assertMessagePackFrameLimits(\n input,\n this.#engine.limits.maxFrameBytes,\n 2,\n );\n const frames: unknown[] = [];\n try {\n UNPACKR.unpackMultiple(input, (value) => {\n if (frames.length >= 2) throw new Error('[PipeX] Frame count exceeds configured limit');\n frames.push(value);\n });\n } catch (err: unknown) {\n if (err instanceof Error && err.message.startsWith('[PipeX]')) throw err;\n throw new Error('[PipeX] binary.unpackWithManifest: invalid MessagePack input');\n }\n\n if (frames.length < 2) {\n throw new Error('[PipeX] binary.unpackWithManifest: buffer contains fewer than 2 frames');\n }\n if (!isManifest(frames[0])) {\n throw new Error('[PipeX] binary.unpackWithManifest: first frame is not a PipeXManifest');\n }\n return { manifest: frames[0], data: frames[1] as T };\n }\n}\n","/**\n * StreamController — live stream operations\n *\n * engine.stream.into(writable) → Writable endpoint (compress forward)\n * engine.stream.reverseInto(writable) → Writable endpoint (decompress reversed)\n * engine.stream.pack() → PackrStream (object → msgpack bytes)\n * engine.stream.unpack() → GuardedUnpackrStream (bytes → objects)\n * engine.stream.pipe(readable, writable) → orchestrate full pipeline\n */\n\nimport { Readable, Writable, Transform, PassThrough, Duplex } from 'node:stream';\nimport { awaitOperation, throwIfAborted } from '../operations.js';\nimport type { DataEngine } from '../dataEngine.js';\nimport {\n buildTransformChain,\n buildManifest,\n buildManifestHeaderTransform,\n buildManifestExtractTransform,\n createPackrStream,\n createUnpackrStream,\n runPipeline,\n buildByteLimitTransform,\n buildFrameLimitTransform,\n buildObjectLimitTransform,\n buildKnownValueByteLimitTransform,\n} from '../core.js';\nimport type { OperationOptions, PipeXManifest, StreamPluginContext } from '../types.js';\n\n\nexport class StreamController {\n readonly #engine: DataEngine;\n\n constructor(engine: DataEngine) {\n this.#engine = engine;\n }\n\n #streamContext(requestId: string, signal: AbortSignal): StreamPluginContext {\n return { requestId, signal, track: pending => this.#engine.trackWork(requestId, pending), limits: this.#engine.limits, logger: this.#engine.logger, tracer: this.#engine.tracer };\n }\n\n #bridge(input: PassThrough, output: PassThrough): Duplex {\n // Node supports a { writable, readable } pair here since v16.8. The\n // NodeJS typings do not currently model the Node-stream pair overload.\n return Duplex.from({ writable: input, readable: output } as unknown as NodeJS.ReadWriteStream);\n }\n\n #into(destination: Writable, reverse: boolean, options: OperationOptions): Writable {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n if (this.#engine.schema) throw new Error('[PipeX] Global object schemas cannot validate raw byte streams');\n const requestId = this.#engine.startRequest();\n const context = this.#streamContext(requestId, signal);\n const mode = reverse ? 'decompress' : 'compress';\n let transforms: ReturnType<typeof buildTransformChain>;\n try {\n transforms = buildTransformChain(\n this.#engine.plugins, mode, reverse,\n bytes => this.#engine.emitProgress(bytes, requestId),\n this.#engine.logger,\n this.#engine.tracer,\n this.#engine.dlq,\n context,\n );\n } catch (error) {\n this.#engine.emitError(error, requestId);\n throw error;\n }\n\n const source = new PassThrough();\n let finalCallback: ((error?: Error | null) => void) | undefined;\n const endpoint = new Writable({\n write(chunk, encoding, callback) {\n source.write(chunk, encoding, callback);\n },\n final(callback) {\n finalCallback = callback;\n source.end();\n },\n destroy(error, callback) {\n finalCallback = undefined;\n if (!source.destroyed) source.destroy(error ?? undefined);\n callback(error);\n },\n });\n const settleEndpoint = (error?: Error) => {\n const callback = finalCallback;\n finalCallback = undefined;\n if (callback) callback(error);\n else if (error && !endpoint.destroyed) endpoint.destroy(error);\n };\n\n void runPipeline(source, [\n buildByteLimitTransform(this.#engine.limits.maxInputBytes, 'input'),\n ...transforms,\n buildByteLimitTransform(this.#engine.limits.maxOutputBytes, 'output'),\n ], destination, { signal }).then(async () => {\n await awaitOperation(this.#engine.emitAudit({\n requestId,\n operation: reverse ? 'reverse' : 'process',\n metadata: { controller: 'stream' },\n }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n settleEndpoint();\n }).catch(error => {\n const failure = error instanceof Error ? error : new Error(String(error));\n this.#engine.emitError(failure, requestId);\n settleEndpoint(failure);\n });\n\n return endpoint;\n }\n\n /**\n * Returns a Writable that pumps incoming bytes through the plugin pipeline\n * (compress direction) and forwards them to `destination`.\n *\n * @example\n * readableSource.pipe(engine.stream.into(createWriteStream('out')));\n */\n into(destination: Writable, options: OperationOptions = {}): Writable {\n return this.#into(destination, false, options);\n }\n\n /**\n * Returns a Writable that pumps bytes through the reversed plugin pipeline\n * (decompress direction) and forwards to `destination`.\n *\n * @example\n * readableSource.pipe(engine.stream.reverseInto(createWriteStream('restored')));\n */\n reverseInto(destination: Writable, options: OperationOptions = {}): Writable {\n return this.#into(destination, true, options);\n }\n\n /**\n * Returns a PackrStream: write JS objects, read msgpack bytes.\n * A manifest header frame is prepended automatically.\n *\n * @example\n * objectSource.pipe(engine.stream.pack()).pipe(tcpSocket);\n */\n pack(options: OperationOptions = {}): Duplex {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const requestId = this.#engine.startRequest({ operation: 'pack' });\n const input = new PassThrough({ objectMode: true });\n const output = new PassThrough();\n const transforms = [\n buildObjectLimitTransform(this.#engine.limits.maxFrames),\n buildKnownValueByteLimitTransform(this.#engine.limits.maxFrameBytes, 'MessagePack frame'),\n createPackrStream(),\n buildManifestHeaderTransform(buildManifest([])),\n buildFrameLimitTransform(\n this.#engine.limits.maxFrameBytes,\n Math.min(Number.MAX_SAFE_INTEGER, this.#engine.limits.maxFrames + 1),\n ),\n buildByteLimitTransform(this.#engine.limits.maxOutputBytes, 'output'),\n ];\n const duplex = this.#bridge(input, output);\n runPipeline(input, transforms, output, { signal })\n .then(async () => {\n await awaitOperation(this.#engine.emitAudit({ requestId, operation: 'pack', metadata: { controller: 'stream' } }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n })\n .catch(error => {\n this.#engine.emitError(error, requestId);\n duplex.destroy(error instanceof Error ? error : new Error(String(error)));\n });\n // Expose `header` as the readable end — callers pipe from this Transform\n return duplex;\n }\n\n /**\n * Returns a GuardedUnpackrStream: write msgpack bytes, read JS objects.\n * Fires the engine's 'manifest' event when the header frame is detected.\n *\n * @example\n * tcpSocket.pipe(engine.stream.unpack()).on('data', obj => console.log(obj));\n */\n unpack(options: OperationOptions = {}): Duplex {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n const requestId = this.#engine.startRequest({ operation: 'unpack' });\n const input = new PassThrough();\n const output = new PassThrough({ objectMode: true });\n const unpacker = createUnpackrStream(this.#engine.limits.maxInputBytes);\n const extract = buildManifestExtractTransform((m: PipeXManifest) => {\n const expected: string[] = [];\n if (m.plugins.length !== expected.length || m.plugins.some((plugin, index) => plugin !== expected[index])) {\n throw new Error('[PipeX] Manifest plugin chain does not match the configured engine');\n }\n this.#engine.emit('manifest', m, requestId);\n });\n const validate = new Transform({\n writableObjectMode: true,\n readableObjectMode: true,\n transform: (value: unknown, _encoding, callback) => {\n try { this.#engine.validate(value); callback(null, value); }\n catch (error) { callback(error as Error); }\n },\n });\n const transforms = [\n buildByteLimitTransform(this.#engine.limits.maxInputBytes, 'input'),\n buildFrameLimitTransform(\n this.#engine.limits.maxFrameBytes,\n Math.min(Number.MAX_SAFE_INTEGER, this.#engine.limits.maxFrames + 1),\n ),\n unpacker,\n extract,\n buildObjectLimitTransform(this.#engine.limits.maxFrames),\n validate,\n ];\n const duplex = this.#bridge(input, output);\n runPipeline(input, transforms, output, { signal })\n .then(async () => {\n await awaitOperation(this.#engine.emitAudit({ requestId, operation: 'unpack', metadata: { controller: 'stream' } }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n })\n .catch(error => {\n this.#engine.emitError(error, requestId);\n duplex.destroy(error instanceof Error ? error : new Error(String(error)));\n });\n return duplex;\n }\n\n /**\n * Orchestrate a complete pipeline: Readable → plugin chain → Writable.\n * This is the primary low-level entry point — file/binary controllers\n * build on top of this.\n *\n * @example\n * await engine.stream.pipe(\n * createReadStream('input.bin'),\n * createWriteStream('output.bin'),\n * );\n */\n async pipe(source: Readable, destination: Writable, reverse = false, options: OperationOptions = {}): Promise<void> {\n const signal = this.#engine.createOperationSignal(options);\n throwIfAborted(signal);\n if (this.#engine.schema) throw new Error('[PipeX] Global object schemas cannot validate raw byte streams');\n const requestId = this.#engine.startRequest();\n const mode = reverse ? 'decompress' : 'compress';\n const context = this.#streamContext(requestId, signal);\n try {\n const transforms = buildTransformChain(\n this.#engine.plugins, mode, reverse,\n bytes => this.#engine.emitProgress(bytes, requestId),\n this.#engine.logger,\n this.#engine.tracer,\n this.#engine.dlq,\n context,\n );\n await runPipeline(source, [\n buildByteLimitTransform(this.#engine.limits.maxInputBytes, 'input'),\n ...transforms,\n buildByteLimitTransform(this.#engine.limits.maxOutputBytes, 'output'),\n ], destination, { signal });\n await awaitOperation(this.#engine.emitAudit({\n requestId,\n operation: reverse ? 'reverse' : 'process',\n metadata: { controller: 'stream' },\n }), signal, pending => this.#engine.trackWork(requestId, pending));\n throwIfAborted(signal);\n this.#engine.endRequest(requestId);\n } catch (err: unknown) {\n this.#engine.emitError(err, requestId);\n throw err;\n }\n }\n}\n","/**\n * DataEngine — the public surface of PipeX\n *\n * Responsibilities:\n * 1. Plugin registry (use / plugins)\n * 2. EventEmitter lifecycle (start, plugin:after, progress, error, end, manifest)\n * 3. Controller wiring (file, binary, stream)\n * 4. Request lifecycle helpers used by controllers (startRequest, endRequest, …)\n *\n * Zero I/O, zero stream logic — all of that lives in core.ts and controllers.\n */\n\nimport { EventEmitter } from 'node:events';\nimport { randomUUID } from 'node:crypto';\nimport { Writable } from 'node:stream';\nimport { z } from 'zod';\nimport type { \n ProcessorPlugin, \n Logger, \n Tracer,\n AuditLogger,\n AuditRecord,\n SchemaRegistry,\n EngineConfig\n , EngineLimits\n , OperationOptions\n , RegisteredPluginCapabilities\n} from './types.js';\nimport { DEFAULT_LIMITS, getPluginCapabilities } from './core.js';\nimport { FileController } from './controllers/FileController.js';\nimport { BinaryController } from './controllers/BinaryController.js';\nimport { StreamController } from './controllers/StreamController.js';\n\nimport { safeLogger, safeTracer, observe } from './observability.js';\nimport { registerDeadline } from './operations.js';\n\nconst MAX_TIMER_MS = 0x7fff_ffff;\n\n// ─── Typed EventEmitter ───────────────────────────────────────────────────────\n\ninterface PipeXEventMap {\n start: [requestId: string];\n 'plugin:after': [name: string, durationMs: number];\n progress: [bytes: number, requestId: string];\n error: [err: Error, requestId: string];\n end: [requestId: string, durationMs?: number];\n manifest: [manifest: unknown, requestId?: string];\n}\n\nexport type PluginConstructor<TOptions = unknown> = new (options: TOptions) => ProcessorPlugin;\n\n// ─── Engine ───────────────────────────────────────────────────────────────────\n\nexport class DataEngine extends EventEmitter {\n /** Built-in plugin registry for config-driven bootstrap. */\n private static readonly pluginRegistry = new Map<string, (options: unknown) => ProcessorPlugin>();\n\n /** Register a plugin class for use in fromConfig(). */\n public static registerPlugin<TOptions>(name: string, pluginClass: PluginConstructor<TOptions>): void {\n if (!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(name) || typeof pluginClass !== 'function') {\n throw new Error('[PipeX] Invalid plugin registration');\n }\n this.pluginRegistry.set(name, options => new pluginClass(options as TOptions));\n }\n\n /**\n * Bootstrap a DataEngine from a configuration object.\n */\n public static async fromConfig(config: EngineConfig): Promise<DataEngine> {\n if (!config || typeof config !== 'object') throw new Error('[PipeX] Configuration must be an object');\n const engine = new DataEngine(config.limits);\n\n if (config.logger) engine.setLogger(config.logger);\n if (config.tracer) engine.setTracer(config.tracer);\n if (config.auditLogger) engine.setAuditLogger(config.auditLogger);\n if (config.dlq) engine.setDlq(config.dlq);\n if (config.schemaRegistry) engine.setSchemaRegistry(config.schemaRegistry);\n if (config.schema) engine.setSchema(config.schema);\n \n if (config.plugins) {\n if (!Array.isArray(config.plugins)) throw new Error('[PipeX] Configuration plugins must be an array');\n for (const p of config.plugins) {\n const createPlugin = this.pluginRegistry.get(p.name);\n if (!createPlugin) throw new Error(`[PipeX] Unknown plugin in config: ${p.name}`);\n try {\n engine.use(createPlugin(p.options));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`[PipeX] Failed to initialize plugin \"${p.name}\": ${message}`, { cause: error });\n }\n }\n }\n\n return engine;\n }\n\n // Plugins are readonly from outside; controllers access via #plugins\n readonly #plugins: ProcessorPlugin[] = [];\n #pluginView: readonly ProcessorPlugin[] = Object.freeze([]);\n #schema?: z.ZodType<any>;\n #registry?: SchemaRegistry;\n #logger?: Logger;\n #tracer?: Tracer;\n #dlq?: Writable;\n #auditLogger?: AuditLogger;\n #limits: Readonly<EngineLimits>;\n readonly #activeRequests = new Set<string>();\n readonly #pendingWork = new Map<string, Set<Promise<unknown>>>();\n readonly #finishedRequests = new Set<string>();\n readonly #requestPipelines = new Map<string, readonly string[]>();\n\n // ── Controllers ─────────────────────────────────────────────────────────────\n readonly file: FileController;\n readonly binary: BinaryController;\n readonly stream: StreamController;\n\n constructor(limits: Partial<EngineLimits> = {}) {\n super();\n this.#limits = Object.freeze({ ...DEFAULT_LIMITS, ...limits });\n this.#validateLimits(this.#limits);\n this.file = new FileController(this);\n this.binary = new BinaryController(this);\n this.stream = new StreamController(this);\n }\n\n #validateLimits(limits: EngineLimits): void {\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`[PipeX] Invalid engine limit ${name}`);\n }\n }\n if (limits.maxInputBytes < 1 || limits.maxOutputBytes < 1 || limits.maxFrameBytes < 1\n || limits.maxFrames < 1 || limits.maxConcurrentOperations < 1 || limits.maxRetryAttempts < 1\n || limits.maxKmsEncryptedKeyBytes < 1 || limits.maxKmsKeyIdBytes < 1) {\n throw new Error('[PipeX] Engine limits must be positive');\n }\n if (limits.operationTimeoutMs > MAX_TIMER_MS || limits.maxKmsEncryptedKeyBytes > 0xffff_ffff) {\n throw new Error('[PipeX] Engine limit exceeds its supported protocol or timer range');\n }\n }\n\n get limits(): Readonly<EngineLimits> {\n return this.#limits;\n }\n\n setLimits(limits: Partial<EngineLimits>): this {\n if (this.#activeRequests.size > 0) {\n throw new Error('[PipeX] Cannot modify engine limits while operations are active');\n }\n const next = { ...this.#limits, ...limits };\n this.#validateLimits(next);\n this.#limits = Object.freeze(next);\n return this;\n }\n\n createOperationSignal(options: OperationOptions = {}): AbortSignal {\n const timeoutMs = options.timeoutMs ?? this.#limits.operationTimeoutMs;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMER_MS) {\n throw new Error('[PipeX] Invalid operation timeout');\n }\n const signals = options.signal ? [options.signal] : [];\n if (timeoutMs > 0) signals.push(AbortSignal.timeout(timeoutMs));\n const signal = signals.length === 0 ? new AbortController().signal : AbortSignal.any(signals);\n registerDeadline(signal, timeoutMs);\n return signal;\n }\n\n /**\n * Set the optional, caller-owned failure sink (legacy DLQ terminology).\n * A failed fallback-transform chunk is written after retries are exhausted;\n * the operation still rejects. PipeX does not persist, replay, end, or own\n * the supplied Writable.\n *\n * @param stream The caller-provided Writable used as a failure sink.\n */\n setDlq(stream: Writable): this {\n if (!stream || typeof stream.write !== 'function') throw new Error('[PipeX] DLQ must be a writable stream');\n this.#dlq = stream;\n return this;\n }\n\n /** The current caller-provided failure sink, if any. */\n get dlq(): Writable | undefined {\n return this.#dlq;\n }\n\n /** \n * Set the engine's logger for structured observability. \n * Compatible with Pino, Winston, or any logger implementing the Logger interface.\n * \n * @param logger The logger instance.\n */\n setLogger(logger: Logger): this {\n if (!logger || !['info', 'warn', 'error', 'debug'].every(level => typeof logger[level as keyof Logger] === 'function')) {\n throw new Error('[PipeX] Logger must implement info, warn, error, and debug');\n }\n this.#logger = safeLogger(logger);\n return this;\n }\n\n /** The current logger instance. */\n get logger(): Logger | undefined {\n return this.#logger;\n }\n\n /** \n * Set the engine's tracer for OpenTelemetry-compatible tracing. \n * \n * @param tracer The tracer instance.\n */\n setTracer(tracer: Tracer): this {\n if (!tracer || typeof tracer.startSpan !== 'function') throw new Error('[PipeX] Tracer must implement startSpan');\n this.#tracer = safeTracer(tracer);\n return this;\n }\n\n /** The current tracer instance. */\n get tracer(): Tracer | undefined {\n return this.#tracer;\n }\n\n /** \n * Set the engine's audit logger for compliance and security auditing. \n * \n * @param logger The audit logger instance.\n */\n setAuditLogger(logger: AuditLogger): this {\n if (!logger || typeof logger.log !== 'function') throw new Error('[PipeX] Audit logger must implement log');\n this.#auditLogger = logger;\n return this;\n }\n\n /** \n * Emits an audit record if an audit logger is configured. \n * This is called automatically by controllers.\n * \n * @param record The audit record metadata.\n */\n async emitAudit(record: Omit<AuditRecord, 'pluginChain' | 'timestamp'>): Promise<void> {\n if (this.#auditLogger) {\n await this.#auditLogger.log({\n ...record,\n pluginChain: record.operation === 'pack' || record.operation === 'unpack'\n ? [] : [...(this.#requestPipelines.get(record.requestId) ?? this.pipeline)],\n timestamp: Date.now(),\n });\n }\n }\n\n /** \n * Set a Schema Registry to fetch schemas dynamically.\n * \n * @param registry The schema registry provider.\n */\n setSchemaRegistry(registry: SchemaRegistry): this {\n if (!registry || typeof registry.getSchema !== 'function') throw new Error('[PipeX] Schema registry must implement getSchema');\n this.#registry = registry;\n return this;\n }\n\n /** \n * Fetch a schema from the registry and set it as the engine's active schema. \n * \n * @param subject The name of the schema to fetch.\n * @param version Optional version of the schema.\n */\n async loadSchema(subject: string, version?: number): Promise<void> {\n if (!this.#registry) throw new Error('[PipeX] No Schema Registry configured');\n const schema = await this.#registry.getSchema(subject, version);\n this.setSchema(schema);\n }\n\n /**\n * Set a global Zod schema for input/output validation.\n * When set, controllers will automatically validate data against this schema.\n */\n setSchema(schema: z.ZodType<any>): this {\n if (!schema || typeof schema.safeParse !== 'function') throw new Error('[PipeX] Schema must implement safeParse');\n this.#schema = schema;\n return this;\n }\n\n get schema(): z.ZodType<any> | undefined {\n return this.#schema;\n }\n\n /** Validates data against the registered schema (if any). Throws on failure. */\n validate(data: unknown): void {\n if (this.#schema) {\n const result = this.#schema.safeParse(data);\n if (!result.success) {\n throw new Error('[PipeX] Core Validation failed');\n }\n }\n }\n\n // ── Plugin registry ──────────────────────────────────────────────────────────\n\n /** Register a plugin and return this for fluent chaining. */\n use(plugin: ProcessorPlugin): this {\n if (!plugin || typeof plugin.name !== 'string' || plugin.name.length === 0 || plugin.name.length > 128\n || typeof plugin.version !== 'string' || plugin.version.length === 0\n || typeof plugin.process !== 'function') {\n throw new Error('[PipeX] Invalid processor plugin');\n }\n getPluginCapabilities(plugin);\n if (this.#activeRequests.size > 0) {\n throw new Error('[PipeX] Cannot modify the plugin pipeline while operations are active');\n }\n if (this.#plugins.length >= 256) throw new Error('[PipeX] Maximum plugin count exceeded');\n this.#plugins.push(plugin);\n this.#pluginView = Object.freeze([...this.#plugins]);\n return this;\n }\n\n /**\n * Read-only view of the registered plugins.\n * Exposed so controllers can iterate without mutating the list.\n */\n get plugins(): readonly ProcessorPlugin[] {\n return this.#pluginView;\n }\n\n /** Human-readable plugin identifiers in execution order. */\n get pipeline(): readonly string[] {\n return Object.freeze(this.#pluginView.map(plugin => `${plugin.name}@${plugin.version}`));\n }\n\n /** Runtime-validated capabilities in pipeline order. */\n get pluginCapabilities(): readonly Readonly<RegisteredPluginCapabilities>[] {\n return Object.freeze(this.#pluginView.map(plugin => Object.freeze({\n plugin: `${plugin.name}@${plugin.version}`,\n ...getPluginCapabilities(plugin),\n })));\n }\n\n // ── Request lifecycle (called by controllers) ────────────────────────────────\n\n /** Generates a requestId, emits 'start', returns the id. */\n startRequest(metadata: Record<string, unknown> = {}): string {\n if (this.#activeRequests.size >= this.#limits.maxConcurrentOperations) {\n throw new Error('[PipeX] Maximum concurrent operations exceeded');\n }\n const requestId = randomUUID();\n this.#activeRequests.add(requestId);\n this.#requestPipelines.set(requestId, this.pipeline);\n try { this.#logger?.info('[PipeX] Request started', { requestId, ...metadata }); } catch { /* logger isolation */ }\n this.emit('start', requestId);\n return requestId;\n }\n\n /** Keep capacity reserved for accepted non-cooperative work after caller cancellation. */\n trackWork(requestId: string, pending: Promise<unknown>): void {\n let work = this.#pendingWork.get(requestId);\n if (!work) this.#pendingWork.set(requestId, work = new Set());\n work.add(pending);\n const settled = () => {\n work!.delete(pending);\n if (work!.size === 0) {\n this.#pendingWork.delete(requestId);\n if (this.#finishedRequests.has(requestId)) this.releaseRequest(requestId);\n }\n };\n void pending.then(settled, settled);\n }\n\n /** Idempotent cleanup, including error paths that fail before transformation starts. */\n releaseRequest(requestId: string): void {\n if (this.#pendingWork.get(requestId)?.size) {\n this.#finishedRequests.add(requestId);\n return;\n }\n this.#activeRequests.delete(requestId);\n this.#finishedRequests.delete(requestId);\n this.#requestPipelines.delete(requestId);\n }\n\n /** Emits 'end' with optional duration. */\n endRequest(requestId: string, durationMs?: number): void {\n this.releaseRequest(requestId);\n try { this.#logger?.info('[PipeX] Request ended', { requestId, durationMs }); } catch { /* logger isolation */ }\n this.emit('end', requestId, durationMs);\n }\n\n /** Emits 'progress'. */\n emitProgress(bytes: number, requestId: string): void {\n this.emit('progress', bytes, requestId);\n }\n\n /** Normalises unknown throws → Error and emits 'error'. */\n emitError(err: unknown, requestId: string): void {\n const error = err instanceof Error ? err : new Error(String(err));\n this.releaseRequest(requestId);\n try { this.#logger?.error('[PipeX] Request failed', { requestId, error: error.message }); } catch { /* logger isolation */ }\n if (this.listenerCount('error') > 0) this.emit('error', error, requestId);\n }\n\n // ── EventEmitter typed overrides ─────────────────────────────────────────────\n\n override emit<K extends keyof PipeXEventMap>(\n event: K,\n ...args: PipeXEventMap[K]\n ): boolean {\n const listeners = this.rawListeners(event);\n for (const listener of listeners) observe(() => Reflect.apply(listener, this, args));\n return listeners.length > 0;\n }\n\n override on<K extends keyof PipeXEventMap>(\n event: K,\n listener: (...args: PipeXEventMap[K]) => void,\n ): this {\n return super.on(event, listener as (...a: unknown[]) => void);\n }\n\n override once<K extends keyof PipeXEventMap>(\n event: K,\n listener: (...args: PipeXEventMap[K]) => void,\n ): this {\n return super.once(event, listener as (...a: unknown[]) => void);\n }\n}\n","import type { KmsOperation, KmsProvider, KmsProviderCapabilities } from './types.js';\nimport { InvalidKmsProviderCapabilityError, UnsupportedKmsOperationError } from './errors.js';\n\nconst OPERATIONS = ['encrypt', 'decrypt', 'generateDataKey'] as const satisfies readonly KmsOperation[];\n\n/**\n * Returns an immutable, runtime-validated view of a generic KMS provider.\n * Explicit false declarations support legacy provider stubs that exist only\n * to throw; such methods are never invoked through PipeX.\n */\nexport function getKmsProviderCapabilities(provider: KmsProvider): Readonly<KmsProviderCapabilities> {\n if (!provider || typeof provider !== 'object') throw new TypeError('[PipeX] Invalid KMS provider');\n if (provider.capabilities !== undefined\n && (!provider.capabilities || typeof provider.capabilities !== 'object')) {\n throw new TypeError('[PipeX] Invalid KMS provider capabilities');\n }\n\n const capabilities = {} as Record<KmsOperation, boolean>;\n for (const operation of OPERATIONS) {\n const declared = provider.capabilities?.[operation];\n const implemented = typeof provider[operation] === 'function';\n if (declared !== undefined && typeof declared !== 'boolean') {\n throw new InvalidKmsProviderCapabilityError(operation, 'MUST_BE_BOOLEAN');\n }\n if (declared === true && !implemented) {\n throw new InvalidKmsProviderCapabilityError(operation, 'MISSING_IMPLEMENTATION');\n }\n capabilities[operation] = declared ?? implemented;\n }\n return Object.freeze(capabilities);\n}\n\nexport function supportsKmsOperation(provider: KmsProvider, operation: KmsOperation): boolean {\n if (!OPERATIONS.includes(operation)) throw new TypeError('[PipeX] Unknown KMS operation');\n return getKmsProviderCapabilities(provider)[operation];\n}\n\nexport function assertKmsOperation(provider: KmsProvider, operation: KmsOperation): void {\n if (!supportsKmsOperation(provider, operation)) throw new UnsupportedKmsOperationError(operation);\n}\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { Transform } from 'node:stream';\nimport { BasePlugin } from '../core/plugin.js';\nimport { pluginInputLimit, pluginOutputLimit } from '../core/resourceLimits.js';\nimport type { ProcessorContext, StreamPluginContext } from '../core/types.js';\n\nexport type HashAlgorithm = 'sha256' | 'sha512';\n\nexport interface HashingOptions {\n algorithm: HashAlgorithm;\n secret: string;\n}\n\nconst HASH_LENGTHS: Record<HashAlgorithm, number> = {\n 'sha256': 32,\n 'sha512': 64,\n};\n\n/**\n * HashingPlugin — Standard library plugin for HMAC integrity checks.\n * Appends a digest to the end of the buffer/stream.\n */\nexport class HashingPlugin extends BasePlugin {\n public readonly name = 'hashing';\n public readonly version = '3.0.0';\n\n constructor(protected override options: HashingOptions) {\n super(options);\n if (!(options.algorithm in HASH_LENGTHS)) throw new Error('[PipeX] Hashing: unknown algorithm');\n if (!options.secret || options.secret.length < 16) {\n throw new Error('[PipeX] Hashing: Secret must be at least 16 characters');\n }\n }\n\n public override async process(data: Buffer, context: ProcessorContext): Promise<Buffer> {\n const maxInputBytes = pluginInputLimit(context);\n const maxOutputBytes = pluginOutputLimit(context);\n const digestLength = HASH_LENGTHS[this.options.algorithm];\n if (data.length > maxInputBytes) throw new Error(`[PipeX] Hashing input exceeds ${maxInputBytes} bytes`);\n if (data.length > maxOutputBytes - digestLength) {\n throw new Error(`[PipeX] Hashing output exceeds ${maxOutputBytes} bytes`);\n }\n context.metadata ??= {};\n const hmac = createHmac(this.options.algorithm, this.options.secret);\n const digest = hmac.update(data).digest();\n context.metadata['hmac'] = digest.toString('hex');\n const result = Buffer.concat([data, digest]);\n return result;\n }\n\n public override async reverse(data: Buffer, context: ProcessorContext): Promise<Buffer> {\n const len = HASH_LENGTHS[this.options.algorithm];\n const maxInputBytes = pluginInputLimit(context);\n const maxOutputBytes = pluginOutputLimit(context);\n if (data.length > maxInputBytes) throw new Error(`[PipeX] Hashing input exceeds ${maxInputBytes} bytes`);\n if (data.length < len) throw new Error('[PipeX] Hashing reverse: data too short');\n if (data.length - len > maxOutputBytes) throw new Error(`[PipeX] Hashing output exceeds ${maxOutputBytes} bytes`);\n\n const originalData = data.subarray(0, data.length - len);\n const attachedHash = data.subarray(data.length - len);\n\n const hmac = createHmac(this.options.algorithm, this.options.secret);\n const expected = hmac.update(originalData).digest();\n try {\n if (!timingSafeEqual(attachedHash, expected)) {\n throw new Error('[PipeX] Hashing: HMAC verification failed');\n }\n\n context.metadata ??= {};\n context.metadata['verified_hmac'] = attachedHash.toString('hex');\n return originalData;\n } finally {\n expected.fill(0);\n }\n }\n\n public createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Transform {\n const { algorithm, secret } = this.options;\n const hmac = createHmac(algorithm, secret);\n const len = HASH_LENGTHS[algorithm];\n const maxInputBytes = pluginInputLimit(context);\n const maxOutputBytes = pluginOutputLimit(context);\n\n if (mode === 'compress') {\n let total = 0;\n return new Transform({\n construct(callback) {\n callback(maxOutputBytes < len\n ? new Error(`[PipeX] Hashing output exceeds ${maxOutputBytes} bytes`)\n : undefined);\n },\n transform(chunk: Buffer, _enc, cb) {\n if (chunk.length > maxInputBytes - total) {\n return cb(new Error(`[PipeX] Hashing input exceeds ${maxInputBytes} bytes`));\n }\n if (chunk.length > maxOutputBytes - len - total) {\n return cb(new Error(`[PipeX] Hashing output exceeds ${maxOutputBytes} bytes`));\n }\n total += chunk.length;\n hmac.update(chunk);\n this.push(chunk);\n cb();\n },\n flush(cb) {\n this.push(hmac.digest());\n cb();\n }\n });\n } else {\n // Verification mode\n let chunks: Buffer[] = [];\n let total = 0;\n\n return new Transform({\n transform(chunk: Buffer, _enc, cb) {\n if (chunk.length > maxInputBytes - total) {\n return cb(new Error(`[PipeX] Hashing input exceeds ${maxInputBytes} bytes`));\n }\n total += chunk.length;\n chunks.push(chunk);\n cb();\n },\n flush(cb) {\n const buffer = Buffer.concat(chunks, total);\n chunks = [];\n let expected: Buffer | undefined;\n try {\n if (buffer.length < len) throw new Error('[PipeX] Hashing stream: No HMAC found');\n const originalData = buffer.subarray(0, buffer.length - len);\n if (originalData.length > maxOutputBytes) throw new Error(`[PipeX] Hashing output exceeds ${maxOutputBytes} bytes`);\n const attachedHash = buffer.subarray(buffer.length - len);\n hmac.update(originalData);\n expected = hmac.digest();\n if (!timingSafeEqual(attachedHash, expected)) {\n throw new Error('[PipeX] Hashing stream: HMAC verification failed');\n }\n const authenticated = Buffer.from(originalData);\n buffer.fill(0);\n this.push(authenticated);\n cb();\n } catch (error) {\n buffer.fill(0);\n cb(error as Error);\n } finally {\n expected?.fill(0);\n }\n },\n destroy(error, callback) { chunks = []; callback(error); },\n });\n }\n }\n}\n","import {\n createCipheriv,\n createDecipheriv,\n hkdfSync,\n randomBytes,\n type CipherGCM,\n type DecipherGCM,\n} from 'node:crypto';\nimport { Transform, type TransformCallback } from 'node:stream';\nimport { DEFAULT_LIMITS, pluginInputLimit, pluginOutputLimit } from '../core/resourceLimits.js';\nimport type { ProcessorContext, StreamPluginContext } from '../core/types.js';\n\nexport type EncryptionAlgorithm = 'aes-256-gcm' | 'chacha20-poly1305';\n\nexport interface EncryptionFormatOptions {\n readonly algorithm: EncryptionAlgorithm;\n readonly key: Buffer;\n readonly frameSizeBytes?: number;\n readonly allowLegacyDecrypt?: boolean;\n}\n\nconst MAGIC = Buffer.from('PXAE');\nconst VERSION = 1;\nconst GLOBAL_HEADER_LENGTH = 28;\nconst FRAME_HEADER_LENGTH = 13;\nconst TAG_LENGTH = 16;\nconst FRAME_OVERHEAD = FRAME_HEADER_LENGTH + TAG_LENGTH;\nconst DEFAULT_PLAINTEXT_FRAME_BYTES = 64 * 1024;\nconst DATA_FRAME = 1;\nconst FINAL_FRAME = 2;\nconst LEGACY_HEADER_LENGTH = 1 + 12 + TAG_LENGTH;\n\nconst ALGORITHM_IDS: Record<EncryptionAlgorithm, number> = {\n 'aes-256-gcm': 1,\n 'chacha20-poly1305': 2,\n};\nconst ID_TO_ALGORITHM: Record<number, EncryptionAlgorithm> = {\n 1: 'aes-256-gcm',\n 2: 'chacha20-poly1305',\n};\n\ninterface FormatLimits {\n readonly maxInputBytes: number;\n readonly maxOutputBytes: number;\n readonly maxFrameBytes: number;\n readonly maxFrames: number;\n}\n\ninterface ParsedHeader {\n readonly bytes: Buffer;\n readonly algorithm: EncryptionAlgorithm;\n readonly frameSizeBytes: number;\n readonly salt: Buffer;\n}\n\nfunction limitsFor(context?: ProcessorContext | StreamPluginContext): FormatLimits {\n return {\n maxInputBytes: pluginInputLimit(context),\n maxOutputBytes: pluginOutputLimit(context),\n maxFrameBytes: context?.limits?.maxFrameBytes ?? DEFAULT_LIMITS.maxFrameBytes,\n maxFrames: context?.limits?.maxFrames ?? DEFAULT_LIMITS.maxFrames,\n };\n}\n\nfunction resolveFrameSize(options: EncryptionFormatOptions, limits: FormatLimits): number {\n const capacity = limits.maxFrameBytes - FRAME_OVERHEAD;\n if (capacity < 1 || limits.maxFrameBytes < GLOBAL_HEADER_LENGTH) {\n throw new Error(`[PipeX] Encryption frame limit ${limits.maxFrameBytes} bytes is too small`);\n }\n const requested = options.frameSizeBytes ?? Math.min(DEFAULT_PLAINTEXT_FRAME_BYTES, capacity);\n if (!Number.isSafeInteger(requested) || requested < 1 || requested > 0xffff_ffff) {\n throw new Error('[PipeX] Encryption frameSizeBytes must be a positive 32-bit integer');\n }\n if (requested > capacity) {\n throw new Error(`[PipeX] Encryption frameSizeBytes exceeds the ${limits.maxFrameBytes}-byte frame limit`);\n }\n return requested;\n}\n\nfunction encodedLength(plaintextBytes: number, frameSizeBytes: number): number {\n const dataFrames = plaintextBytes === 0 ? 0 : Math.ceil(plaintextBytes / frameSizeBytes);\n return GLOBAL_HEADER_LENGTH + plaintextBytes + (dataFrames + 1) * FRAME_OVERHEAD;\n}\n\nfunction dataFrameCount(plaintextBytes: number, frameSizeBytes: number): number {\n return plaintextBytes === 0 ? 0 : Math.ceil(plaintextBytes / frameSizeBytes);\n}\n\nfunction buildHeader(algorithm: EncryptionAlgorithm, frameSizeBytes: number, salt = randomBytes(16)): Buffer {\n const header = Buffer.alloc(GLOBAL_HEADER_LENGTH);\n MAGIC.copy(header, 0);\n header.writeUInt8(VERSION, 4);\n header.writeUInt8(ALGORITHM_IDS[algorithm], 5);\n header.writeUInt16BE(0, 6);\n header.writeUInt32BE(frameSizeBytes, 8);\n salt.copy(header, 12);\n return header;\n}\n\nfunction parseHeader(header: Buffer, limits: FormatLimits): ParsedHeader {\n if (header.length !== GLOBAL_HEADER_LENGTH || !header.subarray(0, 4).equals(MAGIC)) {\n throw new Error('[PipeX] Decryption failed: invalid framed header');\n }\n if (header.readUInt8(4) !== VERSION) throw new Error('[PipeX] Decryption failed: unsupported format version');\n const algorithm = ID_TO_ALGORITHM[header.readUInt8(5)];\n if (!algorithm || header.readUInt16BE(6) !== 0) throw new Error('[PipeX] Decryption failed: invalid framed header');\n const frameSizeBytes = header.readUInt32BE(8);\n if (frameSizeBytes < 1 || frameSizeBytes > limits.maxFrameBytes - FRAME_OVERHEAD) {\n throw new Error('[PipeX] Decryption failed: invalid frame size');\n }\n return { bytes: header, algorithm, frameSizeBytes, salt: header.subarray(12, 28) };\n}\n\nfunction deriveKey(key: Buffer, header: ParsedHeader): Buffer {\n const info = Buffer.from(`PipeX AEAD framed v${VERSION}:${header.algorithm}`, 'utf8');\n return Buffer.from(hkdfSync('sha256', key, header.salt, info, 32));\n}\n\nfunction nonceFor(sequence: bigint): Buffer {\n if (sequence < 0n || sequence > 0xffff_ffff_ffff_ffffn) {\n throw new Error('[PipeX] Encryption frame sequence exhausted');\n }\n const nonce = Buffer.alloc(12);\n nonce.writeBigUInt64BE(sequence, 4);\n return nonce;\n}\n\nfunction buildFrameHeader(type: number, sequence: bigint, ciphertextBytes: number): Buffer {\n const header = Buffer.alloc(FRAME_HEADER_LENGTH);\n header.writeUInt8(type, 0);\n header.writeBigUInt64BE(sequence, 1);\n header.writeUInt32BE(ciphertextBytes, 9);\n return header;\n}\n\nfunction encryptFrame(\n plaintext: Buffer,\n type: number,\n sequence: bigint,\n algorithm: EncryptionAlgorithm,\n key: Buffer,\n globalHeader: Buffer,\n): Buffer {\n const frameHeader = buildFrameHeader(type, sequence, plaintext.length);\n const nonce = nonceFor(sequence);\n try {\n const cipher = createCipheriv(algorithm, key, nonce, { authTagLength: TAG_LENGTH } as any) as CipherGCM;\n cipher.setAAD(Buffer.concat([globalHeader, frameHeader]));\n const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);\n return Buffer.concat([frameHeader, ciphertext, cipher.getAuthTag()], FRAME_OVERHEAD + ciphertext.length);\n } finally {\n nonce.fill(0);\n }\n}\n\nfunction decryptFrame(\n ciphertext: Buffer,\n tag: Buffer,\n frameHeader: Buffer,\n sequence: bigint,\n algorithm: EncryptionAlgorithm,\n key: Buffer,\n globalHeader: Buffer,\n): Buffer {\n const nonce = nonceFor(sequence);\n const decipher = createDecipheriv(algorithm, key, nonce, { authTagLength: TAG_LENGTH } as any) as DecipherGCM;\n decipher.setAAD(Buffer.concat([globalHeader, frameHeader]));\n decipher.setAuthTag(tag);\n const pending = decipher.update(ciphertext);\n try {\n const final = decipher.final();\n return final.length === 0 ? pending : Buffer.concat([pending, final]);\n } catch {\n pending.fill(0);\n throw new Error('[PipeX] Decryption failed: authentication failed');\n } finally {\n nonce.fill(0);\n }\n}\n\nfunction decryptLegacy(data: Buffer, key: Buffer, limits: FormatLimits): Buffer {\n if (data.length < LEGACY_HEADER_LENGTH) throw new Error('[PipeX] Decryption failed: packet too short');\n if (data.length - LEGACY_HEADER_LENGTH > limits.maxOutputBytes) {\n throw new Error(`[PipeX] Decryption output exceeds ${limits.maxOutputBytes} bytes`);\n }\n const algorithm = ID_TO_ALGORITHM[data.readUInt8(0)];\n if (!algorithm) throw new Error('[PipeX] Decryption failed: unknown legacy algorithm');\n const decipher = createDecipheriv(algorithm, key, data.subarray(1, 13), { authTagLength: TAG_LENGTH } as any) as DecipherGCM;\n decipher.setAuthTag(data.subarray(13, LEGACY_HEADER_LENGTH));\n const pending = decipher.update(data.subarray(LEGACY_HEADER_LENGTH));\n try {\n const final = decipher.final();\n return final.length === 0 ? pending : Buffer.concat([pending, final]);\n } catch {\n pending.fill(0);\n throw new Error('[PipeX] Decryption failed: authentication failed');\n }\n}\n\nexport function isFramedEncryption(data: Buffer): boolean {\n return data.length >= MAGIC.length && data.subarray(0, MAGIC.length).equals(MAGIC);\n}\n\nexport function encryptBuffer(data: Buffer, options: EncryptionFormatOptions, context?: ProcessorContext): Buffer {\n const limits = limitsFor(context);\n if (data.length > limits.maxInputBytes) throw new Error(`[PipeX] Encryption input exceeds ${limits.maxInputBytes} bytes`);\n const frameSizeBytes = resolveFrameSize(options, limits);\n if (dataFrameCount(data.length, frameSizeBytes) > limits.maxFrames) {\n throw new Error(`[PipeX] Encryption frame count exceeds ${limits.maxFrames}`);\n }\n const outputLength = encodedLength(data.length, frameSizeBytes);\n if (outputLength > limits.maxOutputBytes) throw new Error(`[PipeX] Encryption output exceeds ${limits.maxOutputBytes} bytes`);\n const header = buildHeader(options.algorithm, frameSizeBytes);\n const parsed = parseHeader(header, limits);\n const derivedKey = deriveKey(options.key, parsed);\n const frames: Buffer[] = [header];\n let sequence = 0n;\n try {\n for (let offset = 0; offset < data.length; offset += frameSizeBytes) {\n frames.push(encryptFrame(data.subarray(offset, Math.min(data.length, offset + frameSizeBytes)), DATA_FRAME, sequence++, options.algorithm, derivedKey, header));\n }\n frames.push(encryptFrame(Buffer.alloc(0), FINAL_FRAME, sequence, options.algorithm, derivedKey, header));\n return Buffer.concat(frames, outputLength);\n } finally {\n derivedKey.fill(0);\n }\n}\n\nexport function decryptBuffer(data: Buffer, options: EncryptionFormatOptions, context?: ProcessorContext): Buffer {\n const limits = limitsFor(context);\n if (data.length > limits.maxInputBytes) throw new Error(`[PipeX] Decryption input exceeds ${limits.maxInputBytes} bytes`);\n // Legacy packets always start with algorithm id 1 or 2. Reserve the magic\n // prefix byte so truncated framed packets cannot be misclassified as legacy.\n if (data.length === 0 || (!isFramedEncryption(data) && data.readUInt8(0) !== MAGIC.readUInt8(0))) {\n if (options.allowLegacyDecrypt === false) throw new Error('[PipeX] Decryption failed: legacy format disabled');\n return decryptLegacy(data, options.key, limits);\n }\n if (data.length < GLOBAL_HEADER_LENGTH) throw new Error('[PipeX] Decryption failed: incomplete framed header');\n const header = parseHeader(data.subarray(0, GLOBAL_HEADER_LENGTH), limits);\n const derivedKey = deriveKey(options.key, header);\n const plaintext: Buffer[] = [];\n let plaintextBytes = 0;\n let position = GLOBAL_HEADER_LENGTH;\n let expectedSequence = 0n;\n let dataFrames = 0;\n let finalSeen = false;\n try {\n while (position < data.length) {\n if (finalSeen || data.length - position < FRAME_HEADER_LENGTH) throw new Error('[PipeX] Decryption failed: incomplete or trailing frame');\n const frameHeader = data.subarray(position, position + FRAME_HEADER_LENGTH);\n position += FRAME_HEADER_LENGTH;\n const type = frameHeader.readUInt8(0);\n const sequence = frameHeader.readBigUInt64BE(1);\n const ciphertextBytes = frameHeader.readUInt32BE(9);\n if (sequence !== expectedSequence) throw new Error('[PipeX] Decryption failed: invalid frame sequence');\n if (type !== DATA_FRAME && type !== FINAL_FRAME) throw new Error('[PipeX] Decryption failed: invalid frame type');\n if (type === FINAL_FRAME && ciphertextBytes !== 0) throw new Error('[PipeX] Decryption failed: invalid final frame');\n if (ciphertextBytes > header.frameSizeBytes || ciphertextBytes > limits.maxFrameBytes - FRAME_OVERHEAD) throw new Error('[PipeX] Decryption failed: frame length exceeds configured limit');\n if (type === DATA_FRAME && dataFrames >= limits.maxFrames) throw new Error(`[PipeX] Encryption frame count exceeds ${limits.maxFrames}`);\n if (type === DATA_FRAME && ciphertextBytes > limits.maxOutputBytes - plaintextBytes) {\n throw new Error(`[PipeX] Decryption output exceeds ${limits.maxOutputBytes} bytes`);\n }\n if (data.length - position < ciphertextBytes + TAG_LENGTH) throw new Error('[PipeX] Decryption failed: incomplete frame');\n const ciphertext = data.subarray(position, position + ciphertextBytes);\n position += ciphertextBytes;\n const tag = data.subarray(position, position + TAG_LENGTH);\n position += TAG_LENGTH;\n const restored = decryptFrame(ciphertext, tag, frameHeader, sequence, header.algorithm, derivedKey, header.bytes);\n if (type === FINAL_FRAME) {\n restored.fill(0);\n finalSeen = true;\n } else {\n dataFrames++;\n plaintextBytes += restored.length;\n plaintext.push(restored);\n }\n expectedSequence++;\n }\n if (!finalSeen) throw new Error('[PipeX] Decryption failed: missing authenticated final frame');\n const result = Buffer.concat(plaintext, plaintextBytes);\n for (const chunk of plaintext) chunk.fill(0);\n return result;\n } catch (error) {\n for (const chunk of plaintext) chunk.fill(0);\n throw error;\n } finally {\n derivedKey.fill(0);\n }\n}\n\nexport function createEncryptionStream(options: EncryptionFormatOptions, context?: StreamPluginContext): Transform {\n const limits = limitsFor(context);\n const frameSizeBytes = resolveFrameSize(options, limits);\n if (encodedLength(0, frameSizeBytes) > limits.maxOutputBytes) throw new Error(`[PipeX] Encryption output exceeds ${limits.maxOutputBytes} bytes`);\n const header = buildHeader(options.algorithm, frameSizeBytes);\n const parsed = parseHeader(header, limits);\n const derivedKey = deriveKey(options.key, parsed);\n let pending = Buffer.alloc(frameSizeBytes);\n let pendingBytes = 0;\n let inputBytes = 0;\n let dataFrames = 0;\n let sequence = 0n;\n let headerSent = false;\n const cleanup = () => { pending.fill(0); derivedKey.fill(0); };\n\n return new Transform({\n transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {\n try {\n const input = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n if (input.length > limits.maxInputBytes - inputBytes) throw new Error(`[PipeX] Encryption input exceeds ${limits.maxInputBytes} bytes`);\n const prospectiveInput = inputBytes + input.length;\n if (dataFrameCount(prospectiveInput, frameSizeBytes) > limits.maxFrames) {\n throw new Error(`[PipeX] Encryption frame count exceeds ${limits.maxFrames}`);\n }\n if (encodedLength(prospectiveInput, frameSizeBytes) > limits.maxOutputBytes) throw new Error(`[PipeX] Encryption output exceeds ${limits.maxOutputBytes} bytes`);\n inputBytes = prospectiveInput;\n if (!headerSent) { this.push(header); headerSent = true; }\n let offset = 0;\n while (offset < input.length) {\n const copied = Math.min(frameSizeBytes - pendingBytes, input.length - offset);\n input.copy(pending, pendingBytes, offset, offset + copied);\n pendingBytes += copied;\n offset += copied;\n if (pendingBytes === frameSizeBytes) {\n if (++dataFrames > limits.maxFrames) throw new Error(`[PipeX] Encryption frame count exceeds ${limits.maxFrames}`);\n this.push(encryptFrame(pending, DATA_FRAME, sequence++, options.algorithm, derivedKey, header));\n pending.fill(0);\n pendingBytes = 0;\n }\n }\n callback();\n } catch (error) {\n cleanup();\n callback(error as Error);\n }\n },\n flush(callback: TransformCallback) {\n try {\n if (!headerSent) { this.push(header); headerSent = true; }\n if (pendingBytes > 0) {\n if (++dataFrames > limits.maxFrames) throw new Error(`[PipeX] Encryption frame count exceeds ${limits.maxFrames}`);\n this.push(encryptFrame(pending.subarray(0, pendingBytes), DATA_FRAME, sequence++, options.algorithm, derivedKey, header));\n }\n this.push(encryptFrame(Buffer.alloc(0), FINAL_FRAME, sequence, options.algorithm, derivedKey, header));\n cleanup();\n callback();\n } catch (error) {\n cleanup();\n callback(error as Error);\n }\n },\n destroy(error, callback) { cleanup(); callback(error); },\n });\n}\n\nexport function createDecryptionStream(options: EncryptionFormatOptions, context?: StreamPluginContext): Transform {\n const limits = limitsFor(context);\n let format: 'unknown' | 'framed' | 'legacy' = 'unknown';\n let totalInput = 0;\n let totalOutput = 0;\n const globalHeader = Buffer.alloc(GLOBAL_HEADER_LENGTH);\n let globalHeaderBytes = 0;\n let parsedHeader: ParsedHeader | undefined;\n let derivedKey: Buffer | undefined;\n const frameHeader = Buffer.alloc(FRAME_HEADER_LENGTH);\n let frameHeaderBytes = 0;\n let frameBody: Buffer | undefined;\n let frameBodyBytes = 0;\n let expectedSequence = 0n;\n let dataFrames = 0;\n let finalSeen = false;\n let legacyChunks: Buffer[] = [];\n const cleanup = () => {\n derivedKey?.fill(0);\n frameBody?.fill(0);\n globalHeader.fill(0);\n frameHeader.fill(0);\n legacyChunks = [];\n };\n\n const consumeFramed = (input: Buffer, stream: Transform): void => {\n let offset = 0;\n while (offset < input.length) {\n if (finalSeen) throw new Error('[PipeX] Decryption failed: trailing data after final frame');\n if (!parsedHeader) {\n const copied = Math.min(GLOBAL_HEADER_LENGTH - globalHeaderBytes, input.length - offset);\n input.copy(globalHeader, globalHeaderBytes, offset, offset + copied);\n globalHeaderBytes += copied;\n offset += copied;\n if (globalHeaderBytes === GLOBAL_HEADER_LENGTH) {\n parsedHeader = parseHeader(globalHeader, limits);\n derivedKey = deriveKey(options.key, parsedHeader);\n }\n continue;\n }\n if (frameHeaderBytes < FRAME_HEADER_LENGTH) {\n const copied = Math.min(FRAME_HEADER_LENGTH - frameHeaderBytes, input.length - offset);\n input.copy(frameHeader, frameHeaderBytes, offset, offset + copied);\n frameHeaderBytes += copied;\n offset += copied;\n if (frameHeaderBytes < FRAME_HEADER_LENGTH) continue;\n const type = frameHeader.readUInt8(0);\n const sequence = frameHeader.readBigUInt64BE(1);\n const ciphertextBytes = frameHeader.readUInt32BE(9);\n if (sequence !== expectedSequence) throw new Error('[PipeX] Decryption failed: invalid frame sequence');\n if (type !== DATA_FRAME && type !== FINAL_FRAME) throw new Error('[PipeX] Decryption failed: invalid frame type');\n if (type === FINAL_FRAME && ciphertextBytes !== 0) throw new Error('[PipeX] Decryption failed: invalid final frame');\n if (ciphertextBytes > parsedHeader.frameSizeBytes || ciphertextBytes > limits.maxFrameBytes - FRAME_OVERHEAD) throw new Error('[PipeX] Decryption failed: frame length exceeds configured limit');\n if (type === DATA_FRAME && dataFrames >= limits.maxFrames) throw new Error(`[PipeX] Encryption frame count exceeds ${limits.maxFrames}`);\n if (type === DATA_FRAME && ciphertextBytes > limits.maxOutputBytes - totalOutput) {\n throw new Error(`[PipeX] Decryption output exceeds ${limits.maxOutputBytes} bytes`);\n }\n frameBody = Buffer.alloc(ciphertextBytes + TAG_LENGTH);\n frameBodyBytes = 0;\n }\n const copied = Math.min(frameBody!.length - frameBodyBytes, input.length - offset);\n input.copy(frameBody!, frameBodyBytes, offset, offset + copied);\n frameBodyBytes += copied;\n offset += copied;\n if (frameBodyBytes < frameBody!.length) continue;\n const type = frameHeader.readUInt8(0);\n const sequence = frameHeader.readBigUInt64BE(1);\n const ciphertextBytes = frameHeader.readUInt32BE(9);\n const restored = decryptFrame(frameBody!.subarray(0, ciphertextBytes), frameBody!.subarray(ciphertextBytes), frameHeader, sequence, parsedHeader.algorithm, derivedKey!, parsedHeader.bytes);\n if (type === FINAL_FRAME) {\n restored.fill(0);\n finalSeen = true;\n } else {\n dataFrames++;\n totalOutput += restored.length;\n stream.push(restored);\n }\n expectedSequence++;\n frameBody!.fill(0);\n frameBody = undefined;\n frameBodyBytes = 0;\n frameHeader.fill(0);\n frameHeaderBytes = 0;\n }\n };\n\n return new Transform({\n transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {\n try {\n const input = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n if (input.length > limits.maxInputBytes - totalInput) throw new Error(`[PipeX] Decryption input exceeds ${limits.maxInputBytes} bytes`);\n totalInput += input.length;\n if (input.length === 0) return callback();\n if (format === 'unknown') {\n format = input.readUInt8(0) === MAGIC.readUInt8(0) ? 'framed' : 'legacy';\n if (format === 'legacy' && options.allowLegacyDecrypt === false) throw new Error('[PipeX] Decryption failed: legacy format disabled');\n }\n if (format === 'legacy') legacyChunks.push(input);\n else consumeFramed(input, this);\n callback();\n } catch (error) {\n cleanup();\n callback(error as Error);\n }\n },\n flush(callback: TransformCallback) {\n try {\n if (format === 'legacy') {\n const restored = decryptLegacy(Buffer.concat(legacyChunks, totalInput), options.key, limits);\n this.push(restored);\n cleanup();\n return callback();\n }\n if (format !== 'framed' || !parsedHeader || frameHeaderBytes !== 0 || frameBody) throw new Error('[PipeX] Decryption failed: incomplete encrypted stream');\n if (!finalSeen) throw new Error('[PipeX] Decryption failed: missing authenticated final frame');\n cleanup();\n callback();\n } catch (error) {\n cleanup();\n callback(error as Error);\n }\n },\n destroy(error, callback) { cleanup(); callback(error); },\n });\n}\n","import type { Transform } from 'node:stream';\nimport { BasePlugin } from '../core/plugin.js';\nimport type { ProcessorContext, StreamPluginContext } from '../core/types.js';\nimport {\n createDecryptionStream,\n createEncryptionStream,\n decryptBuffer,\n encryptBuffer,\n type EncryptionFormatOptions,\n} from './encryptionFormat.js';\n\nexport type { EncryptionAlgorithm } from './encryptionFormat.js';\n\nexport interface EncryptionOptions extends EncryptionFormatOptions {\n /** Maximum plaintext bytes in each authenticated frame. Defaults to 64 KiB. */\n frameSizeBytes?: number;\n /** Temporarily accept the unversioned v3 format while migrating. Defaults to true. */\n allowLegacyDecrypt?: boolean;\n}\n\n/**\n * Authenticated, bounded-memory stream encryption.\n *\n * Version 4 writes the versioned PXAE framed format. The legacy unversioned\n * format remains readable by default for migration, but is never written.\n */\nexport class EncryptionPlugin extends BasePlugin {\n public readonly name = 'encryption';\n public readonly version = '4.0.0';\n\n constructor(protected override options: EncryptionOptions) {\n super(options);\n if (!options || !['aes-256-gcm', 'chacha20-poly1305'].includes(options.algorithm)\n || !Buffer.isBuffer(options.key) || options.key.length !== 32) {\n throw new Error('[PipeX] Encryption: invalid algorithm or key');\n }\n if (options.frameSizeBytes !== undefined\n && (!Number.isSafeInteger(options.frameSizeBytes)\n || options.frameSizeBytes < 1\n || options.frameSizeBytes > 0xffff_ffff)) {\n throw new Error('[PipeX] Encryption frameSizeBytes must be a positive 32-bit integer');\n }\n if (options.allowLegacyDecrypt !== undefined && typeof options.allowLegacyDecrypt !== 'boolean') {\n throw new Error('[PipeX] Encryption allowLegacyDecrypt must be a boolean');\n }\n }\n\n public override async process(data: Buffer, context: ProcessorContext): Promise<Buffer> {\n return encryptBuffer(data, this.options, context);\n }\n\n public override async reverse(data: Buffer, context: ProcessorContext): Promise<Buffer> {\n return decryptBuffer(data, this.options, context);\n }\n\n public createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Transform {\n return mode === 'compress'\n ? createEncryptionStream(this.options, context)\n : createDecryptionStream(this.options, context);\n }\n}\n","import { \n gzip, gunzip, createGzip, createGunzip,\n brotliCompress, brotliDecompress, createBrotliCompress, createBrotliDecompress,\n constants as zlibConstants\n} from 'node:zlib';\nimport { promisify } from 'node:util';\nimport { compose, Duplex, PassThrough, Readable, Transform, type TransformCallback } from 'node:stream';\nimport { BasePlugin } from '../core/plugin.js';\nimport { buildByteLimitTransform } from '../core/core.js';\nimport { pluginInputLimit, pluginOutputLimit } from '../core/resourceLimits.js';\nimport type { ProcessorContext, StreamPluginContext } from '../core/types.js';\n\nexport type CompressionType = 'gzip' | 'brotli' | 'none';\n\nexport interface CompressionOptions {\n type: CompressionType;\n level?: number;\n}\n\nconst TYPE_BYTE_MAP: Record<CompressionType, number> = {\n 'none': 0,\n 'gzip': 1,\n 'brotli': 2,\n};\n\nconst ID_TO_TYPE: Record<number, CompressionType> = {\n 0: 'none',\n 1: 'gzip',\n 2: 'brotli',\n};\nconst gzipAsync = promisify(gzip);\nconst gunzipAsync = promisify(gunzip);\nconst brotliCompressAsync = promisify(brotliCompress);\nconst brotliDecompressAsync = promisify(brotliDecompress);\n\n/**\n * CompressionPlugin — Standard library plugin for Gzip and Brotli.\n * Prepends a 1-byte header to identify the compression type.\n */\nexport class CompressionPlugin extends BasePlugin {\n public readonly name = 'compression';\n public readonly version = '3.0.0';\n\n constructor(protected override options: CompressionOptions) {\n super(options);\n if (!(options.type in TYPE_BYTE_MAP)) throw new Error('[PipeX] Compression: unknown type');\n if (options.level !== undefined && !Number.isInteger(options.level)) {\n throw new Error('[PipeX] Compression: level must be an integer');\n }\n if (options.type === 'gzip' && options.level !== undefined && (options.level < 0 || options.level > 9)) {\n throw new Error('[PipeX] Compression: gzip level must be between 0 and 9');\n }\n if (options.type === 'brotli' && options.level !== undefined && (options.level < 0 || options.level > 11)) {\n throw new Error('[PipeX] Compression: Brotli level must be between 0 and 11');\n }\n if (options.type === 'none' && options.level !== undefined) {\n throw new Error('[PipeX] Compression: level is not supported when type is none');\n }\n }\n\n public override async process(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n const maxInputBytes = pluginInputLimit(ctx);\n const maxOutputBytes = pluginOutputLimit(ctx);\n if (data.length > maxInputBytes) throw new Error(`[PipeX] Compression input exceeds ${maxInputBytes} bytes`);\n const { type, level } = this.options;\n const header = Buffer.from([TYPE_BYTE_MAP[type]]);\n if (data.length > maxOutputBytes - header.length && type === 'none') {\n throw new Error(`[PipeX] Compression output exceeds ${maxOutputBytes} bytes`);\n }\n if (maxOutputBytes <= header.length && type !== 'none') {\n throw new Error(`[PipeX] Compression output exceeds ${maxOutputBytes} bytes`);\n }\n\n let compressed: Buffer;\n if (type === 'gzip') {\n compressed = await gzipAsync(data, { level: level ?? 6, maxOutputLength: maxOutputBytes - header.length });\n } else if (type === 'brotli') {\n compressed = await brotliCompressAsync(data, {\n params: { [zlibConstants.BROTLI_PARAM_QUALITY]: level ?? 11 },\n maxOutputLength: maxOutputBytes - header.length,\n });\n } else {\n compressed = data;\n }\n\n return Buffer.concat([header, compressed]);\n }\n\n public override async reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n const maxInputBytes = pluginInputLimit(ctx);\n const maxOutputBytes = pluginOutputLimit(ctx);\n if (data.length > maxInputBytes) throw new Error(`[PipeX] Compression input exceeds ${maxInputBytes} bytes`);\n if (data.length < 1) throw new Error('[PipeX] Compression reverse: packet too short');\n \n const typeId = data.readUInt8(0);\n const type = ID_TO_TYPE[typeId];\n const payload = data.subarray(1);\n\n if (type === 'gzip') {\n const out = await gunzipAsync(payload, { maxOutputLength: maxOutputBytes });\n return out;\n }\n if (type === 'brotli') {\n const out = await brotliDecompressAsync(payload, { maxOutputLength: maxOutputBytes });\n return out;\n }\n if (type !== 'none') throw new Error('[PipeX] Compression: unknown type');\n if (payload.length > maxOutputBytes) throw new Error(`[PipeX] Compression output exceeds ${maxOutputBytes} bytes`);\n return payload;\n }\n\n public createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex {\n const { type, level } = this.options;\n const maxInputBytes = pluginInputLimit(context);\n const maxOutputBytes = pluginOutputLimit(context);\n\n if (mode === 'compress') {\n const compressor = type === 'gzip'\n ? createGzip({ level: level ?? 6 })\n : type === 'brotli'\n ? createBrotliCompress({ params: { [zlibConstants.BROTLI_PARAM_QUALITY]: level ?? 11 } })\n : new PassThrough();\n let headerSent = false;\n const prependHeader = new Transform({\n transform(chunk: Buffer, _enc: BufferEncoding, cb: TransformCallback) {\n if (!headerSent) {\n headerSent = true;\n this.push(Buffer.from([TYPE_BYTE_MAP[type]]));\n }\n cb(null, chunk);\n },\n flush(cb: TransformCallback) {\n if (!headerSent) this.push(Buffer.from([TYPE_BYTE_MAP[type]]));\n cb();\n },\n });\n return compose(\n buildByteLimitTransform(maxInputBytes, 'compression input'),\n compressor,\n prependHeader,\n buildByteLimitTransform(maxOutputBytes, 'compression output'),\n );\n }\n\n return Duplex.from(async function* (source: AsyncIterable<Buffer | Uint8Array>) {\n const iterator = source[Symbol.asyncIterator]();\n let first: Buffer | undefined;\n let inputBytes = 0;\n let outputBytes = 0;\n while (!first) {\n const next = await iterator.next();\n if (next.done) throw new Error('[PipeX] Stream decompression: packet too short');\n const chunk = Buffer.isBuffer(next.value) ? next.value : Buffer.from(next.value);\n if (chunk.length > maxInputBytes - inputBytes) {\n throw new Error(`[PipeX] Compression input exceeds ${maxInputBytes} bytes`);\n }\n inputBytes += chunk.length;\n if (chunk.length > 0) first = chunk;\n }\n\n const detectedType = ID_TO_TYPE[first.readUInt8(0)];\n if (!detectedType) throw new Error('[PipeX] Stream decompression: unknown type');\n const decompressor = detectedType === 'gzip'\n ? createGunzip()\n : detectedType === 'brotli'\n ? createBrotliDecompress()\n : new PassThrough();\n\n async function* payload(): AsyncGenerator<Buffer> {\n const remainder = first!.subarray(1);\n if (remainder.length > 0) yield remainder;\n while (true) {\n const next = await iterator.next();\n if (next.done) return;\n const chunk = Buffer.isBuffer(next.value) ? next.value : Buffer.from(next.value);\n if (chunk.length > maxInputBytes - inputBytes) {\n throw new Error(`[PipeX] Compression input exceeds ${maxInputBytes} bytes`);\n }\n inputBytes += chunk.length;\n if (chunk.length > 0) yield chunk;\n }\n }\n\n try {\n for await (const chunk of compose(Readable.from(payload()), decompressor)) {\n const output = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n if (output.length > maxOutputBytes - outputBytes) {\n throw new Error(`[PipeX] Compression output exceeds ${maxOutputBytes} bytes`);\n }\n outputBytes += output.length;\n yield output;\n }\n } finally {\n decompressor.destroy();\n try { await iterator.return?.(); } catch { /* preserve the primary stream error */ }\n }\n });\n }\n}\n","import { BasePlugin } from '../core/plugin.js';\nimport type { ProcessorContext } from '../core/types.js';\n\n/**\n * BenchmarkPlugin — Standard library plugin for monitoring data throughput.\n * Records input/output byte counts in context metadata.\n */\nexport class BenchmarkPlugin extends BasePlugin {\n public readonly name = 'benchmark';\n public readonly version = '2.0.0';\n\n public override async process(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n ctx.metadata ??= {};\n const start = ctx.metadata['benchmark:start'] as number || Date.now();\n ctx.metadata['benchmark:in_bytes'] = data.length;\n ctx.metadata['benchmark:start'] = start;\n return data;\n }\n\n public override async reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n ctx.metadata ??= {};\n ctx.metadata['benchmark:out_bytes'] = data.length;\n const start = ctx.metadata['benchmark:start'] as number;\n if (start) {\n ctx.metadata['benchmark:duration_ms'] = Date.now() - start;\n }\n return data;\n }\n}\n","import { fileURLToPath } from 'node:url';\nimport { availableParallelism } from 'node:os';\nimport { Transform, type TransformCallback } from 'node:stream';\nimport { Piscina } from 'piscina';\nimport { BasePlugin } from '../core/plugin.js';\nimport { DEFAULT_LIMITS, pluginInputLimit, pluginOutputLimit } from '../core/resourceLimits.js';\nimport type { ProcessorContext, StreamPluginContext } from '../core/types.js';\nimport {\n OperationAbortedError,\n OperationTimeoutError,\n UnsupportedReverseError,\n WorkerPoolClosedError,\n WorkerPoolCloseError,\n WorkerQueueFullError,\n WorkerTaskError,\n} from '../core/errors.js';\n\nexport interface WorkerPoolOptions {\n /** Absolute path or file URL to a caller-owned ESM/CJS worker module. */\n filename: string | URL;\n /** Export used for forward processing. Omit to use the worker's default export. */\n processName?: string;\n /** Export used for reverse processing. When omitted, reverse is unsupported. */\n reverseName?: string;\n maxThreads?: number;\n /** Maximum queued tasks. Defaults to 64. */\n maxQueue?: number;\n /** Per-task timeout in milliseconds. Zero disables the plugin-level timeout. */\n taskTimeoutMs?: number;\n /** Grace period used by Piscina when closing the pool. Defaults to 30 seconds. */\n closeTimeoutMs?: number;\n}\n\nconst MAX_TIMER_MS = 0x7fff_ffff;\nconst MAX_THREADS = 128;\nconst MAX_QUEUE = 100_000;\nconst DEFAULT_MAX_QUEUE = 64;\nconst DEFAULT_MAX_THREADS = Math.max(1, Math.min(4, availableParallelism()));\n\nfunction validateInteger(value: number | undefined, name: string, allowZero = false): void {\n if (value === undefined) return;\n if (!Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) {\n throw new Error(`[PipeX] Worker pool ${name} must be ${allowZero ? 'a non-negative' : 'a positive'} integer`);\n }\n}\n\nfunction taskControl(context: ProcessorContext, configuredTimeoutMs: number | undefined): {\n signal: AbortSignal | undefined;\n cleanup(): void;\n} {\n const timeoutMs = configuredTimeoutMs\n ?? context.limits?.operationTimeoutMs\n ?? DEFAULT_LIMITS.operationTimeoutMs;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMER_MS) {\n throw new Error('[PipeX] Invalid worker task timeout');\n }\n if (timeoutMs === 0) return { signal: context.signal, cleanup() {} };\n const timeoutController = new AbortController();\n const timer = setTimeout(() => {\n timeoutController.abort(new DOMException('Worker task timed out', 'TimeoutError'));\n }, timeoutMs);\n timer.unref();\n return {\n signal: context.signal\n ? AbortSignal.any([context.signal, timeoutController.signal])\n : timeoutController.signal,\n cleanup() { clearTimeout(timer); },\n };\n}\n\nfunction abortError(signal: AbortSignal): OperationAbortedError | OperationTimeoutError {\n return signal.reason instanceof Error && signal.reason.name === 'TimeoutError'\n ? new OperationTimeoutError({ cause: signal.reason })\n : new OperationAbortedError({ cause: signal.reason });\n}\n\n/** Runs caller-owned CPU transforms in a bounded, persistent Piscina pool. */\nexport class WorkerPoolPlugin extends BasePlugin {\n public readonly name = 'worker-pool';\n public readonly version = '5.0.0';\n readonly #pool: Piscina<ArrayBuffer, ArrayBuffer | Uint8Array>;\n readonly #processName?: string;\n readonly #reverseName?: string;\n readonly #taskTimeoutMs: number | undefined;\n readonly #maxThreads: number;\n readonly #maxQueue: number;\n readonly #maxInFlight: number;\n readonly #closeTimeoutMs: number;\n readonly #reversible: boolean;\n #accepting = true;\n #inFlight = 0;\n #closePromise?: Promise<void>;\n #fatalError?: WorkerTaskError;\n readonly #idleWaiters = new Set<() => void>();\n readonly #onPoolError: (error: Error) => void;\n\n constructor(options: WorkerPoolOptions) {\n super(options);\n if (!options || !(typeof options.filename === 'string' || options.filename instanceof URL)) {\n throw new Error('[PipeX] Worker pool requires a worker filename');\n }\n validateInteger(options.maxThreads, 'maxThreads');\n validateInteger(options.maxQueue, 'maxQueue');\n validateInteger(options.taskTimeoutMs, 'taskTimeoutMs', true);\n validateInteger(options.closeTimeoutMs, 'closeTimeoutMs', true);\n if (options.maxThreads !== undefined && options.maxThreads > MAX_THREADS) {\n throw new Error(`[PipeX] Worker pool maxThreads cannot exceed ${MAX_THREADS}`);\n }\n if (options.maxQueue !== undefined && options.maxQueue > MAX_QUEUE) {\n throw new Error(`[PipeX] Worker pool maxQueue cannot exceed ${MAX_QUEUE}`);\n }\n if (options.taskTimeoutMs !== undefined && options.taskTimeoutMs > MAX_TIMER_MS) {\n throw new Error('[PipeX] Worker pool taskTimeoutMs exceeds the supported timer range');\n }\n if (options.closeTimeoutMs !== undefined && options.closeTimeoutMs > MAX_TIMER_MS) {\n throw new Error('[PipeX] Worker pool closeTimeoutMs exceeds the supported timer range');\n }\n for (const [name, value] of [['processName', options.processName], ['reverseName', options.reverseName]] as const) {\n if (value !== undefined && (typeof value !== 'string' || value.length === 0 || value.length > 128)) {\n throw new Error(`[PipeX] Worker pool ${name} must be a non-empty export name`);\n }\n }\n\n const filename = options.filename instanceof URL ? fileURLToPath(options.filename) : options.filename;\n this.#processName = options.processName;\n this.#reverseName = options.reverseName;\n this.#taskTimeoutMs = options.taskTimeoutMs;\n this.#maxThreads = options.maxThreads ?? DEFAULT_MAX_THREADS;\n this.#maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;\n this.#maxInFlight = this.#maxThreads + this.#maxQueue;\n this.#closeTimeoutMs = options.closeTimeoutMs ?? 30_000;\n this.#reversible = Boolean(options.reverseName);\n this.#pool = new Piscina<ArrayBuffer, ArrayBuffer | Uint8Array>({\n filename,\n minThreads: 0,\n maxThreads: this.#maxThreads,\n maxQueue: this.#maxQueue,\n closeTimeout: this.#closeTimeoutMs,\n });\n this.#onPoolError = error => {\n if (this.#fatalError) return;\n this.#fatalError = new WorkerTaskError('worker-thread', { cause: error });\n this.#accepting = false;\n void this.#pool.destroy().catch(() => undefined);\n };\n this.#pool.on('error', this.#onPoolError);\n }\n\n public override get reversible(): boolean {\n return this.#reversible;\n }\n\n async #run(data: Buffer, ctx: ProcessorContext, exportName?: string): Promise<Buffer> {\n if (this.#fatalError) throw this.#fatalError;\n if (!this.#accepting) throw new WorkerPoolClosedError();\n const maxInputBytes = pluginInputLimit(ctx);\n if (data.length > maxInputBytes) {\n throw new Error(`[PipeX] Worker input exceeds ${maxInputBytes} bytes`);\n }\n if (this.#inFlight >= this.#maxInFlight) throw new WorkerQueueFullError(this.#maxQueue);\n const control = taskControl(ctx, this.#taskTimeoutMs);\n this.#inFlight++;\n\n try {\n control.signal?.throwIfAborted();\n const taskBuffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) as ArrayBuffer;\n const result = await this.#pool.run(taskBuffer, {\n transferList: [taskBuffer],\n signal: control.signal,\n name: exportName,\n } as any);\n if (!(result instanceof ArrayBuffer) && !ArrayBuffer.isView(result)) {\n throw new Error('worker returned a non-binary value');\n }\n const output = result instanceof ArrayBuffer\n ? Buffer.from(result)\n : Buffer.from(result.buffer, result.byteOffset, result.byteLength);\n const maxOutputBytes = pluginOutputLimit(ctx);\n if (output.length > maxOutputBytes) {\n throw new Error(`[PipeX] Worker output exceeds ${maxOutputBytes} bytes`);\n }\n return output;\n } catch (error) {\n if (control.signal?.aborted) throw abortError(control.signal);\n if (error instanceof WorkerPoolClosedError || error instanceof WorkerQueueFullError) throw error;\n if (error instanceof Error\n && (error.message === 'Task queue is at limit'\n || error.message === 'No task queue available and all Workers are busy')) {\n throw new WorkerQueueFullError(this.#maxQueue);\n }\n throw new WorkerTaskError(exportName ?? 'default', { cause: error });\n } finally {\n control.cleanup();\n this.#inFlight--;\n if (this.#inFlight === 0) {\n for (const resolve of this.#idleWaiters) resolve();\n this.#idleWaiters.clear();\n }\n }\n }\n\n public override process(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n return this.#run(data, ctx, this.#processName);\n }\n\n public override reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n if (!this.#reverseName) throw new UnsupportedReverseError(`${this.name}@${this.version}`);\n return this.#run(data, ctx, this.#reverseName);\n }\n\n public createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Transform {\n if (mode === 'decompress' && !this.#reverseName) throw new UnsupportedReverseError(this.name);\n const streamController = new AbortController();\n const signal = context?.signal\n ? AbortSignal.any([context.signal, streamController.signal]) : streamController.signal;\n const limits = context?.limits ?? DEFAULT_LIMITS;\n const maxFrame = Math.min(limits.maxFrameBytes, 0xffff_fffe);\n const magic = Buffer.from([0x50, 0x58, 0x57, 0x4b, 1]); // PXWK v1\n const end = Buffer.from([0xff, 0xff, 0xff, 0xff]);\n let inputBytes = 0;\n let outputBytes = 0;\n let frames = 0;\n let started = false;\n let ended = false;\n let header = Buffer.alloc(magic.length);\n let headerBytes = 0;\n let payload: Buffer | undefined;\n let payloadBytes = 0;\n const plugin = this;\n const emit = (stream: Transform, bytes: Buffer) => {\n if (bytes.length > limits.maxOutputBytes - outputBytes) throw new Error('[PipeX] Worker stream output exceeds configured limit');\n outputBytes += bytes.length;\n stream.push(bytes);\n };\n const run = async (data: Buffer): Promise<Buffer> => {\n if (++frames > limits.maxFrames) throw new Error('[PipeX] Worker frame count exceeds configured limit');\n const ctx: ProcessorContext = {\n requestId: context?.requestId ?? 'worker-stream', timestamp: Date.now(), signal,\n limits, logger: context?.logger, metadata: {},\n };\n const task = mode === 'decompress' ? plugin.reverse(data, ctx) : plugin.process(data, ctx);\n context?.track?.(task);\n const output = await task;\n signal.throwIfAborted();\n if (output.length > maxFrame) throw new Error('[PipeX] Worker frame exceeds configured limit');\n return output;\n };\n return new Transform({\n transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {\n const stream = this;\n void (async () => {\n signal.throwIfAborted();\n if (chunk.length > pluginInputLimit(context) - inputBytes) throw new Error('[PipeX] Worker stream input exceeds configured limit');\n inputBytes += chunk.length;\n if (mode === 'compress') {\n if (!started) { emit(stream, magic); started = true; }\n for (let offset = 0; offset < chunk.length; offset += maxFrame) {\n const output = await run(chunk.subarray(offset, offset + maxFrame));\n const length = Buffer.alloc(4);\n length.writeUInt32BE(output.length);\n emit(stream, length);\n emit(stream, output);\n }\n return;\n }\n let offset = 0;\n while (offset < chunk.length) {\n if (ended) throw new Error('[PipeX] Worker stream has trailing bytes');\n if (!payload) {\n const count = Math.min(header.length - headerBytes, chunk.length - offset);\n chunk.copy(header, headerBytes, offset, offset + count);\n headerBytes += count;\n offset += count;\n if (headerBytes !== header.length) continue;\n if (!started) {\n if (!header.equals(magic)) throw new Error('[PipeX] Invalid worker stream format');\n started = true;\n header = Buffer.alloc(4);\n headerBytes = 0;\n continue;\n }\n const length = header.readUInt32BE();\n headerBytes = 0;\n if (length === 0xffff_ffff) { ended = true; continue; }\n if (length > maxFrame) throw new Error('[PipeX] Worker frame exceeds configured limit');\n payload = Buffer.alloc(length);\n payloadBytes = 0;\n }\n const count = Math.min(payload.length - payloadBytes, chunk.length - offset);\n chunk.copy(payload, payloadBytes, offset, offset + count);\n payloadBytes += count;\n offset += count;\n if (payloadBytes === payload.length) {\n emit(stream, await run(payload));\n payload = undefined;\n payloadBytes = 0;\n }\n }\n })().then(() => callback(), error => callback(error as Error));\n },\n flush(callback) {\n try {\n signal.throwIfAborted();\n if (mode === 'compress') {\n if (!started) emit(this, magic);\n emit(this, end);\n } else if (!ended || payload || headerBytes) throw new Error('[PipeX] Incomplete worker stream');\n callback();\n } catch (error) { callback(error as Error); }\n },\n destroy(error, callback) {\n if (!signal.aborted) streamController.abort(error ?? new DOMException('Worker stream destroyed', 'AbortError'));\n payload = undefined;\n callback(error);\n },\n });\n }\n\n /** Rejects new tasks and waits for queued/running work unless force is true. */\n public async close(options: { force?: boolean } = {}): Promise<void> {\n if (!options || (options.force !== undefined && typeof options.force !== 'boolean')) {\n throw new TypeError('[PipeX] Worker pool close force must be a boolean');\n }\n if (this.#closePromise) return this.#closePromise;\n this.#accepting = false;\n this.#closePromise = (async () => {\n try {\n if (this.#fatalError) await this.#pool.destroy();\n else if (options.force) await this.#pool.destroy();\n else {\n if (this.#inFlight > 0) {\n await new Promise<void>((resolve, reject) => {\n const onIdle = () => { clearTimeout(timer); resolve(); };\n const timer = setTimeout(() => {\n this.#idleWaiters.delete(onIdle);\n reject(new WorkerPoolCloseError());\n }, this.#closeTimeoutMs);\n this.#idleWaiters.add(onIdle);\n });\n }\n await this.#pool.close({ force: false });\n if (this.#fatalError) throw this.#fatalError;\n }\n } catch (error) {\n await this.#pool.destroy().catch(() => undefined);\n throw error instanceof WorkerPoolCloseError\n ? error\n : new WorkerPoolCloseError({ cause: error });\n } finally {\n this.#pool.removeListener('error', this.#onPoolError);\n }\n })();\n return this.#closePromise;\n }\n}\n","import { z } from 'zod';\nimport { BasePlugin } from './plugin.js';\nimport { UNPACKR, assertMessagePackFrameLimits } from './core.js';\nimport { DEFAULT_LIMITS } from './resourceLimits.js';\nimport { pluginInputLimit, pluginOutputLimit } from './resourceLimits.js';\nimport type { ProcessorContext, StreamPluginContext } from './types.js';\nimport { Transform } from 'node:stream';\n\nexport interface ValidationOptions {\n schema: z.ZodType<any>;\n /** \n * Whether to validate during the reverse (decompress) phase. \n * Useful if you want to ensure the restored data still matches the schema.\n */\n validateOnReverse?: boolean;\n}\n\n/**\n * ValidationPlugin — Core plugin for schema-based data validation.\n * Uses Zod to verify the structure of the data passing through the engine.\n * \n * Note: This plugin assumes the data is MsgPack-encoded (default PipeX behavior).\n */\nexport class ValidationPlugin extends BasePlugin {\n public readonly name = 'validation';\n public readonly version = '1.0.0';\n\n constructor(protected override options: ValidationOptions) {\n super(options);\n }\n\n public override async process(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n this.validate(data, Math.min(pluginInputLimit(ctx), pluginOutputLimit(ctx)), ctx.limits?.maxFrameBytes);\n return data;\n }\n\n public override async reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n const maxBytes = Math.min(pluginInputLimit(ctx), pluginOutputLimit(ctx));\n if (data.length > maxBytes) throw new Error(`[PipeX] Validation input exceeds ${maxBytes} bytes`);\n if (this.options.validateOnReverse) {\n this.validate(data, maxBytes, ctx.limits?.maxFrameBytes);\n }\n return data;\n }\n\n private validate(data: Buffer, maxBytes: number, maxFrameBytes = DEFAULT_LIMITS.maxFrameBytes): void {\n if (data.length > maxBytes) throw new Error(`[PipeX] Validation input exceeds ${maxBytes} bytes`);\n assertMessagePackFrameLimits(data, maxFrameBytes, 1);\n let decoded: unknown;\n try {\n decoded = UNPACKR.unpack(data);\n } catch {\n throw new Error('[PipeX] Validation: invalid MessagePack input');\n }\n\n const result = this.options.schema.safeParse(decoded);\n if (!result.success) {\n throw new Error('[PipeX] Validation failed');\n }\n }\n\n public createStream(mode: 'compress' | 'decompress' = 'compress', context?: StreamPluginContext): Transform {\n const chunks: Buffer[] = [];\n let total = 0;\n const maxBytes = Math.min(pluginInputLimit(context), pluginOutputLimit(context));\n return new Transform({\n transform(chunk, _enc, cb) {\n if (chunk.length > maxBytes - total) {\n return cb(new Error(`[PipeX] Validation input exceeds ${maxBytes} bytes`));\n }\n total += chunk.length;\n chunks.push(chunk);\n cb();\n },\n flush: (cb) => {\n try {\n const data = Buffer.concat(chunks, total);\n if (mode !== 'decompress' || this.options.validateOnReverse) {\n this.validate(data, maxBytes, context?.limits?.maxFrameBytes);\n }\n cb(null, data);\n } catch (error) { cb(error as Error); }\n },\n });\n }\n}\n","import { randomBytes, createCipheriv, createDecipheriv, type CipherGCM, type DecipherGCM } from 'node:crypto';\nimport { BasePlugin } from '../core/plugin.js';\nimport { DEFAULT_LIMITS, pluginInputLimit, pluginOutputLimit } from '../core/resourceLimits.js';\nimport type { KmsOperation, KmsProviderCapabilities, ProcessorContext, KmsProvider } from '../core/types.js';\nimport {\n KmsAuthenticationError,\n KmsProviderAuthenticationError,\n KmsProviderError,\n KmsProviderUnavailableError,\n OperationAbortedError,\n OperationTimeoutError,\n} from '../core/errors.js';\nimport { assertKmsOperation, getKmsProviderCapabilities } from '../core/kmsCapabilities.js';\n\nexport interface KmsEncryptionOptions {\n kms: KmsProvider;\n keyId: string;\n /** Temporarily accept the unversioned v1 envelope while migrating. Defaults to true. */\n allowLegacyDecrypt?: boolean;\n}\n\nconst IV_LENGTH = 12;\nconst TAG_LENGTH = 16;\nconst MAGIC = Buffer.from('PXKM');\nconst FORMAT_VERSION = 1;\nconst ALGORITHM_AES_256_GCM = 1;\nconst FIXED_HEADER_LENGTH = 4 + 1 + 1 + 2 + 4 + 4 + IV_LENGTH;\nconst MAX_TIMER_MS = 0x7fff_ffff;\n\nfunction abortError(signal: AbortSignal): OperationAbortedError | OperationTimeoutError {\n const options = { cause: signal.reason };\n return signal.reason instanceof Error && signal.reason.name === 'TimeoutError'\n ? new OperationTimeoutError(options)\n : new OperationAbortedError(options);\n}\n\nasync function abortable<T>(\n promise: Promise<T>,\n signal: AbortSignal | undefined,\n disposeLate?: (value: T) => void,\n): Promise<T> {\n if (!signal) return promise;\n if (signal.aborted) {\n void promise.then(value => {\n try { disposeLate?.(value); } catch { /* best-effort cleanup must not reject */ }\n }, () => undefined);\n throw abortError(signal);\n }\n return new Promise<T>((resolve, reject) => {\n let aborted = false;\n const onAbort = () => {\n aborted = true;\n reject(abortError(signal));\n };\n signal.addEventListener('abort', onAbort, { once: true });\n void promise.then(\n value => {\n signal.removeEventListener('abort', onAbort);\n if (aborted) {\n try { disposeLate?.(value); } catch { /* best-effort cleanup must not reject */ }\n }\n else resolve(value);\n },\n error => {\n signal.removeEventListener('abort', onAbort);\n if (!aborted) reject(error);\n },\n );\n });\n}\n\nfunction providerControl(context: ProcessorContext): {\n signal: AbortSignal | undefined;\n cleanup(): void;\n} {\n const timeoutMs = context.limits?.operationTimeoutMs ?? DEFAULT_LIMITS.operationTimeoutMs;\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMER_MS) {\n throw new Error('[PipeX] Invalid KMS provider timeout');\n }\n if (timeoutMs === 0) return { signal: context.signal, cleanup() {} };\n\n const timeoutController = new AbortController();\n const timer = setTimeout(() => {\n timeoutController.abort(new DOMException('KMS provider operation timed out', 'TimeoutError'));\n }, timeoutMs);\n // This timer may be the only active handle for a provider promise that never\n // settles. Keep it referenced so the configured timeout always rejects.\n const signal = context.signal\n ? AbortSignal.any([context.signal, timeoutController.signal])\n : timeoutController.signal;\n return { signal, cleanup() { clearTimeout(timer); } };\n}\n\nfunction sanitizeProviderError(operation: KmsOperation, error: unknown): Error {\n if (error instanceof OperationAbortedError || error instanceof OperationTimeoutError) return error;\n if (error instanceof KmsProviderAuthenticationError) return new KmsProviderAuthenticationError(operation);\n if (error instanceof KmsProviderUnavailableError) return new KmsProviderUnavailableError(operation);\n return new KmsProviderError(operation);\n}\n\nasync function callProvider<T>(\n provider: KmsProvider,\n operation: KmsOperation,\n context: ProcessorContext,\n invoke: (signal: AbortSignal | undefined) => Promise<T>,\n disposeLate?: (value: T) => void,\n): Promise<T> {\n assertKmsOperation(provider, operation);\n const control = providerControl(context);\n try {\n if (control.signal?.aborted) throw abortError(control.signal);\n const promise = invoke(control.signal);\n return await abortable(promise, control.signal, disposeLate);\n } catch (error) {\n if (control.signal?.aborted) throw abortError(control.signal);\n throw sanitizeProviderError(operation, error);\n } finally {\n control.cleanup();\n }\n}\n\n/**\n * KmsEncryptionPlugin — Enterprise-grade encryption using Envelope Encryption.\n * \n * 1. Generate a data key via KMS.\n * 2. Encrypt data locally using the plaintext data key.\n * 3. Prepend the encrypted data key (ciphertext) to the payload.\n * \n * Packet format: [PXKM][version][algorithm][flags][key_len][ciphertext_len]\n * [12B IV][Encrypted Data Key][Ciphertext][16B Tag]\n */\nexport class KmsEncryptionPlugin extends BasePlugin {\n public readonly name = 'kms-encryption';\n public readonly version = '2.1.0';\n public readonly streaming = false;\n\n public get providerCapabilities(): Readonly<KmsProviderCapabilities> {\n return getKmsProviderCapabilities(this.options.kms);\n }\n\n public override get reversible(): boolean {\n return this.providerCapabilities.decrypt;\n }\n\n constructor(protected override options: KmsEncryptionOptions) {\n super(options);\n if (!options || !options.kms || typeof options.keyId !== 'string' || options.keyId.length === 0) {\n throw new Error('[PipeX] KMS Encryption: invalid provider or keyId');\n }\n if (options.allowLegacyDecrypt !== undefined && typeof options.allowLegacyDecrypt !== 'boolean') {\n throw new Error('[PipeX] KMS Encryption allowLegacyDecrypt must be a boolean');\n }\n getKmsProviderCapabilities(options.kms);\n assertKmsOperation(options.kms, 'generateDataKey');\n }\n\n public override async process(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n const maxInputBytes = pluginInputLimit(ctx);\n const maxOutputBytes = pluginOutputLimit(ctx);\n const maxEncryptedKeyBytes = ctx.limits?.maxKmsEncryptedKeyBytes ?? DEFAULT_LIMITS.maxKmsEncryptedKeyBytes;\n const maxKeyIdBytes = ctx.limits?.maxKmsKeyIdBytes ?? DEFAULT_LIMITS.maxKmsKeyIdBytes;\n if (Buffer.byteLength(this.options.keyId) > maxKeyIdBytes) throw new Error('[PipeX] KMS key identifier exceeds the configured limit');\n if (data.length > maxInputBytes) throw new Error(`[PipeX] KMS encryption input exceeds ${maxInputBytes} bytes`);\n if (data.length > 0xffff_ffff) throw new Error('[PipeX] KMS encryption input exceeds the format limit');\n const minimumOverhead = FIXED_HEADER_LENGTH + 1 + TAG_LENGTH;\n if (data.length > maxOutputBytes - minimumOverhead) {\n throw new Error(`[PipeX] KMS encryption output exceeds ${maxOutputBytes} bytes`);\n }\n const { kms, keyId } = this.options;\n\n const keyResult = await callProvider(\n kms,\n 'generateDataKey',\n ctx,\n signal => kms.generateDataKey!(keyId, { signal }),\n value => { if (Buffer.isBuffer(value?.plaintext)) value.plaintext.fill(0); },\n );\n\n const plaintext = keyResult?.plaintext;\n try {\n const encryptedKey = keyResult?.ciphertext;\n if (!Buffer.isBuffer(plaintext) || plaintext.length !== 32) throw new Error('[PipeX] KMS generated an invalid data key');\n if (!Buffer.isBuffer(encryptedKey) || encryptedKey.length < 1 || encryptedKey.length > maxEncryptedKeyBytes) {\n throw new Error('[PipeX] KMS generated an invalid encrypted key');\n }\n const overhead = FIXED_HEADER_LENGTH + encryptedKey.length + TAG_LENGTH;\n if (data.length > maxOutputBytes - overhead) {\n throw new Error(`[PipeX] KMS encryption output exceeds ${maxOutputBytes} bytes`);\n }\n const outputLength = overhead + data.length;\n\n const iv = randomBytes(IV_LENGTH);\n const cipher = createCipheriv('aes-256-gcm', plaintext, iv, { authTagLength: TAG_LENGTH } as any) as CipherGCM;\n const header = Buffer.alloc(FIXED_HEADER_LENGTH);\n MAGIC.copy(header, 0);\n header.writeUInt8(FORMAT_VERSION, 4);\n header.writeUInt8(ALGORITHM_AES_256_GCM, 5);\n header.writeUInt16BE(0, 6);\n header.writeUInt32BE(encryptedKey.length, 8);\n header.writeUInt32BE(data.length, 12);\n iv.copy(header, 16);\n cipher.setAAD(Buffer.concat([header, encryptedKey]));\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n const tag = cipher.getAuthTag();\n return Buffer.concat([header, encryptedKey, encrypted, tag], outputLength);\n } finally {\n if (Buffer.isBuffer(plaintext)) plaintext.fill(0);\n }\n }\n\n public override async reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer> {\n const { kms, keyId } = this.options;\n assertKmsOperation(kms, 'decrypt');\n const maxInputBytes = pluginInputLimit(ctx);\n const maxOutputBytes = pluginOutputLimit(ctx);\n const maxEncryptedKeyBytes = ctx.limits?.maxKmsEncryptedKeyBytes ?? DEFAULT_LIMITS.maxKmsEncryptedKeyBytes;\n const maxKeyIdBytes = ctx.limits?.maxKmsKeyIdBytes ?? DEFAULT_LIMITS.maxKmsKeyIdBytes;\n if (Buffer.byteLength(keyId) > maxKeyIdBytes) throw new Error('[PipeX] KMS key identifier exceeds the configured limit');\n if (data.length > maxInputBytes) throw new Error(`[PipeX] KMS decryption input exceeds ${maxInputBytes} bytes`);\n if (data.length === 0) throw new Error('[PipeX] KMS Decryption: Packet too short');\n\n const framed = data.length >= MAGIC.length && data.subarray(0, MAGIC.length).equals(MAGIC);\n if (!framed && data.readUInt8(0) === MAGIC.readUInt8(0)) {\n throw new Error('[PipeX] KMS Decryption: incomplete framed header');\n }\n if (!framed && this.options.allowLegacyDecrypt === false) {\n throw new Error('[PipeX] KMS Decryption: legacy format disabled');\n }\n\n let encryptedKey: Buffer;\n let iv: Buffer;\n let tag: Buffer;\n let ciphertext: Buffer;\n let authenticatedHeader: Buffer | undefined;\n if (framed) {\n if (data.length < FIXED_HEADER_LENGTH + 1 + TAG_LENGTH) throw new Error('[PipeX] KMS Decryption: incomplete framed envelope');\n if (data.readUInt8(4) !== FORMAT_VERSION) throw new Error('[PipeX] KMS Decryption: unsupported format version');\n if (data.readUInt8(5) !== ALGORITHM_AES_256_GCM || data.readUInt16BE(6) !== 0) {\n throw new Error('[PipeX] KMS Decryption: invalid framed envelope');\n }\n const keyLen = data.readUInt32BE(8);\n const ciphertextLength = data.readUInt32BE(12);\n if (keyLen < 1 || keyLen > maxEncryptedKeyBytes) throw new Error('[PipeX] KMS Decryption: invalid key envelope');\n const expectedLength = FIXED_HEADER_LENGTH + keyLen + ciphertextLength + TAG_LENGTH;\n if (expectedLength !== data.length) throw new Error('[PipeX] KMS Decryption: invalid envelope length');\n if (ciphertextLength > maxOutputBytes) throw new Error(`[PipeX] KMS decryption output exceeds ${maxOutputBytes} bytes`);\n iv = data.subarray(16, FIXED_HEADER_LENGTH);\n encryptedKey = data.subarray(FIXED_HEADER_LENGTH, FIXED_HEADER_LENGTH + keyLen);\n ciphertext = data.subarray(FIXED_HEADER_LENGTH + keyLen, data.length - TAG_LENGTH);\n tag = data.subarray(data.length - TAG_LENGTH);\n authenticatedHeader = data.subarray(0, FIXED_HEADER_LENGTH + keyLen);\n } else {\n if (data.length < 4) throw new Error('[PipeX] KMS Decryption: Packet too short');\n const keyLen = data.readUInt32BE(0);\n if (keyLen < 1 || keyLen > maxEncryptedKeyBytes || data.length < 4 + keyLen + IV_LENGTH + TAG_LENGTH) {\n throw new Error('[PipeX] KMS Decryption: invalid key envelope');\n }\n encryptedKey = data.subarray(4, 4 + keyLen);\n iv = data.subarray(4 + keyLen, 4 + keyLen + IV_LENGTH);\n tag = data.subarray(4 + keyLen + IV_LENGTH, 4 + keyLen + IV_LENGTH + TAG_LENGTH);\n ciphertext = data.subarray(4 + keyLen + IV_LENGTH + TAG_LENGTH);\n }\n if (ciphertext.length > maxOutputBytes) {\n throw new Error(`[PipeX] KMS decryption output exceeds ${maxOutputBytes} bytes`);\n }\n \n const plaintext = await callProvider(\n kms,\n 'decrypt',\n ctx,\n signal => kms.decrypt!(encryptedKey, keyId, { signal }),\n value => { if (Buffer.isBuffer(value)) value.fill(0); },\n );\n\n try {\n if (!Buffer.isBuffer(plaintext) || plaintext.length !== 32) throw new Error('[PipeX] KMS Decryption: invalid data key length');\n const decipher = createDecipheriv('aes-256-gcm', plaintext, iv, { authTagLength: TAG_LENGTH } as any) as DecipherGCM;\n if (authenticatedHeader) decipher.setAAD(authenticatedHeader);\n decipher.setAuthTag(tag);\n const pending = decipher.update(ciphertext);\n try {\n const final = decipher.final();\n return final.length === 0 ? pending : Buffer.concat([pending, final]);\n } catch {\n pending.fill(0);\n throw new KmsAuthenticationError();\n }\n } finally {\n if (Buffer.isBuffer(plaintext)) plaintext.fill(0);\n }\n }\n}\n","// Export the Core\nexport * from './core/core.js';\nimport { DataEngine } from './core/dataEngine.js';\nexport { DataEngine };\nexport type { PluginConstructor } from './core/dataEngine.js';\nexport type {\n ProcessorPlugin,\n ProcessorContext,\n EngineResult,\n PipeXManifest,\n EngineEvents,\n EngineLimits,\n OperationOptions,\n BinaryUndoOptions,\n StreamPluginContext,\n RetryOptions,\n Logger,\n Span,\n Tracer,\n AuditRecord,\n AuditLogger,\n KmsProvider,\n KmsOperation,\n KmsProviderCapabilities,\n KmsRequestOptions,\n SchemaRegistry,\n EngineConfig,\n PluginCapabilities,\n PluginOperation,\n RegisteredPluginCapabilities,\n} from './core/types.js';\nexport { isManifest } from './core/types.js';\n\nexport { BasePlugin } from './core/plugin.js';\nexport {\n KmsProviderError,\n KmsAuthenticationError,\n KmsProviderAuthenticationError,\n KmsProviderUnavailableError,\n InvalidKmsProviderCapabilityError,\n InvalidPluginCapabilityError,\n OperationAbortedError,\n OperationTimeoutError,\n PipeXError,\n UnsupportedReverseError,\n UnsupportedStreamingError,\n UnsupportedKmsOperationError,\n WorkerPoolClosedError,\n WorkerPoolCloseError,\n WorkerQueueFullError,\n WorkerTaskError,\n} from './core/errors.js';\nexport type { InvalidKmsProviderCapabilityIssue, InvalidPluginCapabilityIssue, PipeXErrorCode } from './core/errors.js';\nexport { getKmsProviderCapabilities, supportsKmsOperation } from './core/kmsCapabilities.js';\n\n// --- Standard Plugin Library ---\nimport { HashingPlugin } from './plugin/hashing.js';\nimport { EncryptionPlugin } from './plugin/encryption.js';\nimport { CompressionPlugin } from './plugin/compression.js';\nimport { BenchmarkPlugin } from './plugin/performance.js';\nimport { WorkerPoolPlugin } from './plugin/worker.js';\nimport { ValidationPlugin } from './core/validation.js';\nimport { KmsEncryptionPlugin } from './plugin/kms_encryption.js';\n\nexport type { HashingOptions, HashAlgorithm } from './plugin/hashing.js';\nexport type { EncryptionOptions, EncryptionAlgorithm } from './plugin/encryption.js';\nexport type { CompressionOptions, CompressionType } from './plugin/compression.js';\nexport type { WorkerPoolOptions } from './plugin/worker.js';\nexport type { ValidationOptions } from './core/validation.js';\nexport type { KmsEncryptionOptions } from './plugin/kms_encryption.js';\n\nexport const Plugins = {\n Hashing: HashingPlugin,\n Encryption: EncryptionPlugin,\n Compression: CompressionPlugin,\n Benchmark: BenchmarkPlugin,\n WorkerPool: WorkerPoolPlugin,\n Validation: ValidationPlugin,\n KmsEncryption: KmsEncryptionPlugin,\n} as const;\n\n// Make config-driven setup work out of the box while keeping custom plugin\n// registration available through DataEngine.registerPlugin().\nDataEngine.registerPlugin('hashing', HashingPlugin);\nDataEngine.registerPlugin('encryption', EncryptionPlugin);\nDataEngine.registerPlugin('compression', CompressionPlugin);\nDataEngine.registerPlugin('benchmark', BenchmarkPlugin);\nDataEngine.registerPlugin('worker-pool', WorkerPoolPlugin);\nDataEngine.registerPlugin('validation', ValidationPlugin);\nDataEngine.registerPlugin('kms-encryption', KmsEncryptionPlugin);\n\n// Also export individually for those who prefer it\nexport { HashingPlugin, EncryptionPlugin, CompressionPlugin, BenchmarkPlugin, WorkerPoolPlugin, ValidationPlugin, KmsEncryptionPlugin };\n"],"mappings":"i+BAwKA,SAAgB,GAAW,EAAwC,CACjE,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GACxD,IAAM,EAAS,EACf,OAAO,EAAO,YAAiB,GAC1B,MAAM,QAAQ,EAAO,QAAW,EAChC,EAAO,QAAW,QAAU,KAC5B,EAAO,QAAW,MAAM,GAAU,OAAO,GAAW,UAAY,EAAO,QAAU,IAAI,EACrF,OAAO,EAAO,IAAU,UACxB,OAAO,cAAc,EAAO,GAAM,EAClC,EAAO,IAAS,EChKvB,IAAa,EAAb,cAAgC,KAAM,CACpC,KAAwC,aAExC,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,EAAQ,CAJP,KAAA,KAAA,IAQP,EAAb,cAA6C,CAAW,CACtD,KAAwC,0BAExC,YAAY,EAAgC,CAC1C,MAAM,sBAAuB,kBAAkB,EAAO,sCAAsC,CADlE,KAAA,OAAA,IAKjB,GAAb,cAA+C,CAAW,CACxD,KAAwC,4BACxC,YAAY,EAAgC,CAC1C,MAAM,wBAAyB,kBAAkB,EAAO,qCAAqC,CADnE,KAAA,OAAA,IAUjB,EAAb,cAAkD,CAAW,CAC3D,KAAwC,+BAExC,YACE,EACA,EACA,EACA,CAMA,MACE,4BACA,kBAAkB,EAAO,kBAAkB,EAAW,eAPxC,IAAU,kBACtB,kCACA,IAAU,yBACR,gDACA,kDAIL,CAZe,KAAA,OAAA,EACA,KAAA,WAAA,EACA,KAAA,MAAA,IAcP,EAAb,cAA2C,CAAW,CACpD,KAAwC,wBACxC,Y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