@lovable.dev/sdk 1.4.0 → 1.6.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflows.js","names":[],"sources":["../../workflow-sdk/src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport interface JournalEntry {\n result?: unknown;\n resultType?: \"undefined\" | \"ref\";\n /** Payload pointer when resultType is \"ref\"; see docs/workflows/payload-offload.md. */\n ref?: PayloadRef;\n /** Marks an auto-offloaded ref that replays as its parsed value instead of a WorkflowFile. */\n transparent?: boolean;\n /** Ephemeral read grant the engine hydrates per invocation; never persisted. */\n grant?: PayloadGrant;\n}\n\nexport type Journal = Record<string, JournalEntry>;\n\nexport type PayloadAeadScheme = \"CHUNKED_AES_256_GCM_V1\";\n\nexport interface PayloadRef {\n bucket: string;\n key: string;\n /** Lowercase hex SHA-256 of the plaintext bytes. */\n sha256: string;\n sizeBytes: number;\n contentType: string;\n /** Base64 AES-256 DEK sealed by the workflows payload KEK. */\n wrappedDek: string;\n kekId: string;\n scheme: PayloadAeadScheme;\n}\n\nexport interface PayloadGrant {\n getUrl: string;\n /** Base64 raw AES-256 DEK for this object. */\n dek: string;\n}\n\nexport interface PayloadOffload {\n /** Absolute URL of the runtime payload endpoint (POST /runtime/v1/payloads). */\n endpoint: string;\n /** Step results whose JSON serialization is <= threshold bytes stay inline. */\n threshold: number;\n /** Per-object plaintext byte cap. */\n maxBytes: number;\n}\n\n/** Lazy handle over an offloaded payload; reads stream-decrypt on access. */\nexport interface WorkflowFile {\n readonly sha256: string;\n readonly sizeBytes: number;\n readonly contentType: string;\n stream(): ReadableStream<Uint8Array>;\n arrayBuffer(): Promise<ArrayBuffer>;\n text(): Promise<string>;\n json(): Promise<unknown>;\n}\n\nexport interface WorkflowFilesApi {\n /** Offloads `data` and returns a handle; stream inputs are buffered in memory (tranche 1). */\n create(\n data: ReadableStream<Uint8Array> | ArrayBuffer | Uint8Array | string,\n options: { contentType: string },\n ): Promise<WorkflowFile>;\n}\n\nexport interface WorkerRequest<Input = unknown> {\n input: Input;\n journal: Journal;\n /** Present when the engine enables large-payload offload for this run. */\n payloadOffload?: PayloadOffload;\n}\n\nexport interface WorkerTaskRequest<Input = unknown> {\n operation: \"task\";\n task: string;\n input: Input;\n runName: string;\n stepId: string;\n attempt: number;\n workflowTenant: string;\n workflowApiUrl: string;\n}\n\nexport type ExecutionEnvironment = \"cloudflare\";\n\nexport interface StepDispatch {\n id: string;\n task: string;\n environment: ExecutionEnvironment;\n input: unknown;\n maxConcurrency?: number;\n /** Durable-promise park request (ctx.promise); the engine parks the run instead of executing. */\n promise?: { name: string; timeoutSeconds?: number };\n}\n\n/** `completed` is this invocation's unpersisted delta, including on workflow failure. */\nexport type WorkerResponse<Output = unknown> =\n | { status: \"done\"; output: Output; outputType?: never; completed: Journal }\n | { status: \"done\"; output: null; outputType: \"undefined\"; completed: Journal }\n | { status: \"failed\"; error: string; failedStep?: string; completed: Journal }\n | { status: \"dispatch\"; steps: StepDispatch[]; completed: Journal };\n\ninterface TaskDefinitionBase {\n readonly name: string;\n readonly environment: ExecutionEnvironment;\n readonly maxConcurrency?: number;\n}\n\nexport type WorkflowLogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface WorkflowLogEntry {\n readonly level: WorkflowLogLevel;\n readonly message: string;\n readonly fields?: Record<string, unknown>;\n}\n\nexport type WorkflowLogEmitter = (entry: WorkflowLogEntry) => void;\n\n/**\n * Fire-and-forget structured logging. Entries are scrubbed for\n * credential-shaped values, capped in size and count, and not journaled;\n * workflow-body entries are suppressed while journaled effects replay, so\n * each entry is emitted once across engine round-trips.\n */\nexport interface WorkflowLogger {\n debug(message: string, fields?: Record<string, unknown>): void;\n info(message: string, fields?: Record<string, unknown>): void;\n warn(message: string, fields?: Record<string, unknown>): void;\n error(message: string, fields?: Record<string, unknown>): void;\n}\n\nexport interface TaskContext {\n readonly runName: string;\n readonly stepId: string;\n readonly attempt: number;\n readonly workflows: WorkflowsApi;\n readonly log: WorkflowLogger;\n}\n\nexport interface WorkflowRunRequest {\n readonly workspaceId: string;\n readonly projectId: string;\n readonly workflowId: string;\n readonly inputs?: unknown;\n readonly invocationKey?: string;\n}\n\nexport interface WorkflowRun {\n readonly id: string;\n readonly state: string;\n readonly error?: string;\n readonly inputs?: unknown;\n readonly outputs?: unknown;\n readonly codeAttempt?: number;\n readonly createTime?: string;\n readonly startTime?: string;\n readonly endTime?: string;\n}\n\nexport interface WorkflowsApi {\n run(request: WorkflowRunRequest): Promise<WorkflowRun>;\n}\n\nexport interface CloudflareTaskDefinition<Input = unknown, Output = unknown> extends TaskDefinitionBase {\n readonly environment: \"cloudflare\";\n readonly run: (input: Input, context: TaskContext) => Promise<Output> | Output;\n}\n\nexport type TaskDefinition<Input = unknown, Output = unknown> = CloudflareTaskDefinition<Input, Output>;\n\nexport interface CloudflareTaskConfig<Input, Output> {\n name: string;\n environment: \"cloudflare\";\n run: (input: Input, context: TaskContext) => Promise<Output> | Output;\n maxConcurrency?: number;\n}\n\nexport interface StepRunOptions {\n id?: string;\n}\n\nexport function defineTask<Input, Output>(\n config: CloudflareTaskConfig<Input, Output>,\n): CloudflareTaskDefinition<Input, Output> {\n assertEntryName(config.name);\n if (config.environment !== \"cloudflare\") {\n throw new Error(\"workflow-sdk: only Cloudflare tasks are supported\");\n }\n if (\n config.maxConcurrency !== undefined &&\n (!Number.isInteger(config.maxConcurrency) || config.maxConcurrency < 1 || config.maxConcurrency > 256)\n ) {\n throw new Error(\"workflow-sdk: maxConcurrency must be an integer between 1 and 256\");\n }\n return config;\n}\n\nexport interface StepApi {\n /** Replays a stable, unique name from the journal; effects must tolerate deliberate retries. */\n run<T>(name: string, effect: () => Promise<T> | T): Promise<T>;\n run<Input, Output>(task: TaskDefinition<Input, Output>, input: Input, options?: StepRunOptions): Promise<Output>;\n}\n\nexport interface WorkflowPromiseOptions {\n /** Auto-reject deadline in seconds (1..86400); unset means bounded only by the run deadline. */\n timeoutSeconds?: number;\n}\n\n/** A durable promise was rejected (explicitly or by its timeout sweep). Catchable to branch on rejection. */\nexport class PromiseRejectedError extends Error {\n constructor(\n readonly promiseName: string,\n readonly reason: string,\n ) {\n super(`workflow-sdk: promise \"${promiseName}\" rejected: ${reason}`);\n }\n}\n\nexport interface WorkflowContext<Input = unknown> {\n readonly input: Input;\n readonly step: StepApi;\n readonly files: WorkflowFilesApi;\n readonly log: WorkflowLogger;\n /** Journaled wall clock keyed by a stable name. */\n now(name: string): Promise<number>;\n /** Journaled random UUID keyed by a stable name. */\n uuid(name: string): Promise<string>;\n /** Parks until external resolution; replay returns the value or throws PromiseRejectedError. */\n promise<T = unknown>(name: string, options?: WorkflowPromiseOptions): Promise<T>;\n}\n\nexport interface WorkflowDefinition<Input = unknown, Output = unknown> {\n readonly name: string;\n readonly handler: (ctx: WorkflowContext<Input>) => Promise<Output>;\n}\n\nexport function defineWorkflow<Input = unknown, Output = unknown>(\n name: string,\n handler: (ctx: WorkflowContext<Input>) => Promise<Output>,\n): WorkflowDefinition<Input, Output> {\n return { name, handler };\n}\n\nfunction hasOwn<Key extends PropertyKey>(value: object, key: Key): value is object & Record<Key, unknown> {\n return Object.prototype.hasOwnProperty.call(value, key);\n}\n\nfunction taskDispatchPromise<T>(start: () => void): Promise<T> {\n const pending = new Promise<T>(() => undefined);\n let started = false;\n return interceptPromiseMethods(pending, (_method, args, invoke) => {\n if (!started) {\n started = true;\n start();\n }\n return invoke(args);\n });\n}\n\ntype PromiseMethod = \"then\" | \"catch\" | \"finally\";\n\nfunction interceptPromiseMethods<T>(\n promise: Promise<T>,\n intercept: (\n method: PromiseMethod,\n args: unknown[],\n invoke: (args: unknown[]) => Promise<unknown>,\n ) => Promise<unknown>,\n): Promise<T> {\n return new Proxy(promise, {\n get(target, property) {\n if (property !== \"then\" && property !== \"catch\" && property !== \"finally\") {\n return Reflect.get(target, property, target);\n }\n const method = Reflect.get(target, property, target) as (...args: unknown[]) => Promise<unknown>;\n return (...args: unknown[]): Promise<unknown> =>\n intercept(property, args, (interceptedArgs) => Reflect.apply(method, target, interceptedArgs));\n },\n });\n}\n\ninterface InlinePromiseState {\n status: \"pending\" | \"fulfilled\" | \"rejected\";\n reason?: unknown;\n}\n\ninterface InlinePromiseRoot {\n name: string;\n failureObserved: boolean;\n state: InlinePromiseState;\n}\n\ninterface InlinePromiseLineage {\n parent?: InlinePromiseLineage;\n durableTaskDispatched: boolean;\n}\n\ninterface InlinePromiseBranch {\n root: InlinePromiseRoot;\n lineage: InlinePromiseLineage;\n inheritsRootRejection: boolean;\n state: InlinePromiseState;\n}\n\nfunction hasDurableTaskDispatch(lineage: InlinePromiseLineage): boolean {\n let current: InlinePromiseLineage | undefined = lineage;\n while (current !== undefined) {\n if (current.durableTaskDispatched) return true;\n current = current.parent;\n }\n return false;\n}\n\nclass Execution<Input> {\n readonly completed: Journal = Object.create(null) as Journal;\n readonly dispatches: StepDispatch[] = [];\n private readonly seenStepNames = new Set<string>();\n private readonly seenPromiseNames = new Set<string>();\n private readonly seenAutomaticEntries = new Set<string>();\n private readonly startedSteps: Promise<unknown>[] = [];\n private readonly unconsumedInlineSteps = new Map<Promise<unknown>, InlinePromiseBranch>();\n private readonly unconsumedTasks = new Map<string, StepFailure>();\n private readonly inlineStep = new AsyncLocalStorage<string>();\n private readonly inlinePromiseLineage = new AsyncLocalStorage<InlinePromiseLineage>();\n private readonly dispatchReady: Promise<void>;\n private resolveDispatch!: () => void;\n private readonly logger: WorkflowLogger;\n // Body logs are suppressed until every journaled effect has been consumed:\n // code that runs before that point already ran (and logged) previously.\n private journalRemaining: number;\n\n constructor(\n readonly input: Input,\n private readonly journal: Journal,\n private readonly offload: PayloadOffload | undefined,\n emit: WorkflowLogEmitter,\n ) {\n this.dispatchReady = new Promise((resolve) => {\n this.resolveDispatch = resolve;\n });\n this.journalRemaining = Object.keys(journal).length;\n this.logger = createWorkflowLogger(emit, () => this.journalRemaining > 0);\n }\n\n private consumeJournalEntry(): void {\n if (this.journalRemaining > 0) this.journalRemaining -= 1;\n }\n\n private async readOrRecord<T>(key: string, createValue: () => Promise<T> | T): Promise<T> {\n if (hasOwn(this.journal, key)) {\n this.consumeJournalEntry();\n return readJournalResult(this.journal[key]) as T;\n }\n const createdValue = await createValue();\n if (createdValue instanceof PayloadFile) {\n this.completed[key] = { resultType: \"ref\", ref: structuredClone(createdValue.ref) };\n return createdValue as T;\n }\n if (createdValue === undefined) {\n this.completed[key] = { result: null, resultType: \"undefined\" };\n return undefined as T;\n }\n const encoded = encodeJSONValue(createdValue, \"step results\");\n if (this.offload !== undefined) {\n const serialized = utf8PayloadBytes(encoded);\n if (serialized.byteLength > this.offload.threshold) {\n const ref = await uploadPayload(this.offload, serialized, \"application/json\");\n this.completed[key] = { resultType: \"ref\", ref, transparent: true };\n return JSON.parse(encoded) as T;\n }\n }\n this.completed[key] = { result: JSON.parse(encoded) as unknown };\n return JSON.parse(encoded) as T;\n }\n\n private automaticEntry<T>(kind: \"now\" | \"uuid\", name: string, createValue: () => T): Promise<T> {\n assertEntryName(name);\n const key = `@${kind}/${name}`;\n if (this.seenAutomaticEntries.has(key)) {\n throw new Error(`workflow-sdk: duplicate ${kind} name \"${name}\"`);\n }\n this.seenAutomaticEntries.add(key);\n const started = this.readOrRecord(key, createValue);\n this.startedSteps.push(started);\n return started;\n }\n\n private runStep<T>(\n nameOrTask: string | TaskDefinition<unknown, T>,\n effectOrInput: unknown,\n options?: StepRunOptions,\n ): Promise<T> {\n if (typeof nameOrTask === \"string\") {\n const name = nameOrTask;\n if (typeof effectOrInput !== \"function\") {\n throw new Error(\"workflow-sdk: inline step effect must be a function\");\n }\n assertEntryName(name);\n if (this.seenStepNames.has(name)) {\n throw new Error(`workflow-sdk: duplicate step name \"${name}\"`);\n }\n this.seenStepNames.add(name);\n const started = this.inlineStep\n .run(name, () => this.readOrRecord(name, effectOrInput as () => Promise<T> | T))\n .catch((error: unknown) => {\n throw error instanceof StepFailure ? error : new StepFailure(name, error);\n });\n this.startedSteps.push(started);\n return this.trackInlineStepPromise(name, started);\n }\n\n const inlineStep = this.inlineStep.getStore();\n if (inlineStep !== undefined) {\n throw new Error(`workflow-sdk: engine-dispatched tasks cannot run inside inline step \"${inlineStep}\"`);\n }\n const id = options?.id ?? nameOrTask.name;\n assertEntryName(id);\n if (this.seenStepNames.has(id)) {\n throw new Error(`workflow-sdk: duplicate step name \"${id}\"`);\n }\n this.seenStepNames.add(id);\n if (hasOwn(this.journal, id)) {\n this.consumeJournalEntry();\n return Promise.resolve()\n .then(() => readJournalResult(this.journal[id]) as T)\n .catch((error: unknown) => {\n throw error instanceof StepFailure ? error : new StepFailure(id, error);\n });\n }\n let input: unknown;\n try {\n input = cloneJSONValue(effectOrInput, \"step input\");\n } catch (error) {\n throw new StepFailure(id, error);\n }\n const unconsumed = new StepFailure(id, new Error(`workflow-sdk: task step \"${id}\" must be awaited or returned`));\n this.unconsumedTasks.set(id, unconsumed);\n const lineage = this.inlinePromiseLineage.getStore();\n return taskDispatchPromise<T>(() => {\n if (lineage !== undefined) {\n lineage.durableTaskDispatched = true;\n }\n this.unconsumedTasks.delete(id);\n this.dispatches.push({\n id,\n task: nameOrTask.name,\n environment: nameOrTask.environment,\n input,\n ...(nameOrTask.maxConcurrency === undefined ? {} : { maxConcurrency: nameOrTask.maxConcurrency }),\n });\n this.resolveDispatch();\n });\n }\n\n readonly step: StepApi = {\n run: ((nameOrTask: string | TaskDefinition<unknown, unknown>, effectOrInput: unknown, options?: StepRunOptions) =>\n this.runStep(nameOrTask, effectOrInput, options)) as StepApi[\"run\"],\n };\n\n readonly files: WorkflowFilesApi = {\n create: (data, options) => {\n if (this.offload === undefined) {\n return Promise.reject(new Error(\"workflow-sdk: payload offload is not enabled for this run\"));\n }\n return createWorkflowFile(this.offload, data, options);\n },\n };\n\n now = (name: string): Promise<number> => this.automaticEntry(\"now\", name, () => Date.now());\n uuid = (name: string): Promise<string> => this.automaticEntry(\"uuid\", name, () => crypto.randomUUID());\n\n promise = <T = unknown>(name: string, options?: WorkflowPromiseOptions): Promise<T> => {\n assertEntryName(name);\n const key = `@promise/${name}`;\n if (this.seenPromiseNames.has(name)) {\n throw new Error(`workflow-sdk: duplicate promise name \"${name}\"`);\n }\n this.seenPromiseNames.add(name);\n const timeoutSeconds = options?.timeoutSeconds;\n if (\n timeoutSeconds !== undefined &&\n (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 86400)\n ) {\n throw new Error(\"workflow-sdk: promise timeoutSeconds must be an integer between 1 and 86400\");\n }\n if (hasOwn(this.journal, key)) {\n this.consumeJournalEntry();\n const entry = readJournalResult(this.journal[key]) as { status?: string; value?: unknown; reason?: string };\n if (entry.status === \"resolved\") {\n return Promise.resolve(structuredClone(entry.value) as T);\n }\n return Promise.reject(new PromiseRejectedError(name, entry.reason ?? \"promise rejected\"));\n }\n this.unconsumedTasks.set(\n key,\n new StepFailure(key, new Error(`workflow-sdk: promise \"${name}\" must be awaited or returned`)),\n );\n return taskDispatchPromise<T>(() => {\n this.unconsumedTasks.delete(key);\n this.dispatches.push({\n id: key,\n task: \"@promise\",\n environment: \"cloudflare\",\n input: null,\n promise: { name, ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }) },\n });\n this.resolveDispatch();\n });\n };\n\n async settleStartedSteps(): Promise<void> {\n await Promise.allSettled(this.startedSteps);\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n\n unconsumedInlineFailure(): StepFailure | undefined {\n for (const branch of this.unconsumedInlineSteps.values()) {\n if (branch.state.status === \"rejected\") {\n const inheritedHandledRejection =\n branch.inheritsRootRejection &&\n branch.root.failureObserved &&\n branch.root.state.status === \"rejected\" &&\n branch.state.reason === branch.root.state.reason;\n if (inheritedHandledRejection) continue;\n return branch.state.reason instanceof StepFailure\n ? branch.state.reason\n : new StepFailure(branch.root.name, branch.state.reason);\n }\n if (branch.state.status === \"fulfilled\" || hasDurableTaskDispatch(branch.lineage)) continue;\n if (branch.root.state.status === \"rejected\" && !branch.root.failureObserved) {\n return branch.root.state.reason instanceof StepFailure\n ? branch.root.state.reason\n : new StepFailure(branch.root.name, branch.root.state.reason);\n }\n return new StepFailure(\n branch.root.name,\n new Error(`workflow-sdk: inline step branch \"${branch.root.name}\" must be awaited or returned`),\n );\n }\n return undefined;\n }\n\n unconsumedTaskFailure(): StepFailure | undefined {\n return this.unconsumedTasks.values().next().value;\n }\n\n waitForDispatch(): Promise<void> {\n return this.dispatchReady;\n }\n\n hasDispatches(): boolean {\n return this.dispatches.length > 0;\n }\n\n context(): WorkflowContext<Input> {\n return {\n input: this.input,\n step: this.step,\n files: this.files,\n log: this.logger,\n now: this.now,\n uuid: this.uuid,\n promise: this.promise,\n };\n }\n\n private trackInlineStepPromise<T>(\n name: string,\n promise: Promise<T>,\n root?: InlinePromiseRoot,\n inheritsRootRejection = true,\n lineage?: InlinePromiseLineage,\n ): Promise<T> {\n const state: InlinePromiseState = { status: \"pending\" };\n const inlineRoot = root ?? { name, failureObserved: false, state };\n const inlineLineage = lineage ?? { durableTaskDispatched: false };\n const branch = { root: inlineRoot, lineage: inlineLineage, inheritsRootRejection, state };\n this.unconsumedInlineSteps.set(promise, branch);\n void promise.then(\n () => {\n state.status = \"fulfilled\";\n },\n (reason: unknown) => {\n state.status = \"rejected\";\n state.reason = reason;\n },\n );\n let consumed = false;\n return interceptPromiseMethods(promise, (method, args, invoke) => {\n if (!consumed) {\n consumed = true;\n this.unconsumedInlineSteps.delete(promise);\n }\n const handlesRejection =\n (method === \"then\" && typeof args[1] === \"function\") || (method === \"catch\" && typeof args[0] === \"function\");\n if (branch.inheritsRootRejection && handlesRejection) {\n inlineRoot.failureObserved = true;\n }\n const childLineage: InlinePromiseLineage = { parent: inlineLineage, durableTaskDispatched: false };\n const interceptedArgs = args.map((arg) =>\n typeof arg === \"function\"\n ? (...callbackArgs: unknown[]) =>\n this.inlinePromiseLineage.run(childLineage, () => Reflect.apply(arg, undefined, callbackArgs))\n : arg,\n );\n const derived = invoke(interceptedArgs);\n return this.trackInlineStepPromise(\n name,\n derived,\n inlineRoot,\n branch.inheritsRootRejection && !handlesRejection,\n childLineage,\n );\n });\n }\n}\n\nclass StepFailure extends Error {\n constructor(\n readonly stepName: string,\n readonly reason: unknown,\n ) {\n super(errorMessage(reason));\n }\n}\n\nfunction assertEntryName(name: string): void {\n if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(name)) {\n throw new Error(`workflow-sdk: invalid journal entry name \"${name}\"`);\n }\n}\n\nfunction encodeJSONValue(value: unknown, kind: string): string {\n try {\n const encoded = JSON.stringify(value);\n if (encoded === undefined) throw new Error(\"unsupported value\");\n return encoded;\n } catch (error) {\n // Deliberate serialization errors (e.g. a nested WorkflowFile) beat the generic hint.\n if (error instanceof Error && error.message.startsWith(\"workflow-sdk:\")) throw error;\n throw new Error(`workflow-sdk: ${kind} must be JSON-serializable`);\n }\n}\n\nfunction cloneJSONValue(value: unknown, kind: string): unknown {\n return JSON.parse(encodeJSONValue(value, kind)) as unknown;\n}\n\nfunction readJournalResult(entry: JournalEntry): unknown {\n if (entry.resultType === \"undefined\") return undefined;\n if (entry.resultType === \"ref\") return resolveJournalRef(entry);\n return structuredClone(entry.result);\n}\n\nfunction errorMessage(err: unknown): string {\n // Persist messages only; stacks and thrown objects can contain paths or user values.\n return err instanceof Error ? err.message : String(err);\n}\n\n// Large-payload offload (claim-check payloads): docs/workflows/payload-offload.md\n\n// encode() types its buffer as ArrayBufferLike under node typings; slice() copies to a plain ArrayBuffer.\nfunction utf8PayloadBytes(text: string): Uint8Array<ArrayBuffer> {\n return new TextEncoder().encode(text).slice();\n}\n\n// CryptoKey spelled structurally: not every embedding tsconfig loads lib.dom.\nexport type PayloadCryptoKey = Awaited<ReturnType<typeof crypto.subtle.importKey>>;\n\nconst PAYLOAD_SCHEME: PayloadAeadScheme = \"CHUNKED_AES_256_GCM_V1\";\nconst PAYLOAD_SEGMENT_SIZE = 1_048_576;\nconst PAYLOAD_NONCE_BYTES = 12;\nconst PAYLOAD_TAG_BYTES = 16;\nconst PAYLOAD_AAD_PREFIX = new TextEncoder().encode(\"lovable-workflow-payload/v1\");\nconst PAYLOAD_MAX_FRAME_BYTES = PAYLOAD_NONCE_BYTES + PAYLOAD_SEGMENT_SIZE + PAYLOAD_TAG_BYTES;\nconst payloadOffloadPath = \"/runtime/v1/payloads\";\n\nfunction isPayloadRefValue(value: unknown): value is PayloadRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n hasOwn(value, \"bucket\") &&\n typeof value.bucket === \"string\" &&\n value.bucket.length > 0 &&\n value.bucket.length <= 128 &&\n hasOwn(value, \"key\") &&\n typeof value.key === \"string\" &&\n value.key.length > 0 &&\n value.key.length <= 1024 &&\n hasOwn(value, \"sha256\") &&\n typeof value.sha256 === \"string\" &&\n /^[0-9a-f]{64}$/.test(value.sha256) &&\n hasOwn(value, \"sizeBytes\") &&\n typeof value.sizeBytes === \"number\" &&\n Number.isSafeInteger(value.sizeBytes) &&\n value.sizeBytes >= 0 &&\n hasOwn(value, \"contentType\") &&\n typeof value.contentType === \"string\" &&\n value.contentType.length > 0 &&\n value.contentType.length <= 256 &&\n hasOwn(value, \"wrappedDek\") &&\n typeof value.wrappedDek === \"string\" &&\n hasOwn(value, \"kekId\") &&\n typeof value.kekId === \"string\" &&\n value.kekId.length > 0 &&\n value.kekId.length <= 128 &&\n hasOwn(value, \"scheme\") &&\n value.scheme === PAYLOAD_SCHEME\n );\n}\n\nfunction isPayloadGrantValue(value: unknown): value is PayloadGrant {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n hasOwn(value, \"getUrl\") &&\n typeof value.getUrl === \"string\" &&\n value.getUrl.length > 0 &&\n hasOwn(value, \"dek\") &&\n typeof value.dek === \"string\" &&\n value.dek.length > 0\n );\n}\n\nfunction isPayloadOffloadValue(value: unknown): value is PayloadOffload {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n hasOwn(value, \"endpoint\") &&\n typeof value.endpoint === \"string\" &&\n value.endpoint.length > 0 &&\n value.endpoint.length <= 2048 &&\n hasOwn(value, \"threshold\") &&\n typeof value.threshold === \"number\" &&\n Number.isSafeInteger(value.threshold) &&\n value.threshold >= 0 &&\n hasOwn(value, \"maxBytes\") &&\n typeof value.maxBytes === \"number\" &&\n Number.isSafeInteger(value.maxBytes) &&\n value.maxBytes >= 1\n );\n}\n\nfunction normalizedPayloadOffload(value: PayloadOffload | undefined): PayloadOffload | undefined {\n if (value === undefined) return undefined;\n if (!isPayloadOffloadValue(value)) {\n throw new Error(\"workflow-sdk: invalid payload offload configuration\");\n }\n return { endpoint: value.endpoint, threshold: value.threshold, maxBytes: value.maxBytes };\n}\n\nfunction isJournalEntryValue(entry: unknown): boolean {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) return false;\n if (hasOwn(entry, \"resultType\") && entry.resultType === \"ref\") {\n return (\n !hasOwn(entry, \"result\") &&\n hasOwn(entry, \"ref\") &&\n isPayloadRefValue(entry.ref) &&\n (!hasOwn(entry, \"transparent\") || typeof entry.transparent === \"boolean\") &&\n (!hasOwn(entry, \"grant\") || isPayloadGrantValue(entry.grant))\n );\n }\n return hasOwn(entry, \"result\") && (!hasOwn(entry, \"resultType\") || entry.resultType === \"undefined\");\n}\n\n// Incremental SHA-256 (FIPS 180-4): WebCrypto digests are one-shot, and the\n// decrypt path must hash the plaintext without buffering the whole object.\nconst SHA256_K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,\n 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,\n 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,\n 0xc67178f2,\n]);\n\nfunction rotr32(value: number, count: number): number {\n return (value >>> count) | (value << (32 - count));\n}\n\nclass Sha256 {\n private readonly state = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]);\n private readonly block = new Uint8Array(64);\n private readonly schedule = new Uint32Array(64);\n private blockBytes = 0;\n private totalBytes = 0;\n\n update(data: Uint8Array): void {\n this.totalBytes += data.length;\n let offset = 0;\n while (offset < data.length) {\n const take = Math.min(64 - this.blockBytes, data.length - offset);\n this.block.set(data.subarray(offset, offset + take), this.blockBytes);\n this.blockBytes += take;\n offset += take;\n if (this.blockBytes === 64) {\n this.compress();\n this.blockBytes = 0;\n }\n }\n }\n\n /** Finalizes the digest; the instance must not be updated afterwards. */\n hex(): string {\n const bitLength = BigInt(this.totalBytes) * 8n;\n this.update(new Uint8Array([0x80]));\n while (this.blockBytes !== 56) this.update(new Uint8Array(1));\n const length = new Uint8Array(8);\n new DataView(length.buffer).setBigUint64(0, bitLength, false);\n this.update(length);\n let hex = \"\";\n for (const word of this.state) hex += word.toString(16).padStart(8, \"0\");\n return hex;\n }\n\n private compress(): void {\n const words = this.schedule;\n const view = new DataView(this.block.buffer);\n for (let index = 0; index < 16; index++) {\n words[index] = view.getUint32(index * 4, false);\n }\n for (let index = 16; index < 64; index++) {\n const s0 = rotr32(words[index - 15], 7) ^ rotr32(words[index - 15], 18) ^ (words[index - 15] >>> 3);\n const s1 = rotr32(words[index - 2], 17) ^ rotr32(words[index - 2], 19) ^ (words[index - 2] >>> 10);\n words[index] = words[index - 16] + s0 + words[index - 7] + s1;\n }\n let [a, b, c, d, e, f, g, h] = this.state;\n for (let index = 0; index < 64; index++) {\n const s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);\n const ch = (e & f) ^ (~e & g);\n const t1 = (h + s1 + ch + SHA256_K[index] + words[index]) | 0;\n const s0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22);\n const maj = (a & b) ^ (a & c) ^ (b & c);\n const t2 = (s0 + maj) | 0;\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n this.state[0] += a;\n this.state[1] += b;\n this.state[2] += c;\n this.state[3] += d;\n this.state[4] += e;\n this.state[5] += f;\n this.state[6] += g;\n this.state[7] += h;\n }\n}\n\nclass ByteQueue {\n private chunks: Uint8Array<ArrayBuffer>[] = [];\n private length = 0;\n\n get size(): number {\n return this.length;\n }\n\n push(chunk: Uint8Array<ArrayBuffer>): void {\n if (chunk.length === 0) return;\n this.chunks.push(chunk);\n this.length += chunk.length;\n }\n\n peek(count: number): Uint8Array<ArrayBuffer> | undefined {\n if (this.length < count) return undefined;\n const out = new Uint8Array(count);\n let offset = 0;\n for (const chunk of this.chunks) {\n const slice = chunk.subarray(0, Math.min(chunk.length, count - offset));\n out.set(slice, offset);\n offset += slice.length;\n if (offset === count) break;\n }\n return out;\n }\n\n take(count: number): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(count);\n let offset = 0;\n while (offset < count) {\n const head = this.chunks[0];\n const needed = count - offset;\n if (head.length <= needed) {\n out.set(head, offset);\n offset += head.length;\n this.chunks.shift();\n } else {\n out.set(head.subarray(0, needed), offset);\n this.chunks[0] = head.subarray(needed);\n offset = count;\n }\n }\n this.length -= count;\n return out;\n }\n}\n\n// AAD binds the scheme label, big-endian segment index, and final flag, so\n// truncation, reordering, and non-final-after-final all fail authentication.\nfunction payloadSegmentAad(index: number, final: boolean): Uint8Array<ArrayBuffer> {\n const aad = new Uint8Array(PAYLOAD_AAD_PREFIX.length + 9);\n aad.set(PAYLOAD_AAD_PREFIX, 0);\n new DataView(aad.buffer).setBigUint64(PAYLOAD_AAD_PREFIX.length, BigInt(index), false);\n aad[aad.length - 1] = final ? 1 : 0;\n return aad;\n}\n\nasync function sealPayloadSegment(\n key: PayloadCryptoKey,\n index: number,\n final: boolean,\n plaintext: Uint8Array<ArrayBuffer>,\n): Promise<Uint8Array<ArrayBuffer>> {\n const nonce = crypto.getRandomValues(new Uint8Array(PAYLOAD_NONCE_BYTES));\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv: nonce, additionalData: payloadSegmentAad(index, final) },\n key,\n plaintext,\n ),\n );\n const frame = new Uint8Array(4 + PAYLOAD_NONCE_BYTES + sealed.length);\n new DataView(frame.buffer).setUint32(0, PAYLOAD_NONCE_BYTES + sealed.length, false);\n frame.set(nonce, 4);\n frame.set(sealed, 4 + PAYLOAD_NONCE_BYTES);\n return frame;\n}\n\nasync function openPayloadSegment(\n key: PayloadCryptoKey,\n nonce: Uint8Array<ArrayBuffer>,\n sealed: Uint8Array<ArrayBuffer>,\n index: number,\n final: boolean,\n): Promise<Uint8Array<ArrayBuffer> | undefined> {\n try {\n return new Uint8Array(\n await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: nonce, additionalData: payloadSegmentAad(index, final) },\n key,\n sealed,\n ),\n );\n } catch {\n return undefined;\n }\n}\n\n/** Chunked AES-256-GCM encryptor emitting [payloadLen u32 BE][nonce 12][ciphertext||tag] frames. */\nexport function encryptPayloadStream(key: PayloadCryptoKey): TransformStream<Uint8Array, Uint8Array> {\n const pending = new ByteQueue();\n let index = 0;\n return new TransformStream<Uint8Array, Uint8Array>({\n async transform(chunk, controller) {\n if (!(chunk instanceof Uint8Array)) {\n throw new Error(\"workflow-sdk: payload streams must produce Uint8Array chunks\");\n }\n pending.push(chunk.slice());\n // Holding one byte back keeps the mandatory final segment non-empty unless the payload is empty.\n while (pending.size > PAYLOAD_SEGMENT_SIZE) {\n controller.enqueue(await sealPayloadSegment(key, index, false, pending.take(PAYLOAD_SEGMENT_SIZE)));\n index += 1;\n }\n },\n async flush(controller) {\n controller.enqueue(await sealPayloadSegment(key, index, true, pending.take(pending.size)));\n },\n });\n}\n\n/** Decrypts CHUNKED_AES_256_GCM_V1; rejects truncation, reordering, splices, and digest or size mismatches. */\nexport function decryptPayloadStream(\n key: PayloadCryptoKey,\n expected: { sha256: string; sizeBytes: number },\n): TransformStream<Uint8Array, Uint8Array> {\n const pending = new ByteQueue();\n const digest = new Sha256();\n let index = 0;\n let finalSeen = false;\n let plaintextBytes = 0;\n const drain = async (controller: TransformStreamDefaultController<Uint8Array>): Promise<void> => {\n for (;;) {\n const header = pending.peek(4);\n if (header === undefined) return;\n const payloadLength = new DataView(header.buffer).getUint32(0, false);\n if (payloadLength < PAYLOAD_NONCE_BYTES + PAYLOAD_TAG_BYTES || payloadLength > PAYLOAD_MAX_FRAME_BYTES) {\n throw new Error(\"workflow-sdk: offloaded payload frame has an invalid length\");\n }\n if (pending.size < 4 + payloadLength) return;\n if (finalSeen) {\n throw new Error(\"workflow-sdk: offloaded payload has data after the final segment\");\n }\n pending.take(4);\n const frame = pending.take(payloadLength);\n const nonce = frame.subarray(0, PAYLOAD_NONCE_BYTES);\n const sealed = frame.subarray(PAYLOAD_NONCE_BYTES);\n // Only full segments can be non-final; anything shorter must authenticate as final.\n let plaintext =\n sealed.length - PAYLOAD_TAG_BYTES === PAYLOAD_SEGMENT_SIZE\n ? await openPayloadSegment(key, nonce, sealed, index, false)\n : undefined;\n if (plaintext === undefined) {\n plaintext = await openPayloadSegment(key, nonce, sealed, index, true);\n if (plaintext === undefined) {\n throw new Error(\"workflow-sdk: offloaded payload segment failed authentication\");\n }\n finalSeen = true;\n }\n index += 1;\n plaintextBytes += plaintext.length;\n digest.update(plaintext);\n if (plaintext.length > 0) controller.enqueue(plaintext);\n }\n };\n return new TransformStream<Uint8Array, Uint8Array>({\n async transform(chunk, controller) {\n if (!(chunk instanceof Uint8Array)) {\n throw new Error(\"workflow-sdk: payload streams must produce Uint8Array chunks\");\n }\n pending.push(chunk.slice());\n await drain(controller);\n },\n async flush(controller) {\n await drain(controller);\n if (!finalSeen) {\n throw new Error(\"workflow-sdk: offloaded payload is truncated before its final segment\");\n }\n if (pending.size > 0) {\n throw new Error(\"workflow-sdk: offloaded payload has trailing bytes after the final segment\");\n }\n if (plaintextBytes !== expected.sizeBytes) {\n throw new Error(\"workflow-sdk: offloaded payload size does not match its journal pointer\");\n }\n if (digest.hex() !== expected.sha256) {\n throw new Error(\"workflow-sdk: offloaded payload digest does not match its journal pointer\");\n }\n },\n });\n}\n\nfunction decodeBase64(value: string, kind: string): Uint8Array<ArrayBuffer> {\n try {\n const decoded = atob(value);\n const bytes = new Uint8Array(decoded.length);\n for (let index = 0; index < decoded.length; index++) {\n bytes[index] = decoded.charCodeAt(index);\n }\n return bytes;\n } catch {\n throw new Error(`workflow-sdk: ${kind} is not valid base64`);\n }\n}\n\nfunction hexDigest(bytes: ArrayBuffer): string {\n let hex = \"\";\n for (const byte of new Uint8Array(bytes)) {\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return hex;\n}\n\nasync function importPayloadDek(dek: string): Promise<PayloadCryptoKey> {\n const raw = decodeBase64(dek, \"payload DEK\");\n if (raw.length !== 32) {\n throw new Error(\"workflow-sdk: payload DEK must be 32 bytes\");\n }\n return crypto.subtle.importKey(\"raw\", raw, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n}\n\nfunction httpsUrl(value: string, kind: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`workflow-sdk: ${kind} is not a valid URL`);\n }\n if (url.protocol !== \"https:\") {\n throw new Error(`workflow-sdk: ${kind} must use https`);\n }\n return value;\n}\n\nasync function collectStream(stream: ReadableStream<Uint8Array>): Promise<Uint8Array<ArrayBuffer>> {\n const reader = stream.getReader();\n const pending = new ByteQueue();\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!(value instanceof Uint8Array)) {\n void reader.cancel().catch(() => undefined);\n throw new Error(\"workflow-sdk: payload streams must produce Uint8Array chunks\");\n }\n pending.push(value.slice());\n }\n return pending.take(pending.size);\n}\n\nasync function encryptPayloadBytes(\n key: PayloadCryptoKey,\n plaintext: Uint8Array<ArrayBuffer>,\n): Promise<Uint8Array<ArrayBuffer>> {\n const source = new ReadableStream<Uint8Array>({\n start(controller) {\n if (plaintext.length > 0) controller.enqueue(plaintext);\n controller.close();\n },\n });\n return collectStream(source.pipeThrough(encryptPayloadStream(key)));\n}\n\nfunction payloadOffloadEndpoint(endpoint: string): string {\n for (const origin of workflowApiOrigins) {\n if (endpoint === `${origin}${payloadOffloadPath}`) return endpoint;\n }\n throw new Error(\"workflow-sdk: payload offload endpoint is not an allowed workflows origin\");\n}\n\ninterface PayloadUploadTicket {\n putUrl: string;\n key: PayloadCryptoKey;\n ref: PayloadRef;\n}\n\nasync function requestPayloadUpload(\n offload: PayloadOffload,\n sha256: string,\n sizeBytes: number,\n contentType: string,\n): Promise<PayloadUploadTicket> {\n const endpoint = payloadOffloadEndpoint(offload.endpoint);\n let response: Response;\n try {\n response = await fetch(endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ sha256, sizeBytes, contentType }),\n redirect: \"error\",\n });\n } catch {\n throw new Error(\"workflow-sdk: payload offload request failed\");\n }\n if (!response.ok) {\n throw new Error(\"workflow-sdk: payload offload request failed\");\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n throw new Error(\"workflow-sdk: invalid payload offload response\");\n }\n if (\n typeof body !== \"object\" ||\n body === null ||\n Array.isArray(body) ||\n !hasOwn(body, \"putUrl\") ||\n typeof body.putUrl !== \"string\" ||\n !hasOwn(body, \"dek\") ||\n typeof body.dek !== \"string\" ||\n !hasOwn(body, \"ref\") ||\n !isPayloadRefValue(body.ref)\n ) {\n throw new Error(\"workflow-sdk: invalid payload offload response\");\n }\n const ref = structuredClone(body.ref);\n if (ref.sha256 !== sha256 || ref.sizeBytes !== sizeBytes || ref.contentType !== contentType) {\n throw new Error(\"workflow-sdk: payload offload response does not match the requested payload\");\n }\n return { putUrl: httpsUrl(body.putUrl, \"payload upload URL\"), key: await importPayloadDek(body.dek), ref };\n}\n\nasync function uploadPayload(\n offload: PayloadOffload,\n plaintext: Uint8Array<ArrayBuffer>,\n contentType: string,\n): Promise<PayloadRef> {\n if (plaintext.byteLength > offload.maxBytes) {\n throw new Error(\n `workflow-sdk: payload of ${plaintext.byteLength} bytes exceeds the offload limit of ${offload.maxBytes} bytes`,\n );\n }\n const sha256 = hexDigest(await crypto.subtle.digest(\"SHA-256\", plaintext));\n const ticket = await requestPayloadUpload(offload, sha256, plaintext.byteLength, contentType);\n const ciphertext = await encryptPayloadBytes(ticket.key, plaintext);\n let response: Response;\n try {\n response = await fetch(ticket.putUrl, {\n method: \"PUT\",\n headers: { \"content-type\": \"application/octet-stream\" },\n body: ciphertext,\n redirect: \"error\",\n });\n } catch {\n throw new Error(\"workflow-sdk: payload upload failed\");\n }\n if (!response.ok) {\n throw new Error(\"workflow-sdk: payload upload failed\");\n }\n return ticket.ref;\n}\n\nfunction openPayloadReadStream(ref: PayloadRef, grant: PayloadGrant): ReadableStream<Uint8Array> {\n const relay = new TransformStream<Uint8Array, Uint8Array>();\n void (async () => {\n const getUrl = httpsUrl(grant.getUrl, \"payload read URL\");\n const key = await importPayloadDek(grant.dek);\n let response: Response;\n try {\n response = await fetch(getUrl, { method: \"GET\", redirect: \"error\" });\n } catch {\n throw new Error(\"workflow-sdk: offloaded payload download failed\");\n }\n if (!response.ok || response.body === null) {\n throw new Error(\"workflow-sdk: offloaded payload download failed\");\n }\n await response.body\n .pipeThrough(decryptPayloadStream(key, { sha256: ref.sha256, sizeBytes: ref.sizeBytes }))\n .pipeTo(relay.writable);\n })().catch((error: unknown) => {\n void relay.writable.abort(error).catch(() => undefined);\n });\n return relay.readable;\n}\n\ntype PayloadFileSource = { kind: \"remote\"; grant: PayloadGrant } | { kind: \"local\"; bytes: Uint8Array<ArrayBuffer> };\n\nclass PayloadFile implements WorkflowFile {\n constructor(\n readonly ref: PayloadRef,\n private readonly source: PayloadFileSource,\n ) {}\n\n get sha256(): string {\n return this.ref.sha256;\n }\n\n get sizeBytes(): number {\n return this.ref.sizeBytes;\n }\n\n get contentType(): string {\n return this.ref.contentType;\n }\n\n stream(): ReadableStream<Uint8Array> {\n if (this.source.kind === \"local\") {\n const bytes = this.source.bytes.slice();\n return new ReadableStream<Uint8Array>({\n start(controller) {\n if (bytes.length > 0) controller.enqueue(bytes);\n controller.close();\n },\n });\n }\n return openPayloadReadStream(this.ref, this.source.grant);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n const bytes = this.source.kind === \"local\" ? this.source.bytes : await collectStream(this.stream());\n const copy = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(copy).set(bytes);\n return copy;\n }\n\n async text(): Promise<string> {\n return new TextDecoder().decode(await this.arrayBuffer());\n }\n\n async json(): Promise<unknown> {\n return JSON.parse(await this.text()) as unknown;\n }\n\n /** Handles journal as their pointer only as a step's direct result; nesting fails loudly. */\n toJSON(): never {\n throw new Error(\"workflow-sdk: a WorkflowFile must be a step's direct result, not nested inside a JSON value\");\n }\n}\n\nfunction resolveJournalRef(entry: JournalEntry): unknown {\n const ref = entry.ref;\n if (ref === undefined || !isPayloadRefValue(ref)) {\n throw new Error(\"workflow-sdk: offloaded journal entry carries a malformed payload pointer\");\n }\n if (entry.grant === undefined) {\n throw new Error(\n \"workflow-sdk: journal entry points at an offloaded payload but carries no read grant; \" +\n \"the engine must hydrate grants before invocation (permanent)\",\n );\n }\n if (!isPayloadGrantValue(entry.grant)) {\n throw new Error(\"workflow-sdk: offloaded journal entry carries a malformed read grant\");\n }\n const file = new PayloadFile(structuredClone(ref), { kind: \"remote\", grant: structuredClone(entry.grant) });\n // Only auto-offloaded entries unwrap; explicit files.create refs replay as handles.\n return entry.transparent === true ? file.json() : file;\n}\n\nasync function payloadCreateBytes(\n data: ReadableStream<Uint8Array> | ArrayBuffer | Uint8Array | string,\n): Promise<Uint8Array<ArrayBuffer>> {\n if (typeof data === \"string\") return utf8PayloadBytes(data);\n if (data instanceof Uint8Array) return data.slice();\n if (data instanceof ArrayBuffer) return new Uint8Array(data.slice(0));\n if (data instanceof ReadableStream) return collectStream(data);\n throw new Error(\"workflow-sdk: files.create accepts a ReadableStream, ArrayBuffer, Uint8Array, or string\");\n}\n\nasync function createWorkflowFile(\n offload: PayloadOffload,\n data: ReadableStream<Uint8Array> | ArrayBuffer | Uint8Array | string,\n options: { contentType: string },\n): Promise<WorkflowFile> {\n if (typeof options !== \"object\" || options === null || typeof options.contentType !== \"string\") {\n throw new Error(\"workflow-sdk: files.create requires a contentType\");\n }\n if (options.contentType.length === 0 || options.contentType.length > 256) {\n throw new Error(\"workflow-sdk: files.create contentType must be 1-256 characters\");\n }\n // Tranche 1 limitation: stream inputs are fully buffered in memory before upload.\n const plaintext = await payloadCreateBytes(data);\n const ref = await uploadPayload(offload, plaintext, options.contentType);\n return new PayloadFile(ref, { kind: \"local\", bytes: plaintext });\n}\n\nconst WORKFLOW_LOG_ENVELOPE_KEY = \"__lovable_workflow_log\";\nconst MAX_LOG_MESSAGE_CHARS = 8192;\nconst MAX_LOGS_PER_INVOCATION = 512;\nconst MAX_LOG_FIELDS = 64;\nconst MAX_LOG_FIELD_CHARS = 2048;\n\n// Canonical set: CREDENTIAL_FIELD_NAMES in packages/workers-wide-event-sink;\n// the SDK stays dependency-free, so it is duplicated (pinned by a sync test).\nconst CREDENTIAL_FIELD_NAMES = [\n \"password\",\n \"passwd\",\n \"secret\",\n \"token\",\n \"authorization\",\n \"auth\",\n \"signature\",\n \"sig\",\n \"credential\",\n \"cookie\",\n \"session\",\n \"key\",\n] as const;\n\nconst CREDENTIAL_NAME_ALTERNATION = CREDENTIAL_FIELD_NAMES.join(\"|\");\n\n// Mirrors packages/workers-wide-event-sink/src/scrub.ts; the SDK stays\n// dependency-free, so the rules are duplicated rather than imported.\nconst LOG_SCRUB_RULES: { pattern: RegExp; replacement: string }[] = [\n {\n pattern: /-----BEGIN[A-Z ]*PRIVATE KEY-----[\\s\\S]+?-----END[A-Z ]*PRIVATE KEY-----/g,\n replacement: \"[REDACTED:private-key]\",\n },\n {\n pattern: /\\beyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{4,}(?:\\.[A-Za-z0-9_-]+)?/g,\n replacement: \"[REDACTED:jwt]\",\n },\n {\n pattern: /\\b(bearer|basic)\\s+[A-Za-z0-9._~+/=-]{12,}/gi,\n replacement: \"$1 [REDACTED]\",\n },\n { pattern: /\\bsk[-_][A-Za-z0-9_-]{10,}/g, replacement: \"[REDACTED:api-key]\" },\n { pattern: /\\brk_(?:live|test)_[A-Za-z0-9]{10,}/g, replacement: \"[REDACTED:api-key]\" },\n { pattern: /\\bgh[pousr]_[A-Za-z0-9]{20,}/g, replacement: \"[REDACTED:github-token]\" },\n { pattern: /\\bgithub_pat_[A-Za-z0-9_]{20,}/g, replacement: \"[REDACTED:github-token]\" },\n { pattern: /\\bxox[abeprst]-[A-Za-z0-9-]{10,}/g, replacement: \"[REDACTED:slack-token]\" },\n { pattern: /\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g, replacement: \"[REDACTED:aws-key]\" },\n { pattern: /\\bAIza[0-9A-Za-z_-]{30,}/g, replacement: \"[REDACTED:google-key]\" },\n { pattern: /\\bya29\\.[0-9A-Za-z_-]{20,}/g, replacement: \"[REDACTED:google-token]\" },\n { pattern: /\\bglpat-[A-Za-z0-9_-]{20,}/g, replacement: \"[REDACTED:gitlab-token]\" },\n { pattern: /\\bnpm_[A-Za-z0-9]{30,}/g, replacement: \"[REDACTED:npm-token]\" },\n {\n pattern: new RegExp(`((?:${CREDENTIAL_NAME_ALTERNATION})s?[\"']?\\\\s*[:=]\\\\s*[\"']?)[^\\\\s\"'\\`,;&]{6,}`, \"gi\"),\n replacement: \"$1[REDACTED]\",\n },\n];\n\n// Substring match on the key: also catches sessionId, keyId, tokenValue,\n// authHeader, etc. Redact-over-leak bias is deliberate.\nconst SENSITIVE_FIELD_KEY = new RegExp(`(?:${CREDENTIAL_NAME_ALTERNATION})`, \"i\");\n\n// Never splits a surrogate pair at the cap boundary.\nfunction truncateLogText(text: string, max: number): string {\n if (text.length <= max) return text;\n let end = max;\n const tail = text.charCodeAt(end - 1);\n if (tail >= 0xd800 && tail <= 0xdbff) end -= 1;\n return `${text.slice(0, end)}…[truncated]`;\n}\n\nfunction scrubLogText(text: string): string {\n let scrubbed = text;\n for (const rule of LOG_SCRUB_RULES) {\n scrubbed = scrubbed.replace(rule.pattern, rule.replacement);\n }\n return scrubbed;\n}\n\nfunction sanitizeLogFields(fields: Record<string, unknown>): Record<string, unknown> | undefined {\n const sanitized: Record<string, unknown> = {};\n let count = 0;\n for (const [key, value] of Object.entries(fields)) {\n if (key.length === 0 || key.length > 128) continue;\n if (count >= MAX_LOG_FIELDS) {\n sanitized.__fields_truncated = true;\n break;\n }\n count += 1;\n if (SENSITIVE_FIELD_KEY.test(key)) {\n sanitized[key] = \"[REDACTED]\";\n continue;\n }\n if (typeof value === \"boolean\" || (typeof value === \"number\" && Number.isFinite(value))) {\n sanitized[key] = value;\n continue;\n }\n let text: string;\n if (typeof value === \"string\") {\n text = value;\n } else {\n try {\n text = JSON.stringify(value) ?? String(value);\n } catch {\n text = \"[unserializable]\";\n }\n }\n sanitized[key] = truncateLogText(scrubLogText(text), MAX_LOG_FIELD_CHARS);\n }\n return count > 0 || hasOwn(sanitized, \"__fields_truncated\") ? sanitized : undefined;\n}\n\nfunction safeEmit(emit: WorkflowLogEmitter, entry: WorkflowLogEntry): void {\n try {\n emit(entry);\n } catch {\n // Logging must never break the run.\n }\n}\n\nfunction createWorkflowLogger(emit: WorkflowLogEmitter, isReplaying?: () => boolean): WorkflowLogger {\n let emitted = 0;\n let limitReported = false;\n const record = (level: WorkflowLogLevel, message: string, fields?: Record<string, unknown>): void => {\n // Replayed body code already emitted these entries in a prior invocation;\n // suppressed entries do not consume the per-invocation cap.\n if (isReplaying?.() === true) return;\n if (emitted >= MAX_LOGS_PER_INVOCATION) {\n if (!limitReported) {\n limitReported = true;\n safeEmit(emit, {\n level: \"warn\",\n message: `workflow-sdk: log limit of ${MAX_LOGS_PER_INVOCATION} entries reached; further logs dropped`,\n });\n }\n return;\n }\n emitted += 1;\n const text = truncateLogText(\n scrubLogText(typeof message === \"string\" ? message : String(message)),\n MAX_LOG_MESSAGE_CHARS,\n );\n const sanitizedFields =\n fields === null || typeof fields !== \"object\" || Array.isArray(fields) ? undefined : sanitizeLogFields(fields);\n safeEmit(emit, { level, message: text, ...(sanitizedFields === undefined ? {} : { fields: sanitizedFields }) });\n };\n return {\n debug: (message, fields) => record(\"debug\", message, fields),\n info: (message, fields) => record(\"info\", message, fields),\n warn: (message, fields) => record(\"warn\", message, fields),\n error: (message, fields) => record(\"error\", message, fields),\n };\n}\n\n// The envelope key goes first so consumers can cheaply pre-filter before JSON\n// parsing; workers/workflows-otel-tail-worker relies on this shape.\nconst envelopeLogEmitter: WorkflowLogEmitter = (entry) => {\n const line = JSON.stringify({\n [WORKFLOW_LOG_ENVELOPE_KEY]: 1,\n level: entry.level,\n message: entry.message,\n ...(entry.fields === undefined ? {} : { fields: entry.fields }),\n });\n if (entry.level === \"debug\") console.debug(line);\n else if (entry.level === \"warn\") console.warn(line);\n else if (entry.level === \"error\") console.error(line);\n else console.info(line);\n};\n\ntype HandlerOutcome<Output> = { kind: \"done\"; output: Output } | { kind: \"failed\"; error: unknown };\n\nexport interface InvokeOptions {\n /** Receives each capped and scrubbed entry; defaults to JSON envelopes on the console. */\n onLog?: WorkflowLogEmitter;\n}\n\nexport async function invoke<Input, Output>(\n workflow: WorkflowDefinition<Input, Output>,\n request: WorkerRequest<Input>,\n options: InvokeOptions = {},\n): Promise<WorkerResponse<Output>> {\n const execution = new Execution(\n request.input,\n request.journal ?? {},\n normalizedPayloadOffload(request.payloadOffload),\n options.onLog ?? envelopeLogEmitter,\n );\n let settledHandlerOutcome: HandlerOutcome<Output> | undefined;\n const settleHandler = (outcome: HandlerOutcome<Output>): HandlerOutcome<Output> => {\n settledHandlerOutcome = outcome;\n return outcome;\n };\n const dispatchOutcome = execution.waitForDispatch().then(() => ({ kind: \"dispatch\" as const }));\n const handlerOutcome = Promise.resolve()\n .then(() => workflow.handler(execution.context()))\n .then(\n (output) => settleHandler({ kind: \"done\", output }),\n (error: unknown) => settleHandler({ kind: \"failed\", error }),\n );\n const outcome = await Promise.race([dispatchOutcome, handlerOutcome]);\n await execution.settleStartedSteps();\n if (outcome.kind === \"dispatch\" || execution.hasDispatches()) {\n if (settledHandlerOutcome?.kind === \"failed\") {\n return failedWorkerResponse(settledHandlerOutcome.error, execution.completed);\n }\n const unconsumedInlineFailure = execution.unconsumedInlineFailure();\n if (unconsumedInlineFailure !== undefined) {\n return failedWorkerResponse(unconsumedInlineFailure, execution.completed);\n }\n const unconsumedTask = execution.unconsumedTaskFailure();\n if (unconsumedTask !== undefined) {\n return failedWorkerResponse(unconsumedTask, execution.completed);\n }\n return { status: \"dispatch\", steps: execution.dispatches, completed: execution.completed };\n }\n if (outcome.kind === \"done\") {\n const unconsumedInlineFailure = execution.unconsumedInlineFailure();\n if (unconsumedInlineFailure !== undefined) {\n return failedWorkerResponse(unconsumedInlineFailure, execution.completed);\n }\n const unconsumedTask = execution.unconsumedTaskFailure();\n if (unconsumedTask !== undefined) {\n return failedWorkerResponse(unconsumedTask, execution.completed);\n }\n if (outcome.output === undefined) {\n return { status: \"done\", output: null, outputType: \"undefined\", completed: execution.completed };\n }\n return { status: \"done\", output: outcome.output, completed: execution.completed };\n }\n return failedWorkerResponse(outcome.error, execution.completed);\n}\n\nfunction failedWorkerResponse<Output>(error: unknown, completed: Journal): WorkerResponse<Output> {\n const stepFailure = error instanceof StepFailure ? error : undefined;\n const failedStep =\n stepFailure?.stepName ?? (error instanceof PromiseRejectedError ? `@promise/${error.promiseName}` : undefined);\n return {\n status: \"failed\",\n error: errorMessage(stepFailure?.reason ?? error),\n ...(failedStep === undefined ? {} : { failedStep }),\n completed,\n };\n}\n\nfunction jsonResponse(body: unknown, status: number): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n}\n\nfunction isWorkerRequest(value: unknown): value is WorkerRequest<unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n if (!hasOwn(value, \"input\") || !hasOwn(value, \"journal\")) return false;\n if (\n hasOwn(value, \"payloadOffload\") &&\n value.payloadOffload !== undefined &&\n !isPayloadOffloadValue(value.payloadOffload)\n ) {\n return false;\n }\n const journal = value.journal;\n if (typeof journal !== \"object\" || journal === null || Array.isArray(journal)) return false;\n return Object.entries(journal).every(\n ([name, entry]) =>\n (/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(name) ||\n /^@(now|uuid|promise)\\/[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(name)) &&\n isJournalEntryValue(entry),\n );\n}\n\nfunction isWorkerTaskRequest(value: unknown): value is WorkerTaskRequest<unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n if (\n !hasOwn(value, \"operation\") ||\n !hasOwn(value, \"task\") ||\n !hasOwn(value, \"input\") ||\n !hasOwn(value, \"runName\") ||\n !hasOwn(value, \"stepId\") ||\n !hasOwn(value, \"attempt\") ||\n !hasOwn(value, \"workflowTenant\") ||\n !hasOwn(value, \"workflowApiUrl\")\n ) {\n return false;\n }\n return (\n value.operation === \"task\" &&\n typeof value.task === \"string\" &&\n /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value.task) &&\n typeof value.runName === \"string\" &&\n value.runName.length > 0 &&\n value.runName.length <= 2048 &&\n typeof value.stepId === \"string\" &&\n /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value.stepId) &&\n typeof value.attempt === \"number\" &&\n Number.isInteger(value.attempt) &&\n value.attempt > 0 &&\n value.attempt <= 2_147_483_647 &&\n typeof value.workflowTenant === \"string\" &&\n /^[A-Za-z0-9_-]{1,128}$/.test(value.workflowTenant) &&\n typeof value.workflowApiUrl === \"string\"\n );\n}\n\nconst workflowApiOrigins = new Set([\"https://workflows.lovable.dev\", \"https://workflows.d.l5e.io\"]);\n\nfunction workflowApiOrigin(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const normalized = value.endsWith(\"/\") ? value.slice(0, -1) : value;\n return workflowApiOrigins.has(normalized) ? normalized : undefined;\n}\n\nfunction workflowIdentifier(value: unknown, kind: string): string {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9_-]{1,128}$/.test(value)) {\n throw new Error(`workflow-sdk: invalid ${kind}`);\n }\n return value;\n}\n\nfunction workflowRunResponse(value: unknown): WorkflowRun {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(\"workflow-sdk: invalid workflow invocation response\");\n }\n const id = hasOwn(value, \"id\") ? value.id : undefined;\n const state = hasOwn(value, \"state\") ? value.state : undefined;\n const codeAttempt = hasOwn(value, \"code_attempt\") ? value.code_attempt : undefined;\n if (\n typeof id !== \"string\" ||\n typeof state !== \"string\" ||\n (codeAttempt !== undefined && (typeof codeAttempt !== \"number\" || !Number.isInteger(codeAttempt)))\n ) {\n throw new Error(\"workflow-sdk: invalid workflow invocation response\");\n }\n return {\n id,\n state,\n ...(hasOwn(value, \"error\") && typeof value.error === \"string\" ? { error: value.error } : {}),\n ...(hasOwn(value, \"inputs\") ? { inputs: value.inputs } : {}),\n ...(hasOwn(value, \"outputs\") ? { outputs: value.outputs } : {}),\n ...(codeAttempt === undefined ? {} : { codeAttempt }),\n ...(hasOwn(value, \"create_time\") && typeof value.create_time === \"string\" ? { createTime: value.create_time } : {}),\n ...(hasOwn(value, \"start_time\") && typeof value.start_time === \"string\" ? { startTime: value.start_time } : {}),\n ...(hasOwn(value, \"end_time\") && typeof value.end_time === \"string\" ? { endTime: value.end_time } : {}),\n };\n}\n\nfunction workflowsApi(origin: string | undefined, tenantId: string): WorkflowsApi {\n const invocations = new Set<string>();\n return {\n async run(request): Promise<WorkflowRun> {\n if (origin === undefined) {\n throw new Error(\"workflow-sdk: workflow API is not configured\");\n }\n if (typeof request !== \"object\" || request === null || Array.isArray(request)) {\n throw new Error(\"workflow-sdk: invalid workflow invocation\");\n }\n const workspaceId = workflowIdentifier(request.workspaceId, \"workflow workspace ID\");\n const projectId = workflowIdentifier(request.projectId, \"workflow project ID\");\n const workflowId = workflowIdentifier(request.workflowId, \"workflow ID\");\n if (\n request.invocationKey !== undefined &&\n (typeof request.invocationKey !== \"string\" || request.invocationKey.length > 128)\n ) {\n throw new Error(\"workflow-sdk: invalid workflow invocation key\");\n }\n const parent = `tenants/${tenantId}/workspaces/${workspaceId}/workflows/${workflowId}`;\n const invocation = `${parent}\\0${request.invocationKey ?? \"\"}`;\n if (invocations.has(invocation)) {\n throw new Error(\"workflow-sdk: duplicate workflow invocation key\");\n }\n invocations.add(invocation);\n const inputs = request.inputs === undefined ? undefined : cloneJSONValue(request.inputs, \"workflow inputs\");\n let response: Response;\n try {\n response = await fetch(`${origin}/runtime/v1/runs`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n parent,\n project_id: projectId,\n run: inputs === undefined ? {} : { inputs },\n ...(request.invocationKey === undefined ? {} : { invocation_key: request.invocationKey }),\n }),\n redirect: \"error\",\n });\n } catch {\n throw new Error(\"workflow-sdk: workflow invocation failed\");\n }\n if (!response.ok) {\n throw new Error(\"workflow-sdk: workflow invocation failed\");\n }\n try {\n return workflowRunResponse(await response.json());\n } catch (error) {\n if (error instanceof Error && error.message === \"workflow-sdk: invalid workflow invocation response\") {\n throw error;\n }\n throw new Error(\"workflow-sdk: invalid workflow invocation response\");\n }\n },\n };\n}\n\nexport interface WorkerOptions {\n tasks?: unknown;\n}\n\nexport interface Worker {\n fetch: (request: Request) => Promise<Response>;\n}\n\nfunction validatedWorkflowDefinition<Input, Output>(value: unknown): WorkflowDefinition<Input, Output> {\n if (typeof value !== \"object\" || value === null || !hasOwn(value, \"name\") || !hasOwn(value, \"handler\")) {\n throw new Error(\"workflow-sdk: invalid workflow definition\");\n }\n if (typeof value.name !== \"string\" || typeof value.handler !== \"function\") {\n throw new Error(\"workflow-sdk: invalid workflow definition\");\n }\n assertEntryName(value.name);\n return value as unknown as WorkflowDefinition<Input, Output>;\n}\n\nfunction validatedTaskDefinition(value: unknown): TaskDefinition<never, unknown> {\n if (\n typeof value !== \"object\" ||\n value === null ||\n !hasOwn(value, \"name\") ||\n !hasOwn(value, \"environment\") ||\n !hasOwn(value, \"run\") ||\n typeof value.name !== \"string\" ||\n value.environment !== \"cloudflare\" ||\n typeof value.run !== \"function\"\n ) {\n throw new Error(\"workflow-sdk: invalid task definition\");\n }\n return defineTask(value as unknown as CloudflareTaskConfig<never, unknown>);\n}\n\nfunction validatedTaskDefinitions(value: unknown): TaskDefinition<never, unknown>[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new Error(\"workflow-sdk: tasks must be an array of task definitions\");\n }\n return value.map((task) => validatedTaskDefinition(task));\n}\n\nexport function toWorker<Input, Output>(\n workflowValue: WorkflowDefinition<Input, Output>,\n options: WorkerOptions = {},\n): Worker {\n const workflow = validatedWorkflowDefinition<Input, Output>(workflowValue);\n const tasks = new Map<string, TaskDefinition<never, unknown>>();\n for (const task of validatedTaskDefinitions(options.tasks)) {\n if (tasks.has(task.name)) {\n throw new Error(`workflow-sdk: duplicate registered task name \"${task.name}\"`);\n }\n tasks.set(task.name, task);\n }\n return {\n async fetch(request: Request): Promise<Response> {\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return jsonResponse({ status: \"failed\", error: \"invalid request body\", completed: {} }, 400);\n }\n if (isWorkerTaskRequest(body)) {\n const workflowApiUrl = workflowApiOrigin(body.workflowApiUrl);\n if (body.workflowApiUrl !== \"\" && workflowApiUrl === undefined) {\n return jsonResponse({ status: \"failed\", error: \"workflow API is not configured\", completed: {} }, 503);\n }\n const task = tasks.get(body.task);\n if (task?.environment !== \"cloudflare\") {\n return jsonResponse({ status: \"failed\", error: \"task is not registered\", completed: {} }, 400);\n }\n try {\n const result = await task.run(body.input as never, {\n runName: body.runName,\n stepId: body.stepId,\n attempt: body.attempt,\n workflows: workflowsApi(workflowApiUrl, body.workflowTenant),\n log: createWorkflowLogger(envelopeLogEmitter),\n });\n const output = result === undefined ? null : cloneJSONValue(result, \"task output\");\n return jsonResponse(\n {\n status: \"done\",\n output,\n ...(result === undefined ? { outputType: \"undefined\" } : {}),\n completed: {},\n },\n 200,\n );\n } catch (err) {\n return jsonResponse(\n { status: \"failed\", error: errorMessage(err), failedStep: body.task, completed: {} },\n 200,\n );\n }\n }\n if (!isWorkerRequest(body)) {\n return jsonResponse({ status: \"failed\", error: \"invalid request body\", completed: {} }, 400);\n }\n const response = await invoke(workflow, body as WorkerRequest<Input>);\n try {\n return jsonResponse(response, 200);\n } catch {\n return jsonResponse(\n { status: \"failed\", error: \"workflow output is not JSON-serializable\", completed: response.completed },\n 200,\n );\n }\n },\n };\n}\n\nexport interface DriveOptions {\n /** Total invocations before a failure is surfaced. Default 1 (no retry). */\n maxAttempts?: number;\n /** Receives each capped and scrubbed entry; defaults to JSON envelopes on the console. */\n onLog?: WorkflowLogEmitter;\n}\n\nexport async function driveToCompletion<Input, Output>(\n workflow: WorkflowDefinition<Input, Output>,\n input: Input,\n options: DriveOptions = {},\n): Promise<Output> {\n const journal: Journal = Object.create(null) as Journal;\n const maxAttempts = Math.max(1, options.maxAttempts ?? 1);\n for (let attempt = 1; ; attempt++) {\n const response = await invoke(workflow, { input, journal }, { onLog: options.onLog });\n Object.assign(journal, response.completed);\n if (response.status === \"done\") {\n if (response.outputType === \"undefined\") {\n return undefined as Output;\n }\n return response.output;\n }\n if (response.status === \"dispatch\") {\n throw new Error(\"workflow-sdk: driveToCompletion cannot execute engine-dispatched steps\");\n }\n if (attempt >= maxAttempts) {\n throw new Error(response.error);\n }\n }\n}\n"],"mappings":";;AAoLA,SAAgB,WACd,QACyC;CACzC,gBAAgB,OAAO,IAAI;CAC3B,IAAI,OAAO,gBAAgB,cACzB,MAAM,IAAI,MAAM,mDAAmD;CAErE,IACE,OAAO,mBAAmB,KAAA,MACzB,CAAC,OAAO,UAAU,OAAO,cAAc,KAAK,OAAO,iBAAiB,KAAK,OAAO,iBAAiB,MAElG,MAAM,IAAI,MAAM,mEAAmE;CAErF,OAAO;AACT;;AAcA,IAAa,uBAAb,cAA0C,MAAM;CAEnC;CACA;CAFX,YACE,aACA,QACA;EACA,MAAM,0BAA0B,YAAY,cAAc,QAAQ;EAHzD,KAAA,cAAA;EACA,KAAA,SAAA;CAGX;AACF;AAoBA,SAAgB,eACd,MACA,SACmC;CACnC,OAAO;EAAE;EAAM;CAAQ;AACzB;AAEA,SAAS,OAAgC,OAAe,KAAkD;CACxG,OAAO,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG;AACxD;AAEA,SAAS,oBAAuB,OAA+B;CAC7D,MAAM,UAAU,IAAI,cAAiB,KAAA,CAAS;CAC9C,IAAI,UAAU;CACd,OAAO,wBAAwB,UAAU,SAAS,MAAM,WAAW;EACjE,IAAI,CAAC,SAAS;GACZ,UAAU;GACV,MAAM;EACR;EACA,OAAO,OAAO,IAAI;CACpB,CAAC;AACH;AAIA,SAAS,wBACP,SACA,WAKY;CACZ,OAAO,IAAI,MAAM,SAAS,EACxB,IAAI,QAAQ,UAAU;EACpB,IAAI,aAAa,U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ACF;EACA,IAAI,CAAC,gBAAgB,IAAI,GACvB,OAAO,aAAa;GAAE,QAAQ;GAAU,OAAO;GAAwB,WAAW,CAAC;EAAE,GAAG,GAAG;EAE7F,MAAM,WAAW,MAAM,OAAO,UAAU,IAA4B;EACpE,IAAI;GACF,OAAO,aAAa,UAAU,GAAG;EACnC,QAAQ;GACN,OAAO,aACL;IAAE,QAAQ;IAAU,OAAO;IAA4C,WAAW,SAAS;GAAU,GACrG,GACF;EACF;CACF,EACF;AACF;AASA,eAAsB,kBACpB,UACA,OACA,UAAwB,CAAC,GACR;CACjB,MAAM,UAAmB,OAAO,OAAO,IAAI;CAC3C,MAAM,cAAc,KAAK,IAAI,GAAG,QAAQ,eAAe,CAAC;CACxD,KAAK,IAAI,UAAU,IAAK,WAAW;EACjC,MAAM,WAAW,MAAM,OAAO,UAAU;GAAE;GAAO;EAAQ,GAAG,EAAE,OAAO,QAAQ,MAAM,CAAC;EACpF,OAAO,OAAO,SAAS,SAAS,SAAS;EACzC,IAAI,SAAS,WAAW,QAAQ;GAC9B,IAAI,SAAS,eAAe,aAC1B;GAEF,OAAO,SAAS;EAClB;EACA,IAAI,SAAS,WAAW,YACtB,MAAM,IAAI,MAAM,wEAAwE;EAE1F,IAAI,WAAW,aACb,MAAM,IAAI,MAAM,SAAS,KAAK;CAElC;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/sdk",
3
- "version": "1.4.0",
3
+ "version": "1.6.1",
4
4
  "description": "TypeScript SDK for the Lovable API",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -14,6 +14,10 @@
14
14
  "./schemas": {
15
15
  "types": "./src/schemas.ts",
16
16
  "import": "./dist/schemas.js"
17
+ },
18
+ "./workflows": {
19
+ "types": "./dist/workflows.d.ts",
20
+ "import": "./dist/workflows.js"
17
21
  }
18
22
  },
19
23
  "files": [
package/src/client.ts CHANGED
@@ -399,12 +399,11 @@ export class LovableClient {
399
399
  fileRefs = await this.uploadProjectFiles(projectId, options.files);
400
400
  }
401
401
 
402
- const body: Omit<Schemas["PublicV1SendMessageInputBody"], "project_id"> = {
402
+ const body: Omit<Schemas["PublicV1SendMessageInputBody"], "project_id"> & {
403
+ max_mode?: boolean;
404
+ } = {
403
405
  message: options.message,
404
406
  };
405
- if (options.variantId) {
406
- body.variant_id = options.variantId;
407
- }
408
407
  if (fileRefs) {
409
408
  body.files = fileRefs;
410
409
  }
@@ -414,6 +413,9 @@ export class LovableClient {
414
413
  if (options.planMode) {
415
414
  body.plan_mode = true;
416
415
  }
416
+ if (options.maxMode) {
417
+ body.max_mode = true;
418
+ }
417
419
  if (options.continuation) {
418
420
  body.continuation = options.continuation;
419
421
  }