{"version":3,"file":"stream.mjs","names":[],"sources":["../../src/util/stream.ts"],"sourcesContent":["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { PadroneSchema } from '../types/index.ts';\n\nexport interface AsyncStreamMeta {\n  [x: string]: unknown;\n  readonly asyncStream: number;\n  readonly itemSchema?: StandardSchemaV1;\n}\n\nlet asyncStreamIdCounter = 1;\nexport const asyncStreamRegistry = new Map<number, AsyncStreamMeta>();\n\n/**\n * Returns metadata to mark a schema field as an async stream via `.meta()`.\n *\n * When used with `stdin`, padrone pipes stdin data as an `AsyncIterable` instead of\n * buffering it. Each line is validated against the item schema (if provided) as it arrives.\n *\n * @param itemSchema - Optional item schema for per-item validation.\n *   Non-string schemas cause each stdin line to be `JSON.parse`'d before validation.\n *\n * @example\n * ```ts\n * import { asyncStream } from 'padrone';\n *\n * // String lines\n * z.object({ lines: z.custom<AsyncIterable<string>>().meta(asyncStream()) })\n *\n * // Typed items — each line JSON.parse'd and validated\n * z.object({ records: z.custom<AsyncIterable<{ name: string }>>().meta(asyncStream(recordSchema)) })\n * ```\n */\nexport function asyncStream<T = string>(itemSchema?: PadroneSchema<T>): AsyncStreamMeta {\n  const id = asyncStreamIdCounter++;\n  const meta: AsyncStreamMeta = itemSchema ? { asyncStream: id, itemSchema } : { asyncStream: id };\n  asyncStreamRegistry.set(id, meta);\n  return meta;\n}\n\n/** Stdin interface matching PadroneRuntime.stdin */\ninterface StdinSource {\n  isTTY?: boolean;\n  text(): Promise<string>;\n  lines(): AsyncIterable<string>;\n}\n\n/**\n * Creates an `AsyncIterable` from a stdin source, optionally validating each item.\n * When no stdin is available (TTY / undefined), yields nothing.\n *\n * - No item schema: yields raw string lines\n * - With item schema: `JSON.parse`s each line, validates, then yields\n */\nexport function createStdinStream(stdin: StdinSource | undefined, itemSchema?: StandardSchemaV1): AsyncIterable<unknown> {\n  if (!stdin) return emptyAsyncIterable;\n\n  if (!itemSchema) return stdin.lines();\n\n  return {\n    async *[Symbol.asyncIterator]() {\n      for await (const line of stdin.lines()) {\n        const result = itemSchema['~standard'].validate(line);\n        const resolved = result instanceof Promise ? await result : result;\n        if ('issues' in resolved && resolved.issues) {\n          throw new Error(`Stream item validation failed: ${resolved.issues.map((i) => i.message).join(', ')}`);\n        }\n        yield (resolved as { value: unknown }).value;\n      }\n    },\n  };\n}\n\nconst emptyAsyncIterable: AsyncIterable<never> = {\n  async *[Symbol.asyncIterator]() {},\n};\n\nconst textEncoder = /* @__PURE__ */ new TextEncoder();\nconst textDecoder = /* @__PURE__ */ new TextDecoder();\n\n/** Concatenate multiple `Uint8Array` chunks into a single array. */\nexport function concatBytes(chunks: Uint8Array[]): Uint8Array {\n  if (chunks.length === 1) return chunks[0]!;\n  let totalLength = 0;\n  for (const chunk of chunks) totalLength += chunk.byteLength;\n  const result = new Uint8Array(totalLength);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return result;\n}\n\n/** Read an async iterable of chunks into a UTF-8 string. */\nexport async function readStreamAsText(stream: AsyncIterable<Uint8Array | string>): Promise<string> {\n  const chunks: Uint8Array[] = [];\n  for await (const chunk of stream) {\n    chunks.push(typeof chunk === 'string' ? textEncoder.encode(chunk) : chunk);\n  }\n  return textDecoder.decode(concatBytes(chunks));\n}\n"],"mappings":";AASA,IAAI,uBAAuB;AAC3B,MAAa,sCAAsB,IAAI,IAA6B;;;;;;;;;;;;;;;;;;;;;AAsBpE,SAAgB,YAAwB,YAAgD;CACtF,MAAM,KAAK;CACX,MAAM,OAAwB,aAAa;EAAE,aAAa;EAAI;CAAW,IAAI,EAAE,aAAa,GAAG;CAC/F,oBAAoB,IAAI,IAAI,IAAI;CAChC,OAAO;AACT;;;;;;;;AAgBA,SAAgB,kBAAkB,OAAgC,YAAuD;CACvH,IAAI,CAAC,OAAO,OAAO;CAEnB,IAAI,CAAC,YAAY,OAAO,MAAM,MAAM;CAEpC,OAAO,EACL,QAAQ,OAAO,iBAAiB;EAC9B,WAAW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