@hyperframes/aws-lambda 0.7.110 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -5
- package/dist/cdk/HyperframesRenderStack.d.ts.map +1 -1
- package/dist/cdk/index.js +5 -2
- package/dist/cdk/index.js.map +2 -2
- package/dist/events.d.ts +10 -10
- package/dist/events.d.ts.map +1 -1
- package/dist/handler.d.ts.map +1 -1
- package/dist/handler.js +40 -10
- package/dist/handler.js.map +2 -2
- package/dist/index.js +41 -11
- package/dist/index.js.map +2 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/renderToLambda.d.ts +2 -2
- package/package.json +2 -2
package/dist/handler.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/handler.ts", "../src/chromium.ts", "../src/formatExtension.ts", "../src/s3Transport.ts", "../src/s3PlanV2Publisher.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * AWS Lambda handler for HyperFrames distributed rendering.\n *\n * One Lambda function, three roles. Step Functions dispatches by setting\n * `event.Action`; the handler unwraps Map-state envelopes, primes the\n * Lambda environment (Chrome path, ffmpeg path, tmpdir), and forwards to\n * the matching OSS primitive from `@hyperframes/producer/distributed`.\n *\n * Everything heavy \u2014 capture, encode, audio mix \u2014 happens inside the OSS\n * primitives. The handler is thin glue: parse event \u2192 S3 download \u2192 call\n * primitive \u2192 S3 upload \u2192 return small JSON result.\n */\n\nimport { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport { S3Client } from \"@aws-sdk/client-s3\";\nimport {\n assemble,\n type AssembleResult,\n type ChunkRenderer,\n type ChunkResult,\n type DistributedRenderConfig,\n listPlanV2ArtifactsForTarget,\n materializePlanV2Target,\n plan,\n isPlanAudioArtifactPath,\n PLAN_AUDIO_RELATIVE_PATH,\n resolvePlanAudioPath,\n planV2WithPublisher,\n type PlanResult,\n type PlanV2Artifact,\n type PlanV2Manifest,\n type PlanV2MaterializationTarget,\n readPlanV2Manifest,\n renderChunk,\n} from \"@hyperframes/producer/distributed\";\nimport { resolveChromeExecutablePath } from \"./chromium.js\";\nimport { type DistributedFormat, formatExtension } from \"./formatExtension.js\";\nimport type {\n AssembleEvent,\n AssembleLambdaResult,\n LambdaAction,\n LambdaEvent,\n LambdaResult,\n PlanEvent,\n PlanLambdaResult,\n RenderChunkEvent,\n RenderChunkLambdaResult,\n} from \"./events.js\";\nimport {\n downloadS3ObjectToFile,\n downloadS3ObjectToFileVerified,\n parseS3Uri,\n tarDirectory,\n untarDirectory,\n uploadFileToS3,\n} from \"./s3Transport.js\";\nimport { S3PlanV2ArtifactPublisher } from \"./s3PlanV2Publisher.js\";\n\n/**\n * Lazily-constructed S3 client. Cached at module scope so warm Lambda\n * containers reuse the underlying HTTP keep-alive pool across invocations.\n */\nlet cachedS3Client: S3Client | null = null;\nfunction getS3Client(): S3Client {\n if (cachedS3Client) return cachedS3Client;\n cachedS3Client = new S3Client({});\n return cachedS3Client;\n}\n\n/**\n * Optional injection points used by the handler's unit tests. Production\n * callers leave these unset; the real OSS primitives are used. Tests\n * inject `s3` and `primitives` directly rather than mutating module\n * state \u2014 the dependency-injection seam is sufficient and avoids a\n * second leak point for cross-test contamination.\n */\nexport interface HandlerDeps {\n s3?: S3Client;\n primitives?: {\n plan: typeof plan;\n planV2WithPublisher?: typeof planV2WithPublisher;\n renderChunk: ChunkRenderer;\n assemble: typeof assemble;\n };\n /** Override the per-invocation `/tmp` workdir root (defaults to Lambda's `/tmp`). */\n tmpRoot?: string;\n /** Skip Chrome resolution (used by handler dispatch tests that mock renderChunk). */\n skipChromeResolution?: boolean;\n}\n\n/**\n * Lambda entry. Step Functions sometimes wraps the event in\n * `{ Payload: ... }` or `{ Input: ... }` depending on the state machine\n * shape; unwrap until we hit a discriminated event.\n */\nexport async function handler(event: LambdaEvent, deps?: HandlerDeps): Promise<LambdaResult> {\n const unwrapped = unwrapEvent(event);\n validateEventS3Uris(unwrapped);\n primeRuntimeEnv();\n // Single structured boot log line \u2014 CloudWatch Logs Insights queries\n // key off `event=handler_start` to grep for a specific Action / S3 URI\n // when triaging without attaching a debugger.\n logEvent({ event: \"handler_start\", action: unwrapped.Action, input: summarizeEvent(unwrapped) });\n try {\n switch (unwrapped.Action) {\n case \"plan\":\n return await handlePlan(unwrapped, deps);\n case \"renderChunk\":\n return await handleRenderChunk(unwrapped, deps);\n case \"assemble\":\n return await handleAssemble(unwrapped, deps);\n default: {\n // Compile-time exhaustiveness: a new LambdaAction member trips\n // the `never` assignment before the runtime error is reachable.\n const _exhaustive: never = unwrapped;\n throw new Error(\n `[handler] unknown Action: ${JSON.stringify(\n (_exhaustive as { Action?: string }).Action,\n )}. Expected one of \"plan\", \"renderChunk\", \"assemble\".`,\n );\n }\n }\n } catch (err) {\n normalizeTerminalErrorName(err);\n // Log before re-throwing so CloudWatch captures the structured\n // error context alongside Lambda's default stack trace. Otherwise\n // ops only sees the trace and has to correlate with execution\n // history to recover the action + input.\n logEvent({\n event: \"handler_error\",\n action: unwrapped.Action,\n input: summarizeEvent(unwrapped),\n message: err instanceof Error ? err.message : String(err),\n name: err instanceof Error ? err.name : undefined,\n });\n throw err;\n }\n}\n\n/**\n * AWS Lambda reports `Error.name` to Step Functions, while producer errors\n * expose stable machine codes separately. Normalize workflow-facing codes\n * whose historical class names differ from their orchestration contracts.\n */\n// The explicit error-name mapping is the public Step Functions failure contract.\n// fallow-ignore-next-line complexity\nfunction normalizeTerminalErrorName(error: unknown): void {\n if (!error || typeof error !== \"object\") return;\n const candidate = error as { code?: unknown; name?: string };\n if (\n candidate.code === \"PLAN_PROTOCOL_UNSUPPORTED\" ||\n candidate.code === \"PLAN_TOO_LARGE\" ||\n candidate.code === \"PLAN_V2_INTEGRITY_UNRECOVERABLE\" ||\n candidate.code === \"FONT_FETCH_FAILED\" ||\n candidate.code === \"FONT_FETCH_UNAVAILABLE\" ||\n candidate.code === \"NOT_MEDIA_PAYLOAD\" ||\n candidate.code === \"VIDEO_SOURCE_UNRENDERABLE\" ||\n candidate.code === \"VIDEO_EXTRACTION_FAILED\" ||\n candidate.code === \"INVALID_VIDEO_METADATA\"\n ) {\n candidate.name = candidate.code;\n }\n}\n\n/**\n * Walk through Step Functions' Map-state and Task-state envelopes until\n * the discriminated event is found.\n */\n// Step Functions wraps at most `{Payload: {Input: ...}}` in our state\n// machine; 4 levels is 2\u00D7 headroom for unusual Map / Wait state\n// configurations and prevents infinite loops on malformed input.\nconst MAX_ENVELOPE_DEPTH = 4;\n\nexport function unwrapEvent(event: LambdaEvent): PlanEvent | RenderChunkEvent | AssembleEvent {\n let cursor: LambdaEvent = event;\n for (let i = 0; i < MAX_ENVELOPE_DEPTH; i++) {\n if (cursor && typeof cursor === \"object\") {\n const obj = cursor as Record<string, unknown>;\n if (typeof obj.Action === \"string\" && isLambdaAction(obj.Action)) {\n return cursor as PlanEvent | RenderChunkEvent | AssembleEvent;\n }\n if (\"Payload\" in obj) {\n cursor = obj.Payload as LambdaEvent;\n continue;\n }\n if (\"Input\" in obj) {\n cursor = obj.Input as LambdaEvent;\n continue;\n }\n }\n break;\n }\n throw new Error(\n `[handler] event has no recognised Action; unwrapped ${MAX_ENVELOPE_DEPTH} levels of Payload/Input without finding one.`,\n );\n}\n\nfunction isLambdaAction(value: string): value is LambdaAction {\n return value === \"plan\" || value === \"renderChunk\" || value === \"assemble\";\n}\n\n/**\n * Emit a single JSON line to stdout. CloudWatch ingests each line as a\n * structured event; Logs Insights queries can `filter event=\"...\"` and\n * project specific fields. We write to stdout (not stderr) because\n * Lambda's default destination for both is the same log group, and\n * Logs Insights' INFO/ERROR level parser keys off the JSON `level`\n * field, not the stream.\n */\nfunction logEvent(payload: Record<string, unknown>): void {\n console.log(JSON.stringify(payload));\n}\n\n/**\n * Compact, non-PII summary of a Lambda event for logging. The full\n * event payload can include the entire project config; we only emit\n * the routable fields (S3 URIs, chunk index, format) needed to triage\n * a failure from CloudWatch.\n */\n// Keep event variants together so logs share one redaction and summarization boundary.\n// fallow-ignore-next-line complexity\nfunction summarizeEvent(\n event: PlanEvent | RenderChunkEvent | AssembleEvent,\n): Record<string, unknown> {\n switch (event.Action) {\n case \"plan\":\n return {\n projectS3Uri: event.ProjectS3Uri,\n planOutputS3Prefix: event.PlanOutputS3Prefix,\n planProtocol: event.PlanProtocol ?? \"v1\",\n format: event.Config.format,\n fps: event.Config.fps,\n };\n case \"renderChunk\":\n return {\n planProtocol: event.PlanProtocol ?? \"v1\",\n ...(event.PlanProtocol === \"v2\"\n ? { planV2ManifestS3Uri: event.PlanV2ManifestS3Uri }\n : { planS3Uri: event.PlanS3Uri }),\n chunkIndex: event.ChunkIndex,\n format: event.Format,\n };\n case \"assemble\":\n return {\n planProtocol: event.PlanProtocol ?? \"v1\",\n ...(event.PlanProtocol === \"v2\"\n ? { planV2ManifestS3Uri: event.PlanV2ManifestS3Uri }\n : { planS3Uri: event.PlanS3Uri }),\n chunkCount: event.ChunkS3Uris.length,\n hasAudio: event.AudioS3Uri !== null,\n outputS3Uri: event.OutputS3Uri,\n format: event.Format,\n };\n }\n}\n\n/**\n * Lambda sets `TMPDIR` to `/tmp` already, but the bundled binaries (Chrome\n * + ffmpeg) live alongside the handler at `/var/task/bin/`. Add that to\n * PATH the first time the handler runs so spawn(\"ffmpeg\", \u2026) inside the\n * OSS primitives resolves to the bundled binary.\n */\nlet runtimeEnvPrimed = false;\nfunction primeRuntimeEnv(): void {\n if (runtimeEnvPrimed) return;\n runtimeEnvPrimed = true;\n const taskRoot = process.env.LAMBDA_TASK_ROOT ?? \"/var/task\";\n const bin = join(taskRoot, \"bin\");\n if (existsSync(bin)) {\n process.env.PATH = `${bin}:${process.env.PATH ?? \"\"}`;\n }\n}\n\n// \u2500\u2500 Plan \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// The v1 handler owns one transactional download, plan, archive, upload, and cleanup lifecycle.\n// fallow-ignore-next-line complexity\nasync function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise<PlanLambdaResult> {\n if (event.PlanProtocol === \"v2\") {\n return handlePlanV2(event, deps);\n }\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.plan ?? plan;\n\n // The producer's probe stage launches Chromium whenever the composition\n // needs a runtime duration probe or has unresolved sub-compositions, so\n // plan has to resolve Chrome the same way renderChunk does. Without this\n // the probe throws \"An `executablePath` or `channel` must be specified\n // for `puppeteer-core`\" the moment runProbeStage calls puppeteer.launch.\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n const chromePath = await resolveChromeExecutablePath();\n process.env.PRODUCER_HEADLESS_SHELL_PATH = chromePath;\n }\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-plan-\"));\n // We use `.tar.gz` (not `.zip`) as the project archive's on-the-wire\n // format because Lambda's Amazon Linux base image ships GNU `tar` but\n // not `unzip` in `/usr/bin`. The smoke script + future CLI both\n // produce tar.gz uploads.\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadS3ObjectToFile(s3, event.ProjectS3Uri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n\n const config: DistributedRenderConfig = {\n ...event.Config,\n };\n const result: PlanResult = await primitive(projectDir, config, planDir);\n\n // Upload the planDir as a single tarball. Step Functions cannot pass\n // a directory-shaped artifact between states; we serialize and rely on\n // the consumer (renderChunk / assemble) to untar. Audio is co-located\n // alongside the plan so RenderChunk doesn't have to pull the whole\n // plan tarball when audio isn't relevant to the chunk.\n const planTar = join(work, \"plan.tar.gz\");\n await tarDirectory(planDir, planTar);\n const planTarUri = `${trimTrailingSlash(event.PlanOutputS3Prefix)}/plan.tar.gz`;\n const audioPath = join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n const hasAudio = existsSync(audioPath) && statSync(audioPath).size > 0;\n const audioUri = hasAudio\n ? `${trimTrailingSlash(event.PlanOutputS3Prefix)}/${PLAN_AUDIO_RELATIVE_PATH}`\n : null;\n // Plan and audio are independent S3 PUTs; run them in parallel so\n // the response returns as soon as the slower of the two completes.\n await Promise.all([\n uploadFileToS3(s3, planTar, planTarUri, \"application/gzip\"),\n hasAudio && audioUri ? uploadFileToS3(s3, audioPath, audioUri, \"audio/aac\") : null,\n ]);\n\n return {\n Action: \"plan\",\n PlanS3Uri: planTarUri,\n PlanHash: result.planHash,\n ChunkCount: result.chunkCount,\n TotalFrames: result.totalFrames,\n Fps: result.fps,\n Width: result.width,\n Height: result.height,\n Format: result.format,\n HasAudio: audioUri !== null,\n AudioS3Uri: audioUri,\n FfmpegVersion: result.ffmpegVersion,\n ProducerVersion: result.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// Plan v2 orchestration is kept as one transactional boundary: stage, CAS upload,\n// and manifest-last publication must stay ordered and fail together.\n// fallow-ignore-next-line complexity\nasync function handlePlanV2(\n event: Extract<PlanEvent, { PlanProtocol: \"v2\" }>,\n deps?: HandlerDeps,\n): Promise<Extract<PlanLambdaResult, { PlanProtocol: \"v2\" }>> {\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.planV2WithPublisher ?? planV2WithPublisher;\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n process.env.PRODUCER_HEADLESS_SHELL_PATH = await resolveChromeExecutablePath();\n }\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-plan-v2-\"));\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n try {\n await downloadS3ObjectToFile(s3, event.ProjectS3Uri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n const publisher = new S3PlanV2ArtifactPublisher({\n s3,\n planOutputS3Prefix: event.PlanOutputS3Prefix,\n temporaryRoot: work,\n });\n const manifest: PlanV2Manifest = await primitive(projectDir, { ...event.Config }, publisher, {\n stagingParentDir: work,\n });\n\n return {\n Action: \"plan\",\n PlanProtocol: \"v2\",\n PlanV2ManifestS3Uri: publisher.manifestUri,\n PlanV2ArtifactS3Prefix: publisher.artifactPrefix,\n PlanHash: manifest.planHash,\n ChunkCount: manifest.chunkCount,\n TotalFrames: manifest.totalFrames,\n Fps: manifest.fps,\n Width: manifest.width,\n Height: manifest.height,\n Format: manifest.format,\n HasAudio: manifest.artifacts.some((artifact) => isPlanAudioArtifactPath(artifact.path)),\n AudioS3Uri: null,\n FfmpegVersion: manifest.ffmpegVersion,\n ProducerVersion: manifest.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// \u2500\u2500 RenderChunk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function handleRenderChunk(\n event: RenderChunkEvent,\n deps?: HandlerDeps,\n): Promise<RenderChunkLambdaResult> {\n if (event.PlanProtocol === \"v2\") {\n return handleRenderChunkV2(event, deps);\n }\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n\n // Sparticuz decompresses Chromium into /tmp on first call; warm starts\n // skip the work (path already cached). Guard the env-var mutation too so\n // a caller-supplied PRODUCER_HEADLESS_SHELL_PATH (e.g. the SAM-local\n // RIE smoke) wins over the auto-resolution.\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n const chromePath = await resolveChromeExecutablePath();\n // The OSS engine resolves Chrome via `PRODUCER_HEADLESS_SHELL_PATH`\n // first (see `browserManager.resolveHeadlessShellPath`); set it before\n // invoking the primitive so launch picks up the bundled binary.\n process.env.PRODUCER_HEADLESS_SHELL_PATH = chromePath;\n }\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-chunk-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadS3ObjectToFile(s3, event.PlanS3Uri, planTar);\n await untarDirectory(planTar, planDir);\n\n // Verify the plan's hash matches what Step Functions told us to render.\n // The producer's renderChunk re-checks internally (defense-in-depth),\n // but doing it here at the handler boundary lets us fail before paying\n // the Chrome-launch + render cost on a misrouted chunk. Throws a\n // typed PLAN_HASH_MISMATCH that Step Functions can route as\n // non-retryable.\n verifyPlanHash(planDir, event.PlanHash);\n\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n\n const result: ChunkResult = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n\n const chunkUri = await uploadChunkOutput(\n s3,\n result,\n event.ChunkOutputS3Prefix,\n event.ChunkIndex,\n );\n\n return {\n Action: \"renderChunk\",\n ChunkS3Uri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// The v2 chunk handler deliberately keeps download, verified materialization,\n// render, and upload in one lifecycle so cleanup and errors remain atomic.\n// fallow-ignore-next-line complexity\nasync function handleRenderChunkV2(\n event: Extract<RenderChunkEvent, { PlanProtocol: \"v2\" }>,\n deps?: HandlerDeps,\n): Promise<RenderChunkLambdaResult> {\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n process.env.PRODUCER_HEADLESS_SHELL_PATH = await resolveChromeExecutablePath();\n }\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-chunk-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(\n s3,\n event,\n { role: \"chunk\", chunkIndex: event.ChunkIndex },\n work,\n );\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n const result = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n const chunkUri = await uploadChunkOutput(\n s3,\n result,\n event.ChunkOutputS3Prefix,\n event.ChunkIndex,\n );\n return {\n Action: \"renderChunk\",\n ChunkS3Uri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function uploadChunkOutput(\n s3: S3Client,\n result: ChunkResult,\n prefix: string,\n chunkIndex: number,\n): Promise<string> {\n const trimmed = trimTrailingSlash(prefix);\n if (result.outputKind === \"file\") {\n const ext = result.outputPath.slice(result.outputPath.lastIndexOf(\".\"));\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}${ext}`;\n await uploadFileToS3(s3, result.outputPath, uri);\n return uri;\n }\n // frame-dir: upload as a tarball so a single S3 object represents the chunk.\n // Assemble's png-sequence path expects a directory per chunk; it untars on\n // its end.\n const tarball = `${result.outputPath}.tar.gz`;\n await tarDirectory(result.outputPath, tarball);\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}.tar.gz`;\n await uploadFileToS3(s3, tarball, uri, \"application/gzip\");\n return uri;\n}\n\n// \u2500\u2500 Assemble \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function handleAssemble(\n event: AssembleEvent,\n deps?: HandlerDeps,\n): Promise<AssembleLambdaResult> {\n if (event.PlanProtocol === \"v2\") {\n return handleAssembleV2(event, deps);\n }\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.assemble ?? assemble;\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-assemble-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadS3ObjectToFile(s3, event.PlanS3Uri, planTar);\n await untarDirectory(planTar, planDir);\n\n const chunkPaths = await downloadChunkObjects(s3, event.ChunkS3Uris, work, event.Format);\n\n let audioPath: string | null = null;\n if (event.AudioS3Uri) {\n audioPath = resolvePlanAudioPath(planDir) ?? join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n await downloadS3ObjectToFile(s3, event.AudioS3Uri, audioPath);\n }\n\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n\n const result: AssembleResult = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToS3(s3, tarball, event.OutputS3Uri, \"application/gzip\");\n } else {\n await uploadFileToS3(s3, finalOutput, event.OutputS3Uri);\n }\n\n return {\n Action: \"assemble\",\n OutputS3Uri: event.OutputS3Uri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// Assembly mirrors the chunk lifecycle while adding assembler-only artifacts;\n// keeping the steps local makes its temporary-storage ownership explicit.\n// fallow-ignore-next-line complexity\nasync function handleAssembleV2(\n event: Extract<AssembleEvent, { PlanProtocol: \"v2\" }>,\n deps?: HandlerDeps,\n): Promise<AssembleLambdaResult> {\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.assemble ?? assemble;\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-assemble-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(s3, event, { role: \"assembler\" }, work);\n // `downloadAndMaterializePlanV2` materializes atomically. Audio is\n // assembler-only and lives at the familiar v1-compatible location.\n const audioPath = resolvePlanAudioPath(planDir);\n const chunkPaths = await downloadChunkObjects(s3, event.ChunkS3Uris, work, event.Format);\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n const result = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToS3(s3, tarball, event.OutputS3Uri, \"application/gzip\");\n } else {\n await uploadFileToS3(s3, finalOutput, event.OutputS3Uri);\n }\n return {\n Action: \"assemble\",\n OutputS3Uri: event.OutputS3Uri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function downloadAndMaterializePlanV2(\n s3: S3Client,\n event: {\n PlanV2ManifestS3Uri: string;\n PlanV2ArtifactS3Prefix: string;\n PlanHash: string;\n },\n target: PlanV2MaterializationTarget,\n work: string,\n): Promise<string> {\n const transportDir = join(work, \"plan-v2\");\n mkdirSync(transportDir, { recursive: true });\n await downloadS3ObjectToFile(s3, event.PlanV2ManifestS3Uri, join(transportDir, \"plan.json\"));\n const manifest = readPlanV2Manifest(transportDir);\n if (manifest.planHash !== event.PlanHash) {\n throwPlanHashMismatch(event.PlanHash, manifest.planHash);\n }\n const artifacts = listPlanV2ArtifactsForTarget(manifest, target);\n const uniqueArtifacts = [\n ...new Map(artifacts.map((artifact) => [artifact.sha256, artifact])).values(),\n ];\n await mapConcurrent(uniqueArtifacts, 16, async (artifact) => {\n await downloadPlanV2Artifact(s3, event.PlanV2ArtifactS3Prefix, transportDir, artifact);\n });\n const planDir = join(work, \"plan\");\n materializePlanV2Target(transportDir, target, planDir);\n return planDir;\n}\n\nasync function downloadPlanV2Artifact(\n s3: S3Client,\n artifactPrefix: string,\n planV2Dir: string,\n artifact: Readonly<PlanV2Artifact>,\n): Promise<void> {\n await downloadS3ObjectToFileVerified(\n s3,\n planV2BlobUri(artifactPrefix, artifact.sha256),\n planV2BlobPath(planV2Dir, artifact.sha256),\n artifact.sha256,\n );\n}\n\nfunction planV2BlobPath(planV2Dir: string, digest: string): string {\n return join(planV2Dir, \"artifacts\", \"sha256\", digest.slice(0, 2), digest);\n}\n\nfunction planV2BlobUri(prefix: string, digest: string): string {\n return `${trimTrailingSlash(prefix)}/${digest.slice(0, 2)}/${digest}`;\n}\n\nfunction throwPlanHashMismatch(expected: string, actual: string): never {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match v2 manifest planHash=${actual}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n}\n\nasync function mapConcurrent<T>(\n values: readonly T[],\n concurrency: number,\n fn: (value: T) => Promise<void>,\n): Promise<void> {\n let cursor = 0;\n async function worker(): Promise<void> {\n while (cursor < values.length) {\n const index = cursor++;\n await fn(values[index]!);\n }\n }\n const results = await Promise.allSettled(\n Array.from({ length: Math.min(concurrency, values.length) }, () => worker()),\n );\n const failure = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n // Do not reject while sibling workers may still be writing into invocation\n // scratch. The caller removes that directory in `finally`; draining the pool\n // first prevents late S3 streams from racing cleanup after another GET fails.\n if (failure) throw failure.reason;\n}\n\nasync function downloadChunkObjects(\n s3: S3Client,\n uris: string[],\n workDir: string,\n format: DistributedFormat,\n): Promise<string[]> {\n const chunksDir = join(workDir, \"chunks\");\n mkdirSync(chunksDir, { recursive: true });\n // Each chunk is an independent S3 GET (+ untar for png-sequence). Run\n // them in parallel \u2014 assemble's wall-clock is otherwise dominated by\n // `\u03A3 chunk-download-ms` instead of `max(chunk-download-ms)`. Preserve\n // the input order by writing into a pre-sized array rather than\n // pushing as each task settles.\n const local: string[] = new Array<string>(uris.length);\n await Promise.all(\n uris.map(async (uri, i) => {\n if (!uri) {\n throw new Error(`[handler] chunk URI at index ${i} is empty`);\n }\n const { key } = parseS3Uri(uri);\n const localPath = join(chunksDir, basename(key));\n await downloadS3ObjectToFile(s3, uri, localPath);\n if (format === \"png-sequence\") {\n const dirPath = join(chunksDir, `frames-${pad(i)}`);\n await untarDirectory(localPath, dirPath);\n local[i] = dirPath;\n } else {\n local[i] = localPath;\n }\n }),\n );\n return local;\n}\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Collect every S3 URI that the handler will touch for a given event. */\n// This is an exhaustive event-union projection used only for safe log summaries.\n// fallow-ignore-next-line complexity\nfunction getEventS3Uris(event: PlanEvent | RenderChunkEvent | AssembleEvent): string[] {\n switch (event.Action) {\n case \"plan\":\n return [event.ProjectS3Uri, event.PlanOutputS3Prefix];\n case \"renderChunk\":\n return event.PlanProtocol === \"v2\"\n ? [event.PlanV2ManifestS3Uri, event.PlanV2ArtifactS3Prefix, event.ChunkOutputS3Prefix]\n : [event.PlanS3Uri, event.ChunkOutputS3Prefix];\n case \"assemble\":\n return [\n ...(event.PlanProtocol === \"v2\"\n ? [event.PlanV2ManifestS3Uri, event.PlanV2ArtifactS3Prefix]\n : [event.PlanS3Uri]),\n ...event.ChunkS3Uris,\n event.OutputS3Uri,\n event.AudioS3Uri,\n ].filter((u): u is string => u != null);\n }\n}\n\n/**\n * Verify every S3 URI in the event resolves to the configured render bucket.\n * Throws `S3_URI_NOT_ALLOWED` (non-retryable) when a URI targets a different\n * bucket, preventing event injection from reading or writing arbitrary S3 data.\n *\n * Skipped when `HYPERFRAMES_RENDER_BUCKET` is unset so existing deployments\n * without the env var continue to work.\n */\nfunction validateEventS3Uris(event: PlanEvent | RenderChunkEvent | AssembleEvent): void {\n const allowedBucket = process.env.HYPERFRAMES_RENDER_BUCKET?.trim();\n if (!allowedBucket) return;\n\n for (const uri of getEventS3Uris(event)) {\n const { bucket } = parseS3Uri(uri);\n if (bucket !== allowedBucket) {\n const err = new Error(\n `[handler] S3_URI_NOT_ALLOWED: URI ${JSON.stringify(uri)} targets bucket \"${bucket}\" but only \"${allowedBucket}\" is permitted`,\n );\n err.name = \"S3_URI_NOT_ALLOWED\";\n throw err;\n }\n }\n}\n\nfunction pad(n: number): string {\n return n.toString().padStart(4, \"0\");\n}\n\nfunction trimTrailingSlash(prefix: string): string {\n return prefix.endsWith(\"/\") ? prefix.slice(0, -1) : prefix;\n}\n\nfunction cleanupDir(dir: string): void {\n try {\n // Lambda warm starts can reuse `/tmp` across invocations; clean up\n // aggressively so we don't leak a chunk-sized footprint between renders.\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // Best-effort \u2014 leak is preferable to crashing on success path.\n }\n}\n\n/**\n * Read the untarred planDir's `plan.json` and assert its `planHash`\n * matches what the Step Functions event claims. Throws on mismatch with\n * a typed `PLAN_HASH_MISMATCH` error name so the state machine's typed\n * non-retryable list routes it correctly.\n *\n * This is defense-in-depth \u2014 the producer's `renderChunk` does the same\n * check internally \u2014 but performing it here lets us fail before paying\n * the Chrome-launch + per-frame capture cost on a misrouted chunk.\n */\nfunction verifyPlanHash(planDir: string, expected: string): void {\n const planJsonPath = join(planDir, \"plan.json\");\n let parsed: { planHash?: unknown };\n try {\n parsed = JSON.parse(readFileSync(planJsonPath, \"utf-8\")) as { planHash?: unknown };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const error = new Error(`PLAN_HASH_MISMATCH: failed to read ${planJsonPath}: ${msg}`);\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n const actual = parsed.planHash;\n if (typeof actual !== \"string\" || actual !== expected) {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match plan.json planHash=${String(actual)}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n}\n", "/**\n * Lambda-runtime Chrome resolver.\n *\n * `renderChunk()` (the only primitive that needs a browser) launches Chrome\n * via the engine's `BrowserManager`. In Lambda we can't ship the full\n * Puppeteer-managed Chrome download \u2014 Puppeteer's Chrome binary is ~330 MB\n * unzipped, well over Lambda's 250 MB ZIP-deploy ceiling.\n *\n * Two valid runtime sources:\n *\n * 1. `@sparticuz/chromium` (primary). Decompresses a Lambda-optimised\n * `chrome-headless-shell` build into `/tmp` at runtime. ~70 MB\n * compressed; the same binary the rest of the ecosystem uses for\n * headless-Chrome-in-Lambda. CDP-level BeginFrame works because the\n * command lives in the protocol, not the binary; the\n * `scripts/probe-beginframe.ts` regression guard pins this.\n *\n * 2. A bundled `chrome-headless-shell` binary (fallback). If\n * `@sparticuz/chromium`'s build ever drops `HeadlessExperimental`\n * support, we fall back to the same `chrome-headless-shell` build\n * the K8s deploy uses. The fallback raises the ZIP from ~70 MB\n * Chrome to ~140 MB Chrome \u2014 still well under 250 MB.\n *\n * The runtime path is selected by the `HYPERFRAMES_LAMBDA_CHROME_SOURCE`\n * env var (set by `build-zip.ts`):\n *\n * \"sparticuz\" \u2192 use `@sparticuz/chromium.executablePath()`\n * \"chrome-headless-shell\" \u2192 use `process.env.HYPERFRAMES_LAMBDA_CHROME_PATH`\n *\n * Adapters that bundle this package can override\n * `HYPERFRAMES_LAMBDA_CHROME_PATH` directly when running outside Lambda\n * (e.g. the SAM-local RIE smoke).\n */\n\nimport { existsSync } from \"node:fs\";\n\n/** Discriminator for the two supported Chrome sources. */\nexport type ChromeSource = \"sparticuz\" | \"chrome-headless-shell\";\n\n/**\n * Thrown when the Chrome binary resolver can't produce a usable path.\n * The class name is the SFN `Retry: { ErrorEquals: [...] }` discriminator \u2014\n * see {@link HyperframesRenderStack}'s NON_RETRYABLE_* lists.\n */\nexport class ChromeBinaryUnavailableError extends Error {\n // Lambda's runtime serializes the error envelope's `errorType` from\n // `err.name`; this class-field override sets it across the structured\n // clone. Read indirectly; fallow can't follow.\n // fallow-ignore-next-line unused-class-member\n override readonly name = \"ChromeBinaryUnavailableError\";\n readonly source: ChromeSource;\n readonly resolvedPath: string | null;\n constructor(source: ChromeSource, resolvedPath: string | null, hint: string) {\n super(`[chromium] Chrome binary unavailable (source=${source}): ${hint}`);\n this.source = source;\n this.resolvedPath = resolvedPath;\n }\n}\n\nconst SPARTICUZ_WEDGE_HINT =\n \"@sparticuz/chromium.executablePath() returned a falsy value or a path that doesn't exist on disk. \" +\n \"This typically happens after a chunk hits `Sandbox.Timedout` mid-extraction and leaves /tmp in a \" +\n \"wedged state \u2014 subsequent invocations land on the same warm instance and never re-extract. \" +\n \"Recycle the function (e.g. `aws lambda update-function-configuration ... --environment ...` with a \" +\n \"bumped marker var, or redeploy via `hyperframes lambda deploy --skip-build`) to force fresh \" +\n \"execution environments. Tracking: investigate the upstream wedge so this auto-recovers.\";\n\n/**\n * Read which Chrome source the bundled ZIP was built against. Defaults to\n * `\"sparticuz\"` so a fresh build with no env override picks the primary\n * path.\n */\nexport function resolveChromeSource(): ChromeSource {\n const raw = process.env.HYPERFRAMES_LAMBDA_CHROME_SOURCE?.toLowerCase();\n if (raw === \"chrome-headless-shell\" || raw === \"shell\") return \"chrome-headless-shell\";\n return \"sparticuz\";\n}\n\n/**\n * Resolve the absolute path to a Chrome binary suitable for BeginFrame.\n *\n * For `\"sparticuz\"`: dynamically import `@sparticuz/chromium` and call\n * `chromium.executablePath()`. The module is dynamic so a build-zip that\n * never reaches the import (because the fallback Chrome is bundled) can\n * tree-shake it out.\n *\n * For `\"chrome-headless-shell\"`: read the path from\n * `HYPERFRAMES_LAMBDA_CHROME_PATH`. Throws if absent or non-existent so a\n * misconfigured deploy fails loudly at boot rather than at first frame.\n */\n// fallow-ignore-next-line complexity\nexport async function resolveChromeExecutablePath(): Promise<string> {\n const source = resolveChromeSource();\n if (source === \"sparticuz\") {\n const mod = await loadSparticuzChromium();\n const path = await mod.executablePath();\n // Guard against the wedge described in ChromeBinaryUnavailableError.\n // sparticuz's contract is \"return the path to a usable binary\" \u2014 when\n // it returns null/undefined/\"\" we can't hand that to puppeteer-core\n // (which will throw an unrelated-looking assertion). Same when the\n // returned path doesn't exist (extraction failed but the function\n // call returned).\n if (!path || typeof path !== \"string\") {\n throw new ChromeBinaryUnavailableError(source, null, SPARTICUZ_WEDGE_HINT);\n }\n if (!existsSync(path)) {\n throw new ChromeBinaryUnavailableError(source, path, SPARTICUZ_WEDGE_HINT);\n }\n return path;\n }\n const explicit = process.env.HYPERFRAMES_LAMBDA_CHROME_PATH;\n if (!explicit) {\n throw new ChromeBinaryUnavailableError(\n source,\n null,\n \"HYPERFRAMES_LAMBDA_CHROME_SOURCE=chrome-headless-shell requires \" +\n \"HYPERFRAMES_LAMBDA_CHROME_PATH to be set to the absolute path of the bundled binary.\",\n );\n }\n if (!existsSync(explicit)) {\n throw new ChromeBinaryUnavailableError(\n source,\n explicit,\n `HYPERFRAMES_LAMBDA_CHROME_PATH=${JSON.stringify(explicit)} does not exist on disk.`,\n );\n }\n return explicit;\n}\n\n/**\n * Resolve the Chromium launch args for the selected source. For\n * `@sparticuz/chromium` we forward `chromium.args` (Lambda-tuned defaults\n * \u2014 single-process, no-sandbox, /tmp paths). For the shell fallback the\n * engine's own arg builder owns it; we return an empty array so the\n * engine's defaults apply.\n */\nexport async function resolveChromeArgs(): Promise<string[]> {\n if (resolveChromeSource() !== \"sparticuz\") return [];\n const mod = await loadSparticuzChromium();\n return mod.args;\n}\n\n/**\n * Dynamic import wrapper isolated so unit tests can stub the module without\n * jest-style module mocking gymnastics. The narrow type here pins the\n * subset of `@sparticuz/chromium`'s surface this package depends on; if\n * the upstream module ever changes shape the type error here surfaces\n * before runtime.\n */\ninterface SparticuzChromiumModule {\n args: string[];\n executablePath(): Promise<string>;\n}\n\nlet cachedSparticuz: SparticuzChromiumModule | null = null;\n\nasync function loadSparticuzChromium(): Promise<SparticuzChromiumModule> {\n if (cachedSparticuz) return cachedSparticuz;\n const mod = (await import(\"@sparticuz/chromium\")) as\n | SparticuzChromiumModule\n | { default: SparticuzChromiumModule };\n const resolved = \"default\" in mod ? mod.default : mod;\n cachedSparticuz = resolved;\n return resolved;\n}\n\n/** Test-only seam: replace the cached `@sparticuz/chromium` module. */\nexport function _setSparticuzChromiumForTests(mod: SparticuzChromiumModule | null): void {\n cachedSparticuz = mod;\n}\n", "/**\n * Map a distributed `format` to the file extension the assembled output\n * should carry on disk + in S3. Shared by `src/handler.ts` (chunk +\n * assemble output paths) and `src/sdk/renderToLambda.ts` (final\n * output key construction) so the two sides agree on what an mp4\n * looks like vs a png-sequence.\n */\n\nimport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\nexport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\n// Closed-enum lookup table. TS enforces exhaustiveness via the\n// `Record<DistributedFormat, string>` annotation \u2014 adding a format to\n// `DistributedFormat` without adding the matching key here fails to\n// typecheck, which is the same exhaustiveness guarantee a switch +\n// `_exhaustive: never` arm provides but at lower complexity.\nconst FORMAT_EXTENSIONS: Record<DistributedFormat, string> = {\n mp4: \".mp4\",\n mov: \".mov\",\n webm: \".webm\",\n \"png-sequence\": \"\",\n};\n\nexport function formatExtension(format: DistributedFormat): string {\n return FORMAT_EXTENSIONS[format];\n}\n", "/**\n * Thin S3 transport for the Lambda handler.\n *\n * The OSS distributed primitives are pure functions over local file paths;\n * the Lambda handler bridges S3 \u2194 Lambda's `/tmp` filesystem on each\n * invocation. Functions here are intentionally narrow: parse a URI, download\n * an object to a local path, upload a path/directory, tar-extract a planDir,\n * tar-pack a planDir back out.\n *\n * Tar (not zip) for planDir transit:\n * - planDirs contain symlinks (extract stage materializes them but the\n * compiled/ subtree may include linked assets); tar preserves them, zip\n * does not.\n * - We use the `tar` npm package (pure JS over `node:zlib`) \u2014 AWS\n * Lambda's `nodejs:22` base image ships neither `tar` nor `unzip` in\n * `/usr/bin`, so a system-binary tar would ENOENT in the actual\n * deployment.\n */\n\nimport {\n createReadStream,\n createWriteStream,\n existsSync,\n mkdirSync,\n rmSync,\n statSync,\n} from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { dirname } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport {\n GetObjectCommand,\n HeadObjectCommand,\n PutObjectCommand,\n type S3Client,\n} from \"@aws-sdk/client-s3\";\nimport * as tar from \"tar\";\n\n/** Parsed `s3://bucket/key` URI. */\nexport interface S3Location {\n bucket: string;\n key: string;\n}\n\n/** Parse `s3://bucket/key/path` \u2192 `{ bucket, key }`. Throws on malformed input. */\nexport function parseS3Uri(uri: string): S3Location {\n if (!uri.startsWith(\"s3://\")) {\n throw new Error(`[s3Transport] expected s3:// URI, got: ${JSON.stringify(uri)}`);\n }\n const rest = uri.slice(\"s3://\".length);\n const slash = rest.indexOf(\"/\");\n if (slash === -1) {\n throw new Error(`[s3Transport] missing key in s3 URI: ${JSON.stringify(uri)}`);\n }\n const bucket = rest.slice(0, slash);\n const key = rest.slice(slash + 1);\n if (!bucket || !key) {\n throw new Error(`[s3Transport] empty bucket or key in s3 URI: ${JSON.stringify(uri)}`);\n }\n return { bucket, key };\n}\n\n/** Build `s3://bucket/key` from a location. */\nexport function formatS3Uri(loc: S3Location): string {\n return `s3://${loc.bucket}/${loc.key}`;\n}\n\n/** Stream an S3 object to a local file path. Throws if the body is missing. */\nexport async function downloadS3ObjectToFile(\n client: S3Client,\n uri: string,\n destPath: string,\n): Promise<void> {\n const { bucket, key } = parseS3Uri(uri);\n const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));\n const body = response.Body as NodeJS.ReadableStream | undefined;\n if (!body) {\n throw new Error(`[s3Transport] s3 GetObject returned empty body for ${uri}`);\n }\n mkdirSync(dirname(destPath), { recursive: true });\n await pipeline(body, createWriteStream(destPath));\n}\n\n/** Download and verify an immutable plan-v2 artifact before materialization. */\nexport async function downloadS3ObjectToFileVerified(\n client: S3Client,\n uri: string,\n destPath: string,\n expectedSha256: string,\n): Promise<void> {\n assertSha256(expectedSha256);\n await downloadS3ObjectToFile(client, uri, destPath);\n const actual = await sha256File(destPath);\n if (actual !== expectedSha256) {\n rmSync(destPath, { force: true });\n const error = new Error(\n `[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: ${uri} expected ${expectedSha256}, got ${actual}`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n }\n}\n\n/**\n * Upload a local file's contents to an S3 URI using a streaming\n * `PutObjectCommand`. PutObject's 5 GB cap comfortably exceeds the\n * distributed pipeline's 2 GB planDir limit and the typical\n * chunk size (\u2264 200 MB), so a single PUT works for every artifact this\n * adapter handles.\n */\nexport async function uploadFileToS3(\n client: S3Client,\n localPath: string,\n uri: string,\n contentType?: string,\n): Promise<void> {\n if (!existsSync(localPath)) {\n throw new Error(`[s3Transport] upload source missing: ${localPath}`);\n }\n const { bucket, key } = parseS3Uri(uri);\n const size = statSync(localPath).size;\n await client.send(\n new PutObjectCommand({\n Bucket: bucket,\n Key: key,\n Body: createReadStream(localPath),\n ContentType: contentType,\n ContentLength: size,\n }),\n );\n}\n\n/**\n * Upload one content-addressed plan-v2 artifact exactly once.\n *\n * Existing objects are reused only when their immutable digest metadata and\n * byte length agree. A conflicting object is never overwritten: doing so\n * could change a plan already being consumed by another chunk invocation.\n */\nexport async function uploadContentAddressedFileToS3(\n client: S3Client,\n localPath: string,\n uri: string,\n expectedSha256: string,\n contentType?: string,\n): Promise<\"uploaded\" | \"reused\"> {\n assertSha256(expectedSha256);\n if (!existsSync(localPath)) {\n throw new Error(`[s3Transport] upload source missing: ${localPath}`);\n }\n const actualSha256 = await sha256File(localPath);\n if (actualSha256 !== expectedSha256) {\n const error = new Error(\n `[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: local artifact ${localPath} expected ${expectedSha256}, got ${actualSha256}`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n }\n\n const { bucket, key } = parseS3Uri(uri);\n const size = statSync(localPath).size;\n const existing = await inspectContentAddressedObject(client, bucket, key, size, expectedSha256);\n if (existing === \"matching\") return \"reused\";\n if (existing === \"conflict\") throwImmutableObjectConflict(uri);\n\n const body = createReadStream(localPath);\n try {\n await client.send(\n new PutObjectCommand({\n Bucket: bucket,\n Key: key,\n Body: body,\n ContentType: contentType,\n ContentLength: size,\n Metadata: { sha256: expectedSha256 },\n ChecksumSHA256: Buffer.from(expectedSha256, \"hex\").toString(\"base64\"),\n // HEAD followed by an unconditional PUT can overwrite a conflicting\n // object published by a concurrent planner. Conditional create makes\n // immutable CAS and fixed-key manifest publication race-safe.\n IfNoneMatch: \"*\",\n }),\n );\n return \"uploaded\";\n } catch (error) {\n if (!isS3PreconditionFailed(error)) throw error;\n const raced = await inspectContentAddressedObject(client, bucket, key, size, expectedSha256);\n if (raced === \"matching\") return \"reused\";\n if (raced === \"conflict\") throwImmutableObjectConflict(uri);\n // The winning object was deleted between the conditional failure and\n // verification. Preserve the service error so the orchestrator may retry.\n throw error;\n } finally {\n // A failed conditional request may reject before consuming the stream.\n // Explicit teardown avoids retaining the source descriptor on a warm\n // Lambda planner.\n body.destroy();\n }\n}\n\nexport async function sha256File(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(path)) {\n hash.update(chunk as Buffer);\n }\n return hash.digest(\"hex\");\n}\n\nfunction assertSha256(value: string): void {\n if (!/^[a-f0-9]{64}$/.test(value)) {\n throw new Error(\n `[s3Transport] expected lowercase SHA-256 digest, got ${JSON.stringify(value)}`,\n );\n }\n}\n\ntype ContentAddressedObjectState = \"missing\" | \"matching\" | \"conflict\";\n\nasync function inspectContentAddressedObject(\n client: S3Client,\n bucket: string,\n key: string,\n expectedSize: number,\n expectedSha256: string,\n): Promise<ContentAddressedObjectState> {\n try {\n const existing = await client.send(\n new HeadObjectCommand({ Bucket: bucket, Key: key, ChecksumMode: \"ENABLED\" }),\n );\n return existing.ContentLength === expectedSize && existing.Metadata?.sha256 === expectedSha256\n ? \"matching\"\n : \"conflict\";\n } catch (error) {\n if (isS3NotFound(error)) return \"missing\";\n throw error;\n }\n}\n\nfunction throwImmutableObjectConflict(uri: string): never {\n const error = new Error(\n `[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: immutable object ${uri} already exists with different digest metadata or size`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n}\n\nfunction isS3NotFound(error: unknown): boolean {\n if (!isRecord(error)) return false;\n const metadata = isRecord(error.$metadata) ? error.$metadata : undefined;\n return (\n error.name === \"NotFound\" || error.name === \"NoSuchKey\" || metadata?.httpStatusCode === 404\n );\n}\n\nfunction isS3PreconditionFailed(error: unknown): boolean {\n if (!isRecord(error)) return false;\n const metadata = isRecord(error.$metadata) ? error.$metadata : undefined;\n return error.name === \"PreconditionFailed\" || metadata?.httpStatusCode === 412;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Pack a directory into a `.tar.gz` at `destTarball`. Uses the `tar` npm\n * package (pure JS over `node:zlib`) rather than spawning a system tar\n * binary \u2014 the AWS Lambda Node 22 base image ships a minimal set of\n * userland tools and does NOT include `tar` in `/usr/bin`.\n */\nexport async function tarDirectory(sourceDir: string, destTarball: string): Promise<void> {\n if (!existsSync(sourceDir) || !statSync(sourceDir).isDirectory()) {\n throw new Error(`[s3Transport] tar source must be an existing directory: ${sourceDir}`);\n }\n mkdirSync(dirname(destTarball), { recursive: true });\n await tar.create({ gzip: true, file: destTarball, cwd: sourceDir }, [\".\"]);\n}\n\n/**\n * Extract a `.tar.gz` produced by {@link tarDirectory} into `destDir`.\n * The directory is created (or cleared) before extraction so a retried\n * invocation doesn't observe stale files from a prior run on the same\n * warm Lambda container.\n */\nexport async function untarDirectory(tarballPath: string, destDir: string): Promise<void> {\n if (!existsSync(tarballPath)) {\n throw new Error(`[s3Transport] tarball missing: ${tarballPath}`);\n }\n // Wipe target so the warm container's prior planDir doesn't bleed into\n // the new invocation. Lambda re-uses /tmp across invocations on the same\n // container.\n if (existsSync(destDir)) {\n rmSync(destDir, { recursive: true, force: true });\n }\n mkdirSync(destDir, { recursive: true });\n await tar.extract({ file: tarballPath, cwd: destDir });\n}\n", "import { createHash } from \"node:crypto\";\nimport { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { S3Client } from \"@aws-sdk/client-s3\";\nimport {\n PlanV2IntegrityError,\n type PlanV2ArtifactPublisher,\n type PlanV2PublishBlob,\n} from \"@hyperframes/producer/distributed\";\nimport { parseS3Uri, uploadContentAddressedFileToS3 } from \"./s3Transport.js\";\n\nexport interface S3PlanV2ArtifactPublisherOptions {\n readonly s3: S3Client;\n /** Validated render output prefix from which all v2 object keys are derived. */\n readonly planOutputS3Prefix: string;\n /** Planner-local scratch parent for the small manifest upload file. */\n readonly temporaryRoot?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction assertSha256(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !/^[a-f0-9]{64}$/.test(value)) {\n throw new PlanV2IntegrityError(`${label} must be a lowercase SHA-256 digest`);\n }\n return value;\n}\n\nfunction manifestDigests(manifestBytes: string): ReadonlySet<string> {\n let value: unknown;\n try {\n value = JSON.parse(manifestBytes);\n } catch {\n throw new PlanV2IntegrityError(\"S3 publisher received invalid manifest JSON\");\n }\n if (!isRecord(value) || !Array.isArray(value.artifacts)) {\n throw new PlanV2IntegrityError(\"S3 publisher manifest requires an artifacts array\");\n }\n return new Set(\n value.artifacts.map((artifact, index) => {\n if (!isRecord(artifact)) {\n throw new PlanV2IntegrityError(`S3 publisher artifacts[${index}] must be an object`);\n }\n return assertSha256(artifact.sha256, `S3 publisher artifacts[${index}].sha256`);\n }),\n );\n}\n\nfunction trimTrailingSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return value.slice(0, end);\n}\n\n/**\n * Manifest-last S3 implementation of the producer's plan-v2 publication seam.\n *\n * Blobs stream from the planner's private frozen directory directly to S3.\n * Successfully uploaded or safely reused digests are tracked so a manifest\n * cannot become visible before all of its references are durable.\n */\nexport class S3PlanV2ArtifactPublisher implements PlanV2ArtifactPublisher {\n readonly artifactPrefix: string;\n readonly manifestUri: string;\n readonly #s3: S3Client;\n readonly #temporaryRoot: string;\n readonly #publishedDigests = new Set<string>();\n #state: \"open\" | \"committed\" | \"aborted\" = \"open\";\n\n constructor(options: Readonly<S3PlanV2ArtifactPublisherOptions>) {\n const outputPrefix = `${trimTrailingSlash(options.planOutputS3Prefix)}/v2`;\n parseS3Uri(outputPrefix);\n this.#s3 = options.s3;\n this.artifactPrefix = `${outputPrefix}/artifacts/sha256`;\n this.manifestUri = `${outputPrefix}/manifest.json`;\n this.#temporaryRoot = options.temporaryRoot ?? tmpdir();\n mkdirSync(this.#temporaryRoot, { recursive: true });\n }\n\n async putBlob(blob: Readonly<PlanV2PublishBlob>): Promise<void> {\n this.#assertOpen(\"publish a blob\");\n const digest = assertSha256(blob.sha256, \"S3 published blob sha256\");\n const sourceSize = statSync(blob.sourcePath).size;\n if (sourceSize !== blob.sizeBytes) {\n throw new PlanV2IntegrityError(\n `S3 published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`,\n );\n }\n const uri = `${this.artifactPrefix}/${digest.slice(0, 2)}/${digest}`;\n await uploadContentAddressedFileToS3(this.#s3, blob.sourcePath, uri, digest);\n this.#publishedDigests.add(digest);\n }\n\n async commitManifest(manifestBytes: string): Promise<void> {\n this.#assertOpen(\"commit a manifest\");\n for (const digest of manifestDigests(manifestBytes)) {\n if (!this.#publishedDigests.has(digest)) {\n throw new PlanV2IntegrityError(\n `cannot commit S3 manifest before referenced blob is durable: ${digest}`,\n );\n }\n }\n\n const manifestDigest = createHash(\"sha256\").update(manifestBytes, \"utf8\").digest(\"hex\");\n const stagingDir = mkdtempSync(join(this.#temporaryRoot, \"hf-plan-v2-manifest-\"));\n const manifestPath = join(stagingDir, \"manifest.json\");\n try {\n writeFileSync(manifestPath, manifestBytes, \"utf8\");\n await uploadContentAddressedFileToS3(\n this.#s3,\n manifestPath,\n this.manifestUri,\n manifestDigest,\n \"application/json\",\n );\n this.#state = \"committed\";\n } finally {\n rmSync(stagingDir, { recursive: true, force: true });\n }\n }\n\n async abort(): Promise<void> {\n if (this.#state === \"open\") this.#state = \"aborted\";\n // Remote CAS blobs are immutable and may already be reused by a retry.\n // Without a committed manifest they are unreachable and expire under the\n // render bucket's intermediate-object lifecycle policy.\n }\n\n #assertOpen(operation: string): void {\n if (this.#state !== \"open\") {\n throw new PlanV2IntegrityError(`cannot ${operation} after publisher is ${this.#state}`);\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAaA,SAAS,cAAAA,aAAY,aAAAC,YAAW,eAAAC,cAAa,cAAc,UAAAC,SAAQ,YAAAC,iBAAgB;AACnF,SAAS,UAAAC,eAAc;AACvB,SAAS,UAAU,QAAAC,aAAY;AAC/B,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAKA;AAAA,EACA;AAAA,OACK;;;ACFP,SAAS,kBAAkB;AAUpB,IAAM,+BAAN,cAA2C,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAKpC,OAAO;AAAA,EAChB;AAAA,EACA;AAAA,EACT,YAAY,QAAsB,cAA6B,MAAc;AAC3E,UAAM,gDAAgD,MAAM,MAAM,IAAI,EAAE;AACxE,SAAK,SAAS;AACd,SAAK,eAAe;AAAA,EACtB;AACF;AAEA,IAAM,uBACJ;AAYK,SAAS,sBAAoC;AAClD,QAAM,MAAM,QAAQ,IAAI,kCAAkC,YAAY;AACtE,MAAI,QAAQ,2BAA2B,QAAQ,QAAS,QAAO;AAC/D,SAAO;AACT;AAeA,eAAsB,8BAA+C;AACnE,QAAM,SAAS,oBAAoB;AACnC,MAAI,WAAW,aAAa;AAC1B,UAAM,MAAM,MAAM,sBAAsB;AACxC,UAAM,OAAO,MAAM,IAAI,eAAe;AAOtC,QAAI,CAAC,QAAQ,OAAO,SAAS,UAAU;AACrC,YAAM,IAAI,6BAA6B,QAAQ,MAAM,oBAAoB;AAAA,IA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ACR;AACF;",
|
|
4
|
+
"sourcesContent": ["/**\n * AWS Lambda handler for HyperFrames distributed rendering.\n *\n * One Lambda function, three roles. Step Functions dispatches by setting\n * `event.Action`; the handler unwraps Map-state envelopes, primes the\n * Lambda environment (Chrome path, ffmpeg path, tmpdir), and forwards to\n * the matching OSS primitive from `@hyperframes/producer/distributed`.\n *\n * Everything heavy \u2014 capture, encode, audio mix \u2014 happens inside the OSS\n * primitives. The handler is thin glue: parse event \u2192 S3 download \u2192 call\n * primitive \u2192 S3 upload \u2192 return small JSON result.\n */\n\nimport { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport { S3Client } from \"@aws-sdk/client-s3\";\nimport {\n assemble,\n type AssembleResult,\n type ChunkRenderer,\n type ChunkResult,\n type DistributedRenderConfig,\n listPlanV2ArtifactsForTarget,\n materializePlanV2Target,\n plan,\n isPlanAudioArtifactPath,\n PLAN_AUDIO_RELATIVE_PATH,\n resolvePlanAudioPath,\n planV2WithPublisher,\n type PlanResult,\n type PlanV2Artifact,\n type PlanV2Manifest,\n type PlanV2MaterializationTarget,\n readPlanV2Manifest,\n renderChunk,\n} from \"@hyperframes/producer/distributed\";\nimport { resolveChromeExecutablePath } from \"./chromium.js\";\nimport { type DistributedFormat, formatExtension } from \"./formatExtension.js\";\nimport type {\n AssembleEvent,\n AssembleLambdaResult,\n LambdaAction,\n LambdaEvent,\n LambdaResult,\n PlanEvent,\n PlanV2Event,\n PlanLambdaResult,\n RenderChunkEvent,\n RenderChunkV2Event,\n RenderChunkLambdaResult,\n AssembleV2Event,\n} from \"./events.js\";\nimport {\n downloadS3ObjectToFile,\n downloadS3ObjectToFileVerified,\n parseS3Uri,\n tarDirectory,\n untarDirectory,\n uploadFileToS3,\n} from \"./s3Transport.js\";\nimport { S3PlanV2ArtifactPublisher } from \"./s3PlanV2Publisher.js\";\n\n/**\n * Lazily-constructed S3 client. Cached at module scope so warm Lambda\n * containers reuse the underlying HTTP keep-alive pool across invocations.\n */\nlet cachedS3Client: S3Client | null = null;\nfunction getS3Client(): S3Client {\n if (cachedS3Client) return cachedS3Client;\n cachedS3Client = new S3Client({});\n return cachedS3Client;\n}\n\n/**\n * Optional injection points used by the handler's unit tests. Production\n * callers leave these unset; the real OSS primitives are used. Tests\n * inject `s3` and `primitives` directly rather than mutating module\n * state \u2014 the dependency-injection seam is sufficient and avoids a\n * second leak point for cross-test contamination.\n */\nexport interface HandlerDeps {\n s3?: S3Client;\n primitives?: {\n plan: typeof plan;\n planV2WithPublisher?: typeof planV2WithPublisher;\n renderChunk: ChunkRenderer;\n assemble: typeof assemble;\n };\n /** Override the per-invocation `/tmp` workdir root (defaults to Lambda's `/tmp`). */\n tmpRoot?: string;\n /** Skip Chrome resolution (used by handler dispatch tests that mock renderChunk). */\n skipChromeResolution?: boolean;\n}\n\n/**\n * Lambda entry. Step Functions sometimes wraps the event in\n * `{ Payload: ... }` or `{ Input: ... }` depending on the state machine\n * shape; unwrap until we hit a discriminated event.\n */\nexport async function handler(event: LambdaEvent, deps?: HandlerDeps): Promise<LambdaResult> {\n const unwrapped = unwrapEvent(event);\n validatePlanProtocolShape(unwrapped);\n validateEventS3Uris(unwrapped);\n primeRuntimeEnv();\n // Single structured boot log line \u2014 CloudWatch Logs Insights queries\n // key off `event=handler_start` to grep for a specific Action / S3 URI\n // when triaging without attaching a debugger.\n logEvent({ event: \"handler_start\", action: unwrapped.Action, input: summarizeEvent(unwrapped) });\n try {\n switch (unwrapped.Action) {\n case \"plan\":\n return await handlePlan(unwrapped, deps);\n case \"renderChunk\":\n return await handleRenderChunk(unwrapped, deps);\n case \"assemble\":\n return await handleAssemble(unwrapped, deps);\n default: {\n // Compile-time exhaustiveness: a new LambdaAction member trips\n // the `never` assignment before the runtime error is reachable.\n const _exhaustive: never = unwrapped;\n throw new Error(\n `[handler] unknown Action: ${JSON.stringify(\n (_exhaustive as { Action?: string }).Action,\n )}. Expected one of \"plan\", \"renderChunk\", \"assemble\".`,\n );\n }\n }\n } catch (err) {\n normalizeTerminalErrorName(err);\n // Log before re-throwing so CloudWatch captures the structured\n // error context alongside Lambda's default stack trace. Otherwise\n // ops only sees the trace and has to correlate with execution\n // history to recover the action + input.\n logEvent({\n event: \"handler_error\",\n action: unwrapped.Action,\n input: summarizeEvent(unwrapped),\n message: err instanceof Error ? err.message : String(err),\n name: err instanceof Error ? err.name : undefined,\n });\n throw err;\n }\n}\n\n/**\n * AWS Lambda reports `Error.name` to Step Functions, while producer errors\n * expose stable machine codes separately. Normalize workflow-facing codes\n * whose historical class names differ from their orchestration contracts.\n */\n// The explicit error-name mapping is the public Step Functions failure contract.\n// fallow-ignore-next-line complexity\nfunction normalizeTerminalErrorName(error: unknown): void {\n if (!error || typeof error !== \"object\") return;\n const candidate = error as { code?: unknown; name?: string };\n if (\n candidate.code === \"PLAN_PROTOCOL_UNSUPPORTED\" ||\n candidate.code === \"PLAN_TOO_LARGE\" ||\n candidate.code === \"PLAN_V2_INTEGRITY_UNRECOVERABLE\" ||\n candidate.code === \"FONT_FETCH_FAILED\" ||\n candidate.code === \"FONT_FETCH_UNAVAILABLE\" ||\n candidate.code === \"NOT_MEDIA_PAYLOAD\" ||\n candidate.code === \"VIDEO_SOURCE_UNRENDERABLE\" ||\n candidate.code === \"VIDEO_EXTRACTION_FAILED\" ||\n candidate.code === \"INVALID_VIDEO_METADATA\"\n ) {\n candidate.name = candidate.code;\n }\n}\n\n/**\n * Walk through Step Functions' Map-state and Task-state envelopes until\n * the discriminated event is found.\n */\n// Step Functions wraps at most `{Payload: {Input: ...}}` in our state\n// machine; 4 levels is 2\u00D7 headroom for unusual Map / Wait state\n// configurations and prevents infinite loops on malformed input.\nconst MAX_ENVELOPE_DEPTH = 4;\n\nexport function unwrapEvent(event: LambdaEvent): PlanEvent | RenderChunkEvent | AssembleEvent {\n let cursor: LambdaEvent = event;\n for (let i = 0; i < MAX_ENVELOPE_DEPTH; i++) {\n if (cursor && typeof cursor === \"object\") {\n const obj = cursor as Record<string, unknown>;\n if (typeof obj.Action === \"string\" && isLambdaAction(obj.Action)) {\n return cursor as PlanEvent | RenderChunkEvent | AssembleEvent;\n }\n if (\"Payload\" in obj) {\n cursor = obj.Payload as LambdaEvent;\n continue;\n }\n if (\"Input\" in obj) {\n cursor = obj.Input as LambdaEvent;\n continue;\n }\n }\n break;\n }\n throw new Error(\n `[handler] event has no recognised Action; unwrapped ${MAX_ENVELOPE_DEPTH} levels of Payload/Input without finding one.`,\n );\n}\n\nfunction isLambdaAction(value: string): value is LambdaAction {\n return value === \"plan\" || value === \"renderChunk\" || value === \"assemble\";\n}\n\n// This is the single fail-closed boundary for the wire union. Keeping all\n// forbidden locator combinations together makes mixed-protocol input auditable.\n// fallow-ignore-next-line complexity\nfunction validatePlanProtocolShape(event: PlanEvent | RenderChunkEvent | AssembleEvent): void {\n const raw = event as unknown as Record<string, unknown>;\n const protocol = raw.PlanProtocol;\n if (protocol !== undefined && protocol !== \"v1\" && protocol !== \"v2\") {\n const error = new Error(\n `[handler] unsupported PlanProtocol ${JSON.stringify(protocol)}; expected \"v1\", \"v2\", or absent`,\n );\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n if (event.Action === \"plan\") return;\n\n const effectiveProtocol = protocol ?? \"v2\";\n const hasV1Locator = typeof raw.PlanS3Uri === \"string\";\n const hasV2Manifest = typeof raw.PlanV2ManifestS3Uri === \"string\";\n const hasV2Prefix = typeof raw.PlanV2ArtifactS3Prefix === \"string\";\n const valid =\n effectiveProtocol === \"v2\"\n ? !hasV1Locator && hasV2Manifest && hasV2Prefix\n : hasV1Locator && !hasV2Manifest && !hasV2Prefix;\n if (!valid) {\n const error = new Error(\n `[handler] ${effectiveProtocol} ${event.Action} event has mixed or missing plan locators`,\n );\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n if (effectiveProtocol === \"v2\" && event.Action === \"assemble\" && event.AudioS3Uri !== null) {\n const error = new Error(\"[handler] v2 assemble audio must be materialized from the manifest\");\n error.name = \"PLAN_PROTOCOL_UNSUPPORTED\";\n throw error;\n }\n}\n\n/**\n * Emit a single JSON line to stdout. CloudWatch ingests each line as a\n * structured event; Logs Insights queries can `filter event=\"...\"` and\n * project specific fields. We write to stdout (not stderr) because\n * Lambda's default destination for both is the same log group, and\n * Logs Insights' INFO/ERROR level parser keys off the JSON `level`\n * field, not the stream.\n */\nfunction logEvent(payload: Record<string, unknown>): void {\n console.log(JSON.stringify(payload));\n}\n\n/**\n * Compact, non-PII summary of a Lambda event for logging. The full\n * event payload can include the entire project config; we only emit\n * the routable fields (S3 URIs, chunk index, format) needed to triage\n * a failure from CloudWatch.\n */\n// Keep event variants together so logs share one redaction and summarization boundary.\n// fallow-ignore-next-line complexity\nfunction summarizeEvent(\n event: PlanEvent | RenderChunkEvent | AssembleEvent,\n): Record<string, unknown> {\n switch (event.Action) {\n case \"plan\":\n return {\n projectS3Uri: event.ProjectS3Uri,\n planOutputS3Prefix: event.PlanOutputS3Prefix,\n planProtocol: event.PlanProtocol ?? \"v2\",\n format: event.Config.format,\n fps: event.Config.fps,\n };\n case \"renderChunk\":\n return {\n planProtocol: event.PlanProtocol ?? \"v2\",\n ...(event.PlanProtocol !== \"v1\"\n ? { planV2ManifestS3Uri: event.PlanV2ManifestS3Uri }\n : { planS3Uri: event.PlanS3Uri }),\n chunkIndex: event.ChunkIndex,\n format: event.Format,\n };\n case \"assemble\":\n return {\n planProtocol: event.PlanProtocol ?? \"v2\",\n ...(event.PlanProtocol !== \"v1\"\n ? { planV2ManifestS3Uri: event.PlanV2ManifestS3Uri }\n : { planS3Uri: event.PlanS3Uri }),\n chunkCount: event.ChunkS3Uris.length,\n hasAudio: event.AudioS3Uri !== null,\n outputS3Uri: event.OutputS3Uri,\n format: event.Format,\n };\n }\n}\n\n/**\n * Lambda sets `TMPDIR` to `/tmp` already, but the bundled binaries (Chrome\n * + ffmpeg) live alongside the handler at `/var/task/bin/`. Add that to\n * PATH the first time the handler runs so spawn(\"ffmpeg\", \u2026) inside the\n * OSS primitives resolves to the bundled binary.\n */\nlet runtimeEnvPrimed = false;\nfunction primeRuntimeEnv(): void {\n if (runtimeEnvPrimed) return;\n runtimeEnvPrimed = true;\n const taskRoot = process.env.LAMBDA_TASK_ROOT ?? \"/var/task\";\n const bin = join(taskRoot, \"bin\");\n if (existsSync(bin)) {\n process.env.PATH = `${bin}:${process.env.PATH ?? \"\"}`;\n }\n}\n\n// \u2500\u2500 Plan \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// The v1 handler owns one transactional download, plan, archive, upload, and cleanup lifecycle.\n// fallow-ignore-next-line complexity\nasync function handlePlan(event: PlanEvent, deps?: HandlerDeps): Promise<PlanLambdaResult> {\n if (event.PlanProtocol !== \"v1\") {\n return handlePlanV2(event, deps);\n }\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.plan ?? plan;\n\n // The producer's probe stage launches Chromium whenever the composition\n // needs a runtime duration probe or has unresolved sub-compositions, so\n // plan has to resolve Chrome the same way renderChunk does. Without this\n // the probe throws \"An `executablePath` or `channel` must be specified\n // for `puppeteer-core`\" the moment runProbeStage calls puppeteer.launch.\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n const chromePath = await resolveChromeExecutablePath();\n process.env.PRODUCER_HEADLESS_SHELL_PATH = chromePath;\n }\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-plan-\"));\n // We use `.tar.gz` (not `.zip`) as the project archive's on-the-wire\n // format because Lambda's Amazon Linux base image ships GNU `tar` but\n // not `unzip` in `/usr/bin`. The smoke script + future CLI both\n // produce tar.gz uploads.\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadS3ObjectToFile(s3, event.ProjectS3Uri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n\n const config: DistributedRenderConfig = {\n ...event.Config,\n };\n const result: PlanResult = await primitive(projectDir, config, planDir);\n\n // Upload the planDir as a single tarball. Step Functions cannot pass\n // a directory-shaped artifact between states; we serialize and rely on\n // the consumer (renderChunk / assemble) to untar. Audio is co-located\n // alongside the plan so RenderChunk doesn't have to pull the whole\n // plan tarball when audio isn't relevant to the chunk.\n const planTar = join(work, \"plan.tar.gz\");\n await tarDirectory(planDir, planTar);\n const planTarUri = `${trimTrailingSlash(event.PlanOutputS3Prefix)}/plan.tar.gz`;\n const audioPath = join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n const hasAudio = existsSync(audioPath) && statSync(audioPath).size > 0;\n const audioUri = hasAudio\n ? `${trimTrailingSlash(event.PlanOutputS3Prefix)}/${PLAN_AUDIO_RELATIVE_PATH}`\n : null;\n // Plan and audio are independent S3 PUTs; run them in parallel so\n // the response returns as soon as the slower of the two completes.\n await Promise.all([\n uploadFileToS3(s3, planTar, planTarUri, \"application/gzip\"),\n hasAudio && audioUri ? uploadFileToS3(s3, audioPath, audioUri, \"audio/aac\") : null,\n ]);\n\n return {\n Action: \"plan\",\n PlanS3Uri: planTarUri,\n PlanHash: result.planHash,\n ChunkCount: result.chunkCount,\n TotalFrames: result.totalFrames,\n Fps: result.fps,\n Width: result.width,\n Height: result.height,\n Format: result.format,\n HasAudio: audioUri !== null,\n AudioS3Uri: audioUri,\n FfmpegVersion: result.ffmpegVersion,\n ProducerVersion: result.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// Plan v2 orchestration is kept as one transactional boundary: stage, CAS upload,\n// and manifest-last publication must stay ordered and fail together.\n// fallow-ignore-next-line complexity\nasync function handlePlanV2(\n event: PlanV2Event,\n deps?: HandlerDeps,\n): Promise<Extract<PlanLambdaResult, { PlanProtocol: \"v2\" }>> {\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.planV2WithPublisher ?? planV2WithPublisher;\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n process.env.PRODUCER_HEADLESS_SHELL_PATH = await resolveChromeExecutablePath();\n }\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-plan-v2-\"));\n const projectArchive = join(work, \"project.tar.gz\");\n const projectDir = join(work, \"project\");\n try {\n await downloadS3ObjectToFile(s3, event.ProjectS3Uri, projectArchive);\n await untarDirectory(projectArchive, projectDir);\n const publisher = new S3PlanV2ArtifactPublisher({\n s3,\n planOutputS3Prefix: event.PlanOutputS3Prefix,\n temporaryRoot: work,\n });\n const manifest: PlanV2Manifest = await primitive(projectDir, { ...event.Config }, publisher, {\n stagingParentDir: work,\n });\n\n return {\n Action: \"plan\",\n PlanProtocol: \"v2\",\n PlanV2ManifestS3Uri: publisher.manifestUri,\n PlanV2ArtifactS3Prefix: publisher.artifactPrefix,\n PlanHash: manifest.planHash,\n ChunkCount: manifest.chunkCount,\n TotalFrames: manifest.totalFrames,\n Fps: manifest.fps,\n Width: manifest.width,\n Height: manifest.height,\n Format: manifest.format,\n HasAudio: manifest.artifacts.some((artifact) => isPlanAudioArtifactPath(artifact.path)),\n AudioS3Uri: null,\n FfmpegVersion: manifest.ffmpegVersion,\n ProducerVersion: manifest.producerVersion,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// \u2500\u2500 RenderChunk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function handleRenderChunk(\n event: RenderChunkEvent,\n deps?: HandlerDeps,\n): Promise<RenderChunkLambdaResult> {\n if (event.PlanProtocol !== \"v1\") {\n return handleRenderChunkV2(event, deps);\n }\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n\n // Sparticuz decompresses Chromium into /tmp on first call; warm starts\n // skip the work (path already cached). Guard the env-var mutation too so\n // a caller-supplied PRODUCER_HEADLESS_SHELL_PATH (e.g. the SAM-local\n // RIE smoke) wins over the auto-resolution.\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n const chromePath = await resolveChromeExecutablePath();\n // The OSS engine resolves Chrome via `PRODUCER_HEADLESS_SHELL_PATH`\n // first (see `browserManager.resolveHeadlessShellPath`); set it before\n // invoking the primitive so launch picks up the bundled binary.\n process.env.PRODUCER_HEADLESS_SHELL_PATH = chromePath;\n }\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-chunk-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadS3ObjectToFile(s3, event.PlanS3Uri, planTar);\n await untarDirectory(planTar, planDir);\n\n // Verify the plan's hash matches what Step Functions told us to render.\n // The producer's renderChunk re-checks internally (defense-in-depth),\n // but doing it here at the handler boundary lets us fail before paying\n // the Chrome-launch + render cost on a misrouted chunk. Throws a\n // typed PLAN_HASH_MISMATCH that Step Functions can route as\n // non-retryable.\n verifyPlanHash(planDir, event.PlanHash);\n\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n\n const result: ChunkResult = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n\n const chunkUri = await uploadChunkOutput(\n s3,\n result,\n event.ChunkOutputS3Prefix,\n event.ChunkIndex,\n );\n\n return {\n Action: \"renderChunk\",\n ChunkS3Uri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// The v2 chunk handler deliberately keeps download, verified materialization,\n// render, and upload in one lifecycle so cleanup and errors remain atomic.\n// fallow-ignore-next-line complexity\nasync function handleRenderChunkV2(\n event: RenderChunkV2Event,\n deps?: HandlerDeps,\n): Promise<RenderChunkLambdaResult> {\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.renderChunk ?? renderChunk;\n if (!deps?.skipChromeResolution && !process.env.PRODUCER_HEADLESS_SHELL_PATH) {\n process.env.PRODUCER_HEADLESS_SHELL_PATH = await resolveChromeExecutablePath();\n }\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-chunk-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(\n s3,\n event,\n { role: \"chunk\", chunkIndex: event.ChunkIndex },\n work,\n );\n const chunkOutputBase = join(\n work,\n event.Format === \"png-sequence\"\n ? `chunk-${pad(event.ChunkIndex)}`\n : `chunk-${pad(event.ChunkIndex)}${formatExtension(event.Format)}`,\n );\n const result = await primitive(planDir, event.ChunkIndex, chunkOutputBase);\n const chunkUri = await uploadChunkOutput(\n s3,\n result,\n event.ChunkOutputS3Prefix,\n event.ChunkIndex,\n );\n return {\n Action: \"renderChunk\",\n ChunkS3Uri: chunkUri,\n ChunkIndex: event.ChunkIndex,\n Sha256: result.sha256,\n FramesEncoded: result.framesEncoded,\n CaptureMode: result.captureMode,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function uploadChunkOutput(\n s3: S3Client,\n result: ChunkResult,\n prefix: string,\n chunkIndex: number,\n): Promise<string> {\n const trimmed = trimTrailingSlash(prefix);\n if (result.outputKind === \"file\") {\n const ext = result.outputPath.slice(result.outputPath.lastIndexOf(\".\"));\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}${ext}`;\n await uploadFileToS3(s3, result.outputPath, uri);\n return uri;\n }\n // frame-dir: upload as a tarball so a single S3 object represents the chunk.\n // Assemble's png-sequence path expects a directory per chunk; it untars on\n // its end.\n const tarball = `${result.outputPath}.tar.gz`;\n await tarDirectory(result.outputPath, tarball);\n const uri = `${trimmed}/chunks/${pad(chunkIndex)}.tar.gz`;\n await uploadFileToS3(s3, tarball, uri, \"application/gzip\");\n return uri;\n}\n\n// \u2500\u2500 Assemble \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function handleAssemble(\n event: AssembleEvent,\n deps?: HandlerDeps,\n): Promise<AssembleLambdaResult> {\n if (event.PlanProtocol !== \"v1\") {\n return handleAssembleV2(event, deps);\n }\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.assemble ?? assemble;\n\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-assemble-\"));\n const planTar = join(work, \"plan.tar.gz\");\n const planDir = join(work, \"plan\");\n\n try {\n await downloadS3ObjectToFile(s3, event.PlanS3Uri, planTar);\n await untarDirectory(planTar, planDir);\n\n const chunkPaths = await downloadChunkObjects(s3, event.ChunkS3Uris, work, event.Format);\n\n let audioPath: string | null = null;\n if (event.AudioS3Uri) {\n audioPath = resolvePlanAudioPath(planDir) ?? join(planDir, PLAN_AUDIO_RELATIVE_PATH);\n await downloadS3ObjectToFile(s3, event.AudioS3Uri, audioPath);\n }\n\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n\n const result: AssembleResult = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToS3(s3, tarball, event.OutputS3Uri, \"application/gzip\");\n } else {\n await uploadFileToS3(s3, finalOutput, event.OutputS3Uri);\n }\n\n return {\n Action: \"assemble\",\n OutputS3Uri: event.OutputS3Uri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\n// Assembly mirrors the chunk lifecycle while adding assembler-only artifacts;\n// keeping the steps local makes its temporary-storage ownership explicit.\n// fallow-ignore-next-line complexity\nasync function handleAssembleV2(\n event: AssembleV2Event,\n deps?: HandlerDeps,\n): Promise<AssembleLambdaResult> {\n const started = Date.now();\n const s3 = deps?.s3 ?? getS3Client();\n const primitive = deps?.primitives?.assemble ?? assemble;\n const work = mkdtempSync(join(deps?.tmpRoot ?? tmpdir(), \"hf-lambda-assemble-v2-\"));\n try {\n const planDir = await downloadAndMaterializePlanV2(s3, event, { role: \"assembler\" }, work);\n // `downloadAndMaterializePlanV2` materializes atomically. Audio is\n // assembler-only and lives at the familiar v1-compatible location.\n const audioPath = resolvePlanAudioPath(planDir);\n const chunkPaths = await downloadChunkObjects(s3, event.ChunkS3Uris, work, event.Format);\n const finalOutput =\n event.Format === \"png-sequence\"\n ? join(work, \"output-frames\")\n : join(work, `output${formatExtension(event.Format)}`);\n const result = await primitive(planDir, chunkPaths, audioPath, finalOutput, {\n cfr: event.Cfr === true,\n });\n if (event.Format === \"png-sequence\") {\n const tarball = `${finalOutput}.tar.gz`;\n await tarDirectory(finalOutput, tarball);\n await uploadFileToS3(s3, tarball, event.OutputS3Uri, \"application/gzip\");\n } else {\n await uploadFileToS3(s3, finalOutput, event.OutputS3Uri);\n }\n return {\n Action: \"assemble\",\n OutputS3Uri: event.OutputS3Uri,\n FramesEncoded: result.framesEncoded,\n FileSize: result.fileSize,\n DurationMs: Date.now() - started,\n };\n } finally {\n cleanupDir(work);\n }\n}\n\nasync function downloadAndMaterializePlanV2(\n s3: S3Client,\n event: {\n PlanV2ManifestS3Uri: string;\n PlanV2ArtifactS3Prefix: string;\n PlanHash: string;\n },\n target: PlanV2MaterializationTarget,\n work: string,\n): Promise<string> {\n const transportDir = join(work, \"plan-v2\");\n mkdirSync(transportDir, { recursive: true });\n await downloadS3ObjectToFile(s3, event.PlanV2ManifestS3Uri, join(transportDir, \"plan.json\"));\n const manifest = readPlanV2Manifest(transportDir);\n if (manifest.planHash !== event.PlanHash) {\n throwPlanHashMismatch(event.PlanHash, manifest.planHash);\n }\n const artifacts = listPlanV2ArtifactsForTarget(manifest, target);\n const uniqueArtifacts = [\n ...new Map(artifacts.map((artifact) => [artifact.sha256, artifact])).values(),\n ];\n await mapConcurrent(uniqueArtifacts, 16, async (artifact) => {\n await downloadPlanV2Artifact(s3, event.PlanV2ArtifactS3Prefix, transportDir, artifact);\n });\n const planDir = join(work, \"plan\");\n materializePlanV2Target(transportDir, target, planDir);\n return planDir;\n}\n\nasync function downloadPlanV2Artifact(\n s3: S3Client,\n artifactPrefix: string,\n planV2Dir: string,\n artifact: Readonly<PlanV2Artifact>,\n): Promise<void> {\n await downloadS3ObjectToFileVerified(\n s3,\n planV2BlobUri(artifactPrefix, artifact.sha256),\n planV2BlobPath(planV2Dir, artifact.sha256),\n artifact.sha256,\n );\n}\n\nfunction planV2BlobPath(planV2Dir: string, digest: string): string {\n return join(planV2Dir, \"artifacts\", \"sha256\", digest.slice(0, 2), digest);\n}\n\nfunction planV2BlobUri(prefix: string, digest: string): string {\n return `${trimTrailingSlash(prefix)}/${digest.slice(0, 2)}/${digest}`;\n}\n\nfunction throwPlanHashMismatch(expected: string, actual: string): never {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match v2 manifest planHash=${actual}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n}\n\nasync function mapConcurrent<T>(\n values: readonly T[],\n concurrency: number,\n fn: (value: T) => Promise<void>,\n): Promise<void> {\n let cursor = 0;\n async function worker(): Promise<void> {\n while (cursor < values.length) {\n const index = cursor++;\n await fn(values[index]!);\n }\n }\n const results = await Promise.allSettled(\n Array.from({ length: Math.min(concurrency, values.length) }, () => worker()),\n );\n const failure = results.find(\n (result): result is PromiseRejectedResult => result.status === \"rejected\",\n );\n // Do not reject while sibling workers may still be writing into invocation\n // scratch. The caller removes that directory in `finally`; draining the pool\n // first prevents late S3 streams from racing cleanup after another GET fails.\n if (failure) throw failure.reason;\n}\n\nasync function downloadChunkObjects(\n s3: S3Client,\n uris: string[],\n workDir: string,\n format: DistributedFormat,\n): Promise<string[]> {\n const chunksDir = join(workDir, \"chunks\");\n mkdirSync(chunksDir, { recursive: true });\n // Each chunk is an independent S3 GET (+ untar for png-sequence). Run\n // them in parallel \u2014 assemble's wall-clock is otherwise dominated by\n // `\u03A3 chunk-download-ms` instead of `max(chunk-download-ms)`. Preserve\n // the input order by writing into a pre-sized array rather than\n // pushing as each task settles.\n const local: string[] = new Array<string>(uris.length);\n await Promise.all(\n uris.map(async (uri, i) => {\n if (!uri) {\n throw new Error(`[handler] chunk URI at index ${i} is empty`);\n }\n const { key } = parseS3Uri(uri);\n const localPath = join(chunksDir, basename(key));\n await downloadS3ObjectToFile(s3, uri, localPath);\n if (format === \"png-sequence\") {\n const dirPath = join(chunksDir, `frames-${pad(i)}`);\n await untarDirectory(localPath, dirPath);\n local[i] = dirPath;\n } else {\n local[i] = localPath;\n }\n }),\n );\n return local;\n}\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Collect every S3 URI that the handler will touch for a given event. */\n// This is an exhaustive event-union projection used only for safe log summaries.\n// fallow-ignore-next-line complexity\nfunction getEventS3Uris(event: PlanEvent | RenderChunkEvent | AssembleEvent): string[] {\n switch (event.Action) {\n case \"plan\":\n return [event.ProjectS3Uri, event.PlanOutputS3Prefix];\n case \"renderChunk\":\n return event.PlanProtocol !== \"v1\"\n ? [event.PlanV2ManifestS3Uri, event.PlanV2ArtifactS3Prefix, event.ChunkOutputS3Prefix]\n : [event.PlanS3Uri, event.ChunkOutputS3Prefix];\n case \"assemble\":\n return [\n ...(event.PlanProtocol !== \"v1\"\n ? [event.PlanV2ManifestS3Uri, event.PlanV2ArtifactS3Prefix]\n : [event.PlanS3Uri]),\n ...event.ChunkS3Uris,\n event.OutputS3Uri,\n event.AudioS3Uri,\n ].filter((u): u is string => u != null);\n }\n}\n\n/**\n * Verify every S3 URI in the event resolves to the configured render bucket.\n * Throws `S3_URI_NOT_ALLOWED` (non-retryable) when a URI targets a different\n * bucket, preventing event injection from reading or writing arbitrary S3 data.\n *\n * Skipped when `HYPERFRAMES_RENDER_BUCKET` is unset so existing deployments\n * without the env var continue to work.\n */\nfunction validateEventS3Uris(event: PlanEvent | RenderChunkEvent | AssembleEvent): void {\n const allowedBucket = process.env.HYPERFRAMES_RENDER_BUCKET?.trim();\n if (!allowedBucket) return;\n\n for (const uri of getEventS3Uris(event)) {\n const { bucket } = parseS3Uri(uri);\n if (bucket !== allowedBucket) {\n const err = new Error(\n `[handler] S3_URI_NOT_ALLOWED: URI ${JSON.stringify(uri)} targets bucket \"${bucket}\" but only \"${allowedBucket}\" is permitted`,\n );\n err.name = \"S3_URI_NOT_ALLOWED\";\n throw err;\n }\n }\n}\n\nfunction pad(n: number): string {\n return n.toString().padStart(4, \"0\");\n}\n\nfunction trimTrailingSlash(prefix: string): string {\n return prefix.endsWith(\"/\") ? prefix.slice(0, -1) : prefix;\n}\n\nfunction cleanupDir(dir: string): void {\n try {\n // Lambda warm starts can reuse `/tmp` across invocations; clean up\n // aggressively so we don't leak a chunk-sized footprint between renders.\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // Best-effort \u2014 leak is preferable to crashing on success path.\n }\n}\n\n/**\n * Read the untarred planDir's `plan.json` and assert its `planHash`\n * matches what the Step Functions event claims. Throws on mismatch with\n * a typed `PLAN_HASH_MISMATCH` error name so the state machine's typed\n * non-retryable list routes it correctly.\n *\n * This is defense-in-depth \u2014 the producer's `renderChunk` does the same\n * check internally \u2014 but performing it here lets us fail before paying\n * the Chrome-launch + per-frame capture cost on a misrouted chunk.\n */\nfunction verifyPlanHash(planDir: string, expected: string): void {\n const planJsonPath = join(planDir, \"plan.json\");\n let parsed: { planHash?: unknown };\n try {\n parsed = JSON.parse(readFileSync(planJsonPath, \"utf-8\")) as { planHash?: unknown };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const error = new Error(`PLAN_HASH_MISMATCH: failed to read ${planJsonPath}: ${msg}`);\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n const actual = parsed.planHash;\n if (typeof actual !== \"string\" || actual !== expected) {\n const error = new Error(\n `PLAN_HASH_MISMATCH: event PlanHash=${expected} did not match plan.json planHash=${String(actual)}`,\n );\n error.name = \"PLAN_HASH_MISMATCH\";\n throw error;\n }\n}\n", "/**\n * Lambda-runtime Chrome resolver.\n *\n * `renderChunk()` (the only primitive that needs a browser) launches Chrome\n * via the engine's `BrowserManager`. In Lambda we can't ship the full\n * Puppeteer-managed Chrome download \u2014 Puppeteer's Chrome binary is ~330 MB\n * unzipped, well over Lambda's 250 MB ZIP-deploy ceiling.\n *\n * Two valid runtime sources:\n *\n * 1. `@sparticuz/chromium` (primary). Decompresses a Lambda-optimised\n * `chrome-headless-shell` build into `/tmp` at runtime. ~70 MB\n * compressed; the same binary the rest of the ecosystem uses for\n * headless-Chrome-in-Lambda. CDP-level BeginFrame works because the\n * command lives in the protocol, not the binary; the\n * `scripts/probe-beginframe.ts` regression guard pins this.\n *\n * 2. A bundled `chrome-headless-shell` binary (fallback). If\n * `@sparticuz/chromium`'s build ever drops `HeadlessExperimental`\n * support, we fall back to the same `chrome-headless-shell` build\n * the K8s deploy uses. The fallback raises the ZIP from ~70 MB\n * Chrome to ~140 MB Chrome \u2014 still well under 250 MB.\n *\n * The runtime path is selected by the `HYPERFRAMES_LAMBDA_CHROME_SOURCE`\n * env var (set by `build-zip.ts`):\n *\n * \"sparticuz\" \u2192 use `@sparticuz/chromium.executablePath()`\n * \"chrome-headless-shell\" \u2192 use `process.env.HYPERFRAMES_LAMBDA_CHROME_PATH`\n *\n * Adapters that bundle this package can override\n * `HYPERFRAMES_LAMBDA_CHROME_PATH` directly when running outside Lambda\n * (e.g. the SAM-local RIE smoke).\n */\n\nimport { existsSync } from \"node:fs\";\n\n/** Discriminator for the two supported Chrome sources. */\nexport type ChromeSource = \"sparticuz\" | \"chrome-headless-shell\";\n\n/**\n * Thrown when the Chrome binary resolver can't produce a usable path.\n * The class name is the SFN `Retry: { ErrorEquals: [...] }` discriminator \u2014\n * see {@link HyperframesRenderStack}'s NON_RETRYABLE_* lists.\n */\nexport class ChromeBinaryUnavailableError extends Error {\n // Lambda's runtime serializes the error envelope's `errorType` from\n // `err.name`; this class-field override sets it across the structured\n // clone. Read indirectly; fallow can't follow.\n // fallow-ignore-next-line unused-class-member\n override readonly name = \"ChromeBinaryUnavailableError\";\n readonly source: ChromeSource;\n readonly resolvedPath: string | null;\n constructor(source: ChromeSource, resolvedPath: string | null, hint: string) {\n super(`[chromium] Chrome binary unavailable (source=${source}): ${hint}`);\n this.source = source;\n this.resolvedPath = resolvedPath;\n }\n}\n\nconst SPARTICUZ_WEDGE_HINT =\n \"@sparticuz/chromium.executablePath() returned a falsy value or a path that doesn't exist on disk. \" +\n \"This typically happens after a chunk hits `Sandbox.Timedout` mid-extraction and leaves /tmp in a \" +\n \"wedged state \u2014 subsequent invocations land on the same warm instance and never re-extract. \" +\n \"Recycle the function (e.g. `aws lambda update-function-configuration ... --environment ...` with a \" +\n \"bumped marker var, or redeploy via `hyperframes lambda deploy --skip-build`) to force fresh \" +\n \"execution environments. Tracking: investigate the upstream wedge so this auto-recovers.\";\n\n/**\n * Read which Chrome source the bundled ZIP was built against. Defaults to\n * `\"sparticuz\"` so a fresh build with no env override picks the primary\n * path.\n */\nexport function resolveChromeSource(): ChromeSource {\n const raw = process.env.HYPERFRAMES_LAMBDA_CHROME_SOURCE?.toLowerCase();\n if (raw === \"chrome-headless-shell\" || raw === \"shell\") return \"chrome-headless-shell\";\n return \"sparticuz\";\n}\n\n/**\n * Resolve the absolute path to a Chrome binary suitable for BeginFrame.\n *\n * For `\"sparticuz\"`: dynamically import `@sparticuz/chromium` and call\n * `chromium.executablePath()`. The module is dynamic so a build-zip that\n * never reaches the import (because the fallback Chrome is bundled) can\n * tree-shake it out.\n *\n * For `\"chrome-headless-shell\"`: read the path from\n * `HYPERFRAMES_LAMBDA_CHROME_PATH`. Throws if absent or non-existent so a\n * misconfigured deploy fails loudly at boot rather than at first frame.\n */\n// fallow-ignore-next-line complexity\nexport async function resolveChromeExecutablePath(): Promise<string> {\n const source = resolveChromeSource();\n if (source === \"sparticuz\") {\n const mod = await loadSparticuzChromium();\n const path = await mod.executablePath();\n // Guard against the wedge described in ChromeBinaryUnavailableError.\n // sparticuz's contract is \"return the path to a usable binary\" \u2014 when\n // it returns null/undefined/\"\" we can't hand that to puppeteer-core\n // (which will throw an unrelated-looking assertion). Same when the\n // returned path doesn't exist (extraction failed but the function\n // call returned).\n if (!path || typeof path !== \"string\") {\n throw new ChromeBinaryUnavailableError(source, null, SPARTICUZ_WEDGE_HINT);\n }\n if (!existsSync(path)) {\n throw new ChromeBinaryUnavailableError(source, path, SPARTICUZ_WEDGE_HINT);\n }\n return path;\n }\n const explicit = process.env.HYPERFRAMES_LAMBDA_CHROME_PATH;\n if (!explicit) {\n throw new ChromeBinaryUnavailableError(\n source,\n null,\n \"HYPERFRAMES_LAMBDA_CHROME_SOURCE=chrome-headless-shell requires \" +\n \"HYPERFRAMES_LAMBDA_CHROME_PATH to be set to the absolute path of the bundled binary.\",\n );\n }\n if (!existsSync(explicit)) {\n throw new ChromeBinaryUnavailableError(\n source,\n explicit,\n `HYPERFRAMES_LAMBDA_CHROME_PATH=${JSON.stringify(explicit)} does not exist on disk.`,\n );\n }\n return explicit;\n}\n\n/**\n * Resolve the Chromium launch args for the selected source. For\n * `@sparticuz/chromium` we forward `chromium.args` (Lambda-tuned defaults\n * \u2014 single-process, no-sandbox, /tmp paths). For the shell fallback the\n * engine's own arg builder owns it; we return an empty array so the\n * engine's defaults apply.\n */\nexport async function resolveChromeArgs(): Promise<string[]> {\n if (resolveChromeSource() !== \"sparticuz\") return [];\n const mod = await loadSparticuzChromium();\n return mod.args;\n}\n\n/**\n * Dynamic import wrapper isolated so unit tests can stub the module without\n * jest-style module mocking gymnastics. The narrow type here pins the\n * subset of `@sparticuz/chromium`'s surface this package depends on; if\n * the upstream module ever changes shape the type error here surfaces\n * before runtime.\n */\ninterface SparticuzChromiumModule {\n args: string[];\n executablePath(): Promise<string>;\n}\n\nlet cachedSparticuz: SparticuzChromiumModule | null = null;\n\nasync function loadSparticuzChromium(): Promise<SparticuzChromiumModule> {\n if (cachedSparticuz) return cachedSparticuz;\n const mod = (await import(\"@sparticuz/chromium\")) as\n | SparticuzChromiumModule\n | { default: SparticuzChromiumModule };\n const resolved = \"default\" in mod ? mod.default : mod;\n cachedSparticuz = resolved;\n return resolved;\n}\n\n/** Test-only seam: replace the cached `@sparticuz/chromium` module. */\nexport function _setSparticuzChromiumForTests(mod: SparticuzChromiumModule | null): void {\n cachedSparticuz = mod;\n}\n", "/**\n * Map a distributed `format` to the file extension the assembled output\n * should carry on disk + in S3. Shared by `src/handler.ts` (chunk +\n * assemble output paths) and `src/sdk/renderToLambda.ts` (final\n * output key construction) so the two sides agree on what an mp4\n * looks like vs a png-sequence.\n */\n\nimport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\nexport type { DistributedFormat } from \"@hyperframes/producer/distributed\";\n\n// Closed-enum lookup table. TS enforces exhaustiveness via the\n// `Record<DistributedFormat, string>` annotation \u2014 adding a format to\n// `DistributedFormat` without adding the matching key here fails to\n// typecheck, which is the same exhaustiveness guarantee a switch +\n// `_exhaustive: never` arm provides but at lower complexity.\nconst FORMAT_EXTENSIONS: Record<DistributedFormat, string> = {\n mp4: \".mp4\",\n mov: \".mov\",\n webm: \".webm\",\n \"png-sequence\": \"\",\n};\n\nexport function formatExtension(format: DistributedFormat): string {\n return FORMAT_EXTENSIONS[format];\n}\n", "/**\n * Thin S3 transport for the Lambda handler.\n *\n * The OSS distributed primitives are pure functions over local file paths;\n * the Lambda handler bridges S3 \u2194 Lambda's `/tmp` filesystem on each\n * invocation. Functions here are intentionally narrow: parse a URI, download\n * an object to a local path, upload a path/directory, tar-extract a planDir,\n * tar-pack a planDir back out.\n *\n * Tar (not zip) for planDir transit:\n * - planDirs contain symlinks (extract stage materializes them but the\n * compiled/ subtree may include linked assets); tar preserves them, zip\n * does not.\n * - We use the `tar` npm package (pure JS over `node:zlib`) \u2014 AWS\n * Lambda's `nodejs:22` base image ships neither `tar` nor `unzip` in\n * `/usr/bin`, so a system-binary tar would ENOENT in the actual\n * deployment.\n */\n\nimport {\n createReadStream,\n createWriteStream,\n existsSync,\n mkdirSync,\n rmSync,\n statSync,\n} from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { dirname } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport {\n GetObjectCommand,\n HeadObjectCommand,\n PutObjectCommand,\n type S3Client,\n} from \"@aws-sdk/client-s3\";\nimport * as tar from \"tar\";\n\n/** Parsed `s3://bucket/key` URI. */\nexport interface S3Location {\n bucket: string;\n key: string;\n}\n\n/** Parse `s3://bucket/key/path` \u2192 `{ bucket, key }`. Throws on malformed input. */\nexport function parseS3Uri(uri: string): S3Location {\n if (!uri.startsWith(\"s3://\")) {\n throw new Error(`[s3Transport] expected s3:// URI, got: ${JSON.stringify(uri)}`);\n }\n const rest = uri.slice(\"s3://\".length);\n const slash = rest.indexOf(\"/\");\n if (slash === -1) {\n throw new Error(`[s3Transport] missing key in s3 URI: ${JSON.stringify(uri)}`);\n }\n const bucket = rest.slice(0, slash);\n const key = rest.slice(slash + 1);\n if (!bucket || !key) {\n throw new Error(`[s3Transport] empty bucket or key in s3 URI: ${JSON.stringify(uri)}`);\n }\n return { bucket, key };\n}\n\n/** Build `s3://bucket/key` from a location. */\nexport function formatS3Uri(loc: S3Location): string {\n return `s3://${loc.bucket}/${loc.key}`;\n}\n\n/** Stream an S3 object to a local file path. Throws if the body is missing. */\nexport async function downloadS3ObjectToFile(\n client: S3Client,\n uri: string,\n destPath: string,\n): Promise<void> {\n const { bucket, key } = parseS3Uri(uri);\n const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));\n const body = response.Body as NodeJS.ReadableStream | undefined;\n if (!body) {\n throw new Error(`[s3Transport] s3 GetObject returned empty body for ${uri}`);\n }\n mkdirSync(dirname(destPath), { recursive: true });\n await pipeline(body, createWriteStream(destPath));\n}\n\n/** Download and verify an immutable plan-v2 artifact before materialization. */\nexport async function downloadS3ObjectToFileVerified(\n client: S3Client,\n uri: string,\n destPath: string,\n expectedSha256: string,\n): Promise<void> {\n assertSha256(expectedSha256);\n await downloadS3ObjectToFile(client, uri, destPath);\n const actual = await sha256File(destPath);\n if (actual !== expectedSha256) {\n rmSync(destPath, { force: true });\n const error = new Error(\n `[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: ${uri} expected ${expectedSha256}, got ${actual}`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n }\n}\n\n/**\n * Upload a local file's contents to an S3 URI using a streaming\n * `PutObjectCommand`. PutObject's 5 GB cap comfortably exceeds the\n * distributed pipeline's 2 GB planDir limit and the typical\n * chunk size (\u2264 200 MB), so a single PUT works for every artifact this\n * adapter handles.\n */\nexport async function uploadFileToS3(\n client: S3Client,\n localPath: string,\n uri: string,\n contentType?: string,\n): Promise<void> {\n if (!existsSync(localPath)) {\n throw new Error(`[s3Transport] upload source missing: ${localPath}`);\n }\n const { bucket, key } = parseS3Uri(uri);\n const size = statSync(localPath).size;\n await client.send(\n new PutObjectCommand({\n Bucket: bucket,\n Key: key,\n Body: createReadStream(localPath),\n ContentType: contentType,\n ContentLength: size,\n }),\n );\n}\n\n/**\n * Upload one content-addressed plan-v2 artifact exactly once.\n *\n * Existing objects are reused only when their immutable digest metadata and\n * byte length agree. A conflicting object is never overwritten: doing so\n * could change a plan already being consumed by another chunk invocation.\n */\nexport async function uploadContentAddressedFileToS3(\n client: S3Client,\n localPath: string,\n uri: string,\n expectedSha256: string,\n contentType?: string,\n): Promise<\"uploaded\" | \"reused\"> {\n assertSha256(expectedSha256);\n if (!existsSync(localPath)) {\n throw new Error(`[s3Transport] upload source missing: ${localPath}`);\n }\n const actualSha256 = await sha256File(localPath);\n if (actualSha256 !== expectedSha256) {\n const error = new Error(\n `[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: local artifact ${localPath} expected ${expectedSha256}, got ${actualSha256}`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n }\n\n const { bucket, key } = parseS3Uri(uri);\n const size = statSync(localPath).size;\n const existing = await inspectContentAddressedObject(client, bucket, key, size, expectedSha256);\n if (existing === \"matching\") return \"reused\";\n if (existing === \"conflict\") throwImmutableObjectConflict(uri);\n\n const body = createReadStream(localPath);\n try {\n await client.send(\n new PutObjectCommand({\n Bucket: bucket,\n Key: key,\n Body: body,\n ContentType: contentType,\n ContentLength: size,\n Metadata: { sha256: expectedSha256 },\n ChecksumSHA256: Buffer.from(expectedSha256, \"hex\").toString(\"base64\"),\n // HEAD followed by an unconditional PUT can overwrite a conflicting\n // object published by a concurrent planner. Conditional create makes\n // immutable CAS and fixed-key manifest publication race-safe.\n IfNoneMatch: \"*\",\n }),\n );\n return \"uploaded\";\n } catch (error) {\n if (!isS3PreconditionFailed(error)) throw error;\n const raced = await inspectContentAddressedObject(client, bucket, key, size, expectedSha256);\n if (raced === \"matching\") return \"reused\";\n if (raced === \"conflict\") throwImmutableObjectConflict(uri);\n // The winning object was deleted between the conditional failure and\n // verification. Preserve the service error so the orchestrator may retry.\n throw error;\n } finally {\n // A failed conditional request may reject before consuming the stream.\n // Explicit teardown avoids retaining the source descriptor on a warm\n // Lambda planner.\n body.destroy();\n }\n}\n\nexport async function sha256File(path: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of createReadStream(path)) {\n hash.update(chunk as Buffer);\n }\n return hash.digest(\"hex\");\n}\n\nfunction assertSha256(value: string): void {\n if (!/^[a-f0-9]{64}$/.test(value)) {\n throw new Error(\n `[s3Transport] expected lowercase SHA-256 digest, got ${JSON.stringify(value)}`,\n );\n }\n}\n\ntype ContentAddressedObjectState = \"missing\" | \"matching\" | \"conflict\";\n\nasync function inspectContentAddressedObject(\n client: S3Client,\n bucket: string,\n key: string,\n expectedSize: number,\n expectedSha256: string,\n): Promise<ContentAddressedObjectState> {\n try {\n const existing = await client.send(\n new HeadObjectCommand({ Bucket: bucket, Key: key, ChecksumMode: \"ENABLED\" }),\n );\n return existing.ContentLength === expectedSize && existing.Metadata?.sha256 === expectedSha256\n ? \"matching\"\n : \"conflict\";\n } catch (error) {\n if (isS3NotFound(error)) return \"missing\";\n throw error;\n }\n}\n\nfunction throwImmutableObjectConflict(uri: string): never {\n const error = new Error(\n `[s3Transport] PLAN_ARTIFACT_DIGEST_MISMATCH: immutable object ${uri} already exists with different digest metadata or size`,\n );\n error.name = \"PLAN_ARTIFACT_DIGEST_MISMATCH\";\n throw error;\n}\n\nfunction isS3NotFound(error: unknown): boolean {\n if (!isRecord(error)) return false;\n const metadata = isRecord(error.$metadata) ? error.$metadata : undefined;\n return (\n error.name === \"NotFound\" || error.name === \"NoSuchKey\" || metadata?.httpStatusCode === 404\n );\n}\n\nfunction isS3PreconditionFailed(error: unknown): boolean {\n if (!isRecord(error)) return false;\n const metadata = isRecord(error.$metadata) ? error.$metadata : undefined;\n return error.name === \"PreconditionFailed\" || metadata?.httpStatusCode === 412;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Pack a directory into a `.tar.gz` at `destTarball`. Uses the `tar` npm\n * package (pure JS over `node:zlib`) rather than spawning a system tar\n * binary \u2014 the AWS Lambda Node 22 base image ships a minimal set of\n * userland tools and does NOT include `tar` in `/usr/bin`.\n */\nexport async function tarDirectory(sourceDir: string, destTarball: string): Promise<void> {\n if (!existsSync(sourceDir) || !statSync(sourceDir).isDirectory()) {\n throw new Error(`[s3Transport] tar source must be an existing directory: ${sourceDir}`);\n }\n mkdirSync(dirname(destTarball), { recursive: true });\n await tar.create({ gzip: true, file: destTarball, cwd: sourceDir }, [\".\"]);\n}\n\n/**\n * Extract a `.tar.gz` produced by {@link tarDirectory} into `destDir`.\n * The directory is created (or cleared) before extraction so a retried\n * invocation doesn't observe stale files from a prior run on the same\n * warm Lambda container.\n */\nexport async function untarDirectory(tarballPath: string, destDir: string): Promise<void> {\n if (!existsSync(tarballPath)) {\n throw new Error(`[s3Transport] tarball missing: ${tarballPath}`);\n }\n // Wipe target so the warm container's prior planDir doesn't bleed into\n // the new invocation. Lambda re-uses /tmp across invocations on the same\n // container.\n if (existsSync(destDir)) {\n rmSync(destDir, { recursive: true, force: true });\n }\n mkdirSync(destDir, { recursive: true });\n await tar.extract({ file: tarballPath, cwd: destDir });\n}\n", "import { createHash } from \"node:crypto\";\nimport { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { S3Client } from \"@aws-sdk/client-s3\";\nimport {\n PlanV2IntegrityError,\n type PlanV2ArtifactPublisher,\n type PlanV2PublishBlob,\n} from \"@hyperframes/producer/distributed\";\nimport { parseS3Uri, uploadContentAddressedFileToS3 } from \"./s3Transport.js\";\n\nexport interface S3PlanV2ArtifactPublisherOptions {\n readonly s3: S3Client;\n /** Validated render output prefix from which all v2 object keys are derived. */\n readonly planOutputS3Prefix: string;\n /** Planner-local scratch parent for the small manifest upload file. */\n readonly temporaryRoot?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction assertSha256(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !/^[a-f0-9]{64}$/.test(value)) {\n throw new PlanV2IntegrityError(`${label} must be a lowercase SHA-256 digest`);\n }\n return value;\n}\n\nfunction manifestDigests(manifestBytes: string): ReadonlySet<string> {\n let value: unknown;\n try {\n value = JSON.parse(manifestBytes);\n } catch {\n throw new PlanV2IntegrityError(\"S3 publisher received invalid manifest JSON\");\n }\n if (!isRecord(value) || !Array.isArray(value.artifacts)) {\n throw new PlanV2IntegrityError(\"S3 publisher manifest requires an artifacts array\");\n }\n return new Set(\n value.artifacts.map((artifact, index) => {\n if (!isRecord(artifact)) {\n throw new PlanV2IntegrityError(`S3 publisher artifacts[${index}] must be an object`);\n }\n return assertSha256(artifact.sha256, `S3 publisher artifacts[${index}].sha256`);\n }),\n );\n}\n\nfunction trimTrailingSlash(value: string): string {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;\n return value.slice(0, end);\n}\n\n/**\n * Manifest-last S3 implementation of the producer's plan-v2 publication seam.\n *\n * Blobs stream from the planner's private frozen directory directly to S3.\n * Successfully uploaded or safely reused digests are tracked so a manifest\n * cannot become visible before all of its references are durable.\n */\nexport class S3PlanV2ArtifactPublisher implements PlanV2ArtifactPublisher {\n readonly artifactPrefix: string;\n readonly manifestUri: string;\n readonly #s3: S3Client;\n readonly #temporaryRoot: string;\n readonly #publishedDigests = new Set<string>();\n #state: \"open\" | \"committed\" | \"aborted\" = \"open\";\n\n constructor(options: Readonly<S3PlanV2ArtifactPublisherOptions>) {\n const outputPrefix = `${trimTrailingSlash(options.planOutputS3Prefix)}/v2`;\n parseS3Uri(outputPrefix);\n this.#s3 = options.s3;\n this.artifactPrefix = `${outputPrefix}/artifacts/sha256`;\n this.manifestUri = `${outputPrefix}/manifest.json`;\n this.#temporaryRoot = options.temporaryRoot ?? tmpdir();\n mkdirSync(this.#temporaryRoot, { recursive: true });\n }\n\n async putBlob(blob: Readonly<PlanV2PublishBlob>): Promise<void> {\n this.#assertOpen(\"publish a blob\");\n const digest = assertSha256(blob.sha256, \"S3 published blob sha256\");\n const sourceSize = statSync(blob.sourcePath).size;\n if (sourceSize !== blob.sizeBytes) {\n throw new PlanV2IntegrityError(\n `S3 published blob size changed for ${digest}: expected ${blob.sizeBytes}, got ${sourceSize}`,\n );\n }\n const uri = `${this.artifactPrefix}/${digest.slice(0, 2)}/${digest}`;\n await uploadContentAddressedFileToS3(this.#s3, blob.sourcePath, uri, digest);\n this.#publishedDigests.add(digest);\n }\n\n async commitManifest(manifestBytes: string): Promise<void> {\n this.#assertOpen(\"commit a manifest\");\n for (const digest of manifestDigests(manifestBytes)) {\n if (!this.#publishedDigests.has(digest)) {\n throw new PlanV2IntegrityError(\n `cannot commit S3 manifest before referenced blob is durable: ${digest}`,\n );\n }\n }\n\n const manifestDigest = createHash(\"sha256\").update(manifestBytes, \"utf8\").digest(\"hex\");\n const stagingDir = mkdtempSync(join(this.#temporaryRoot, \"hf-plan-v2-manifest-\"));\n const manifestPath = join(stagingDir, \"manifest.json\");\n try {\n writeFileSync(manifestPath, manifestBytes, \"utf8\");\n await uploadContentAddressedFileToS3(\n this.#s3,\n manifestPath,\n this.manifestUri,\n manifestDigest,\n \"application/json\",\n );\n this.#state = \"committed\";\n } finally {\n rmSync(stagingDir, { recursive: true, force: true });\n }\n }\n\n async abort(): Promise<void> {\n if (this.#state === \"open\") this.#state = \"aborted\";\n // Remote CAS blobs are immutable and may already be reused by a retry.\n // Without a committed manifest they are unreachable and expire under the\n // render bucket's intermediate-object lifecycle policy.\n }\n\n #assertOpen(operation: string): void {\n if (this.#state !== \"open\") {\n throw new PlanV2IntegrityError(`cannot ${operation} after publisher is ${this.#state}`);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAaA,SAAS,cAAAA,aAAY,aAAAC,YAAW,eAAAC,cAAa,cAAc,UAAAC,SAAQ,YAAAC,iBAAgB;AACnF,SAAS,UAAAC,eAAc;AACvB,SAAS,UAAU,QAAAC,aAAY;AAC/B,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAKA;AAAA,EACA;AAAA,OACK;;;ACFP,SAAS,kBAAkB;AAUpB,IAAM,+BAAN,cAA2C,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAKpC,OAAO;AAAA,EAChB;AAAA,EACA;AAAA,EACT,YAAY,QAAsB,cAA6B,MAAc;AAC3E,UAAM,gDAAgD,MAAM,MAAM,IAAI,EAAE;AACxE,SAAK,SAAS;AACd,SAAK,eAAe;AAAA,EACtB;AACF;AAEA,IAAM,uBACJ;AAYK,SAAS,sBAAoC;AAClD,QAAM,MAAM,QAAQ,IAAI,kCAAkC,YAAY;AACtE,MAAI,QAAQ,2BAA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cAAe;AAEpB,aAAW,OAAO,eAAe,KAAK,GAAG;AACvC,UAAM,EAAE,OAAO,IAAI,WAAW,GAAG;AACjC,QAAI,WAAW,eAAe;AAC5B,YAAM,MAAM,IAAI;AAAA,QACd,qCAAqC,KAAK,UAAU,GAAG,CAAC,oBAAoB,MAAM,eAAe,aAAa;AAAA,MAChH;AACA,UAAI,OAAO;AACX,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAEA,SAAS,IAAI,GAAmB;AAC9B,SAAO,EAAE,SAAS,EAAE,SAAS,GAAG,GAAG;AACrC;AAEA,SAASI,mBAAkB,QAAwB;AACjD,SAAO,OAAO,SAAS,GAAG,IAAI,OAAO,MAAM,GAAG,EAAE,IAAI;AACtD;AAEA,SAAS,WAAW,KAAmB;AACrC,MAAI;AAGF,IAAAI,QAAO,KAAK,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,EAC9C,QAAQ;AAAA,EAER;AACF;AAYA,SAAS,eAAe,SAAiB,UAAwB;AAC/D,QAAM,eAAeR,MAAK,SAAS,WAAW;AAC9C,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,aAAa,cAAc,OAAO,CAAC;AAAA,EACzD,SAAS,KAAK;AACZ,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,UAAM,QAAQ,IAAI,MAAM,sCAAsC,YAAY,KAAK,GAAG,EAAE;AACpF,UAAM,OAAO;AACb,UAAM;AAAA,EACR;AACA,QAAM,SAAS,OAAO;AACtB,MAAI,OAAO,WAAW,YAAY,WAAW,UAAU;AACrD,UAAM,QAAQ,IAAI;AAAA,MAChB,sCAAsC,QAAQ,qCAAqC,OAAO,MAAM,CAAC;AAAA,IACnG;AACA,UAAM,OAAO;AACb,UAAM;AAAA,EACR;AACF;",
|
|
6
6
|
"names": ["existsSync", "mkdirSync", "mkdtempSync", "rmSync", "statSync", "tmpdir", "join", "existsSync", "existsSync", "createHash", "mkdirSync", "rmSync", "statSync", "isRecord", "assertSha256", "mkdirSync", "statSync", "createHash", "rmSync", "join", "existsSync", "mkdtempSync", "tmpdir", "trimTrailingSlash", "statSync", "uri", "mkdirSync", "rmSync"]
|
|
7
7
|
}
|
package/dist/index.js
CHANGED
|
@@ -393,6 +393,7 @@ function getS3Client() {
|
|
|
393
393
|
}
|
|
394
394
|
async function handler(event, deps) {
|
|
395
395
|
const unwrapped = unwrapEvent(event);
|
|
396
|
+
validatePlanProtocolShape(unwrapped);
|
|
396
397
|
validateEventS3Uris(unwrapped);
|
|
397
398
|
primeRuntimeEnv();
|
|
398
399
|
logEvent({ event: "handler_start", action: unwrapped.Action, input: summarizeEvent(unwrapped) });
|
|
@@ -459,6 +460,35 @@ function unwrapEvent(event) {
|
|
|
459
460
|
function isLambdaAction(value) {
|
|
460
461
|
return value === "plan" || value === "renderChunk" || value === "assemble";
|
|
461
462
|
}
|
|
463
|
+
function validatePlanProtocolShape(event) {
|
|
464
|
+
const raw = event;
|
|
465
|
+
const protocol = raw.PlanProtocol;
|
|
466
|
+
if (protocol !== void 0 && protocol !== "v1" && protocol !== "v2") {
|
|
467
|
+
const error = new Error(
|
|
468
|
+
`[handler] unsupported PlanProtocol ${JSON.stringify(protocol)}; expected "v1", "v2", or absent`
|
|
469
|
+
);
|
|
470
|
+
error.name = "PLAN_PROTOCOL_UNSUPPORTED";
|
|
471
|
+
throw error;
|
|
472
|
+
}
|
|
473
|
+
if (event.Action === "plan") return;
|
|
474
|
+
const effectiveProtocol = protocol ?? "v2";
|
|
475
|
+
const hasV1Locator = typeof raw.PlanS3Uri === "string";
|
|
476
|
+
const hasV2Manifest = typeof raw.PlanV2ManifestS3Uri === "string";
|
|
477
|
+
const hasV2Prefix = typeof raw.PlanV2ArtifactS3Prefix === "string";
|
|
478
|
+
const valid = effectiveProtocol === "v2" ? !hasV1Locator && hasV2Manifest && hasV2Prefix : hasV1Locator && !hasV2Manifest && !hasV2Prefix;
|
|
479
|
+
if (!valid) {
|
|
480
|
+
const error = new Error(
|
|
481
|
+
`[handler] ${effectiveProtocol} ${event.Action} event has mixed or missing plan locators`
|
|
482
|
+
);
|
|
483
|
+
error.name = "PLAN_PROTOCOL_UNSUPPORTED";
|
|
484
|
+
throw error;
|
|
485
|
+
}
|
|
486
|
+
if (effectiveProtocol === "v2" && event.Action === "assemble" && event.AudioS3Uri !== null) {
|
|
487
|
+
const error = new Error("[handler] v2 assemble audio must be materialized from the manifest");
|
|
488
|
+
error.name = "PLAN_PROTOCOL_UNSUPPORTED";
|
|
489
|
+
throw error;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
462
492
|
function logEvent(payload) {
|
|
463
493
|
console.log(JSON.stringify(payload));
|
|
464
494
|
}
|
|
@@ -468,21 +498,21 @@ function summarizeEvent(event) {
|
|
|
468
498
|
return {
|
|
469
499
|
projectS3Uri: event.ProjectS3Uri,
|
|
470
500
|
planOutputS3Prefix: event.PlanOutputS3Prefix,
|
|
471
|
-
planProtocol: event.PlanProtocol ?? "
|
|
501
|
+
planProtocol: event.PlanProtocol ?? "v2",
|
|
472
502
|
format: event.Config.format,
|
|
473
503
|
fps: event.Config.fps
|
|
474
504
|
};
|
|
475
505
|
case "renderChunk":
|
|
476
506
|
return {
|
|
477
|
-
planProtocol: event.PlanProtocol ?? "
|
|
478
|
-
...event.PlanProtocol
|
|
507
|
+
planProtocol: event.PlanProtocol ?? "v2",
|
|
508
|
+
...event.PlanProtocol !== "v1" ? { planV2ManifestS3Uri: event.PlanV2ManifestS3Uri } : { planS3Uri: event.PlanS3Uri },
|
|
479
509
|
chunkIndex: event.ChunkIndex,
|
|
480
510
|
format: event.Format
|
|
481
511
|
};
|
|
482
512
|
case "assemble":
|
|
483
513
|
return {
|
|
484
|
-
planProtocol: event.PlanProtocol ?? "
|
|
485
|
-
...event.PlanProtocol
|
|
514
|
+
planProtocol: event.PlanProtocol ?? "v2",
|
|
515
|
+
...event.PlanProtocol !== "v1" ? { planV2ManifestS3Uri: event.PlanV2ManifestS3Uri } : { planS3Uri: event.PlanS3Uri },
|
|
486
516
|
chunkCount: event.ChunkS3Uris.length,
|
|
487
517
|
hasAudio: event.AudioS3Uri !== null,
|
|
488
518
|
outputS3Uri: event.OutputS3Uri,
|
|
@@ -501,7 +531,7 @@ function primeRuntimeEnv() {
|
|
|
501
531
|
}
|
|
502
532
|
}
|
|
503
533
|
async function handlePlan(event, deps) {
|
|
504
|
-
if (event.PlanProtocol
|
|
534
|
+
if (event.PlanProtocol !== "v1") {
|
|
505
535
|
return handlePlanV2(event, deps);
|
|
506
536
|
}
|
|
507
537
|
const started = Date.now();
|
|
@@ -596,7 +626,7 @@ async function handlePlanV2(event, deps) {
|
|
|
596
626
|
}
|
|
597
627
|
}
|
|
598
628
|
async function handleRenderChunk(event, deps) {
|
|
599
|
-
if (event.PlanProtocol
|
|
629
|
+
if (event.PlanProtocol !== "v1") {
|
|
600
630
|
return handleRenderChunkV2(event, deps);
|
|
601
631
|
}
|
|
602
632
|
const started = Date.now();
|
|
@@ -691,7 +721,7 @@ async function uploadChunkOutput(s3, result, prefix, chunkIndex) {
|
|
|
691
721
|
return uri;
|
|
692
722
|
}
|
|
693
723
|
async function handleAssemble(event, deps) {
|
|
694
|
-
if (event.PlanProtocol
|
|
724
|
+
if (event.PlanProtocol !== "v1") {
|
|
695
725
|
return handleAssembleV2(event, deps);
|
|
696
726
|
}
|
|
697
727
|
const started = Date.now();
|
|
@@ -846,10 +876,10 @@ function getEventS3Uris(event) {
|
|
|
846
876
|
case "plan":
|
|
847
877
|
return [event.ProjectS3Uri, event.PlanOutputS3Prefix];
|
|
848
878
|
case "renderChunk":
|
|
849
|
-
return event.PlanProtocol
|
|
879
|
+
return event.PlanProtocol !== "v1" ? [event.PlanV2ManifestS3Uri, event.PlanV2ArtifactS3Prefix, event.ChunkOutputS3Prefix] : [event.PlanS3Uri, event.ChunkOutputS3Prefix];
|
|
850
880
|
case "assemble":
|
|
851
881
|
return [
|
|
852
|
-
...event.PlanProtocol
|
|
882
|
+
...event.PlanProtocol !== "v1" ? [event.PlanV2ManifestS3Uri, event.PlanV2ArtifactS3Prefix] : [event.PlanS3Uri],
|
|
853
883
|
...event.ChunkS3Uris,
|
|
854
884
|
event.OutputS3Uri,
|
|
855
885
|
event.AudioS3Uri
|
|
@@ -1031,7 +1061,7 @@ async function renderToLambda(opts) {
|
|
|
1031
1061
|
PlanOutputS3Prefix: planOutputS3Prefix,
|
|
1032
1062
|
OutputS3Uri: outputS3Uri,
|
|
1033
1063
|
Config: opts.config,
|
|
1034
|
-
PlanProtocol: opts.planProtocol ?? "
|
|
1064
|
+
PlanProtocol: opts.planProtocol ?? "v2"
|
|
1035
1065
|
};
|
|
1036
1066
|
validateStepFunctionsInputSize(input);
|
|
1037
1067
|
const sfn = opts.sfn ?? new SFNClient({ region: opts.region });
|