@workflow/world-local 5.0.0-beta.5 → 5.0.0-beta.7

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.
Files changed (45) hide show
  1. package/dist/config.js +1 -1
  2. package/dist/fs.d.ts +3 -0
  3. package/dist/fs.d.ts.map +1 -1
  4. package/dist/fs.js +7 -3
  5. package/dist/index.js +1 -1
  6. package/dist/init.js +1 -1
  7. package/dist/instrumentObject.js +1 -1
  8. package/dist/queue.js +1 -1
  9. package/dist/storage/events-storage.d.ts.map +1 -1
  10. package/dist/storage/events-storage.js +59 -18
  11. package/dist/storage/filters.js +1 -1
  12. package/dist/storage/helpers.js +1 -1
  13. package/dist/storage/hooks-storage.js +1 -1
  14. package/dist/storage/index.js +1 -1
  15. package/dist/storage/legacy.d.ts.map +1 -1
  16. package/dist/storage/legacy.js +2 -1
  17. package/dist/storage/runs-storage.d.ts +5 -1
  18. package/dist/storage/runs-storage.d.ts.map +1 -1
  19. package/dist/storage/runs-storage.js +72 -3
  20. package/dist/storage/steps-storage.js +1 -1
  21. package/dist/storage.js +1 -1
  22. package/dist/streamer.js +1 -1
  23. package/dist/telemetry.js +1 -1
  24. package/dist/test-helpers.js +1 -1
  25. package/dist/util.js +1 -1
  26. package/package.json +4 -4
  27. package/dist/config.js.map +0 -1
  28. package/dist/fs.js.map +0 -1
  29. package/dist/index.js.map +0 -1
  30. package/dist/init.js.map +0 -1
  31. package/dist/instrumentObject.js.map +0 -1
  32. package/dist/queue.js.map +0 -1
  33. package/dist/storage/events-storage.js.map +0 -1
  34. package/dist/storage/filters.js.map +0 -1
  35. package/dist/storage/helpers.js.map +0 -1
  36. package/dist/storage/hooks-storage.js.map +0 -1
  37. package/dist/storage/index.js.map +0 -1
  38. package/dist/storage/legacy.js.map +0 -1
  39. package/dist/storage/runs-storage.js.map +0 -1
  40. package/dist/storage/steps-storage.js.map +0 -1
  41. package/dist/storage.js.map +0 -1
  42. package/dist/streamer.js.map +0 -1
  43. package/dist/telemetry.js.map +0 -1
  44. package/dist/test-helpers.js.map +0 -1
  45. package/dist/util.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"events-storage.js","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,EACpB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EACL,WAAW,EACX,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,qBAAqB,EACrB,UAAU,EACV,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,UAAU,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,EACxB,QAAQ,EACR,oBAAoB,EACpB,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,SAAS,GACV,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;;;GAWG;AACH,MAAM,SAAS,GAAG,IAAI,GAAG,EAA4B,CAAC;AAEtD,MAAM,oBAAoB,GAAG,CAAC,CAAC,MAAM,CAAC;IACpC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;CAClB,CAAC,CAAC;AAEH,KAAK,UAA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CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO;aAChC,CAAC,CAAC;YAEH,yDAAyD;YACzD,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO;oBACL,GAAG,MAAM;oBACT,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAC9B,kBAAkB,CAAC,KAAK,EAAE,WAAW,CAAC,CACvC;iBACF,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n EntityConflictError,\n HookNotFoundError,\n RunExpiredError,\n RunNotSupportedError,\n TooEarlyError,\n WorkflowRunNotFoundError,\n WorkflowWorldError,\n} from '@workflow/errors';\nimport type {\n Event,\n EventResult,\n Hook,\n SerializedData,\n Step,\n Storage,\n Wait,\n WorkflowRun,\n} from '@workflow/world';\nimport {\n EventSchema,\n HookSchema,\n isLegacySpecVersion,\n requiresNewerWorld,\n SPEC_VERSION_CURRENT,\n StepSchema,\n validateUlidTimestamp,\n WaitSchema,\n WorkflowRunSchema,\n} from '@workflow/world';\nimport { z } from 'zod';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n deleteJSON,\n jsonReplacer,\n listJSONFiles,\n paginatedFileSystemQuery,\n readJSON,\n readJSONWithFallback,\n resolveWithinBase,\n taggedPath,\n writeExclusive,\n writeJSON,\n} from '../fs.js';\nimport { stripEventDataRefs } from './filters.js';\nimport { getObjectCreatedAt, hashToken, monotonicUlid } from './helpers.js';\nimport { deleteAllHooksForRun } from './hooks-storage.js';\nimport { handleLegacyEvent } from './legacy.js';\n\n/**\n * Per-step in-process async mutex. Serializes concurrent `events.create` calls\n * that target the same step, so that the \"check terminal state, then write step\n * entity + event\" sequence is atomic. Without this, two concurrent step_started\n * calls can both pass the not-terminal check and both write step_started events\n * — or a step_started can land in the log after step_completed has already\n * written, producing unconsumed events on replay.\n *\n * Duplicate step_started events for a non-terminal step are still allowed\n * (retries legitimately re-start a step), only writes to an already-terminal\n * step are rejected.\n */\nconst stepLocks = new Map<string, Promise<unknown>>();\n\nconst HookTokenClaimSchema = z.object({\n runId: z.string(),\n});\n\nasync function readHookTokenClaim(\n constraintPath: string\n): Promise<z.infer<typeof HookTokenClaimSchema> | null> {\n try {\n return await readJSON(constraintPath, HookTokenClaimSchema);\n } catch (error) {\n if (error instanceof SyntaxError || error instanceof z.ZodError) {\n return null;\n }\n throw error;\n }\n}\n\nfunction withStepLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = stepLocks.get(key);\n const taskBox: { task?: Promise<T> } = {};\n const task = (async () => {\n if (prev) {\n // Wait for the previous task to settle; don't inherit its errors.\n await prev.catch(() => undefined);\n }\n try {\n return await fn();\n } finally {\n if (stepLocks.get(key) === taskBox.task) {\n stepLocks.delete(key);\n }\n }\n })();\n taskBox.task = task;\n stepLocks.set(key, task);\n return task;\n}\n\n/**\n * Helper function to delete all waits associated with a workflow run.\n * Called when a run reaches a terminal state.\n */\nasync function deleteAllWaitsForRun(\n basedir: string,\n runId: string\n): Promise<void> {\n const waitsDir = path.join(basedir, 'waits');\n const files = await listJSONFiles(waitsDir);\n\n for (const file of files) {\n // fileIds may contain tag suffixes (e.g., \"wrun_ABC-corrId.vitest-0\")\n // but startsWith still matches correctly since the tag is a suffix.\n if (file.startsWith(`${runId}-`)) {\n const waitPath = path.join(waitsDir, `${file}.json`);\n await deleteJSON(waitPath);\n }\n }\n}\n\n/**\n * Creates the events storage implementation using the filesystem.\n * Implements the Storage['events'] interface with create, list, and listByCorrelationId operations.\n */\nexport function createEventsStorage(\n basedir: string,\n tag?: string\n): Storage['events'] {\n return {\n async create(runId, data, params): Promise<EventResult> {\n // Validate request-supplied IDs before they're concatenated into\n // filesystem paths. This is the primary defense against path traversal\n // attacks where a client supplies runId / correlationId values like\n // \"../../../package\" to read or write files outside the storage root.\n // Run before taking the per-step mutex so malformed inputs fail fast.\n if (runId != null && runId !== '') {\n assertSafeEntityId('runId', runId);\n }\n if (\n 'correlationId' in data &&\n typeof data.correlationId === 'string' &&\n data.correlationId.length > 0\n ) {\n assertSafeEntityId('correlationId', data.correlationId);\n }\n\n // Step lifecycle events are serialized per-step via an in-process mutex\n // so that the \"check state, then write\" sequence in step_started /\n // step_completed / step_failed / step_retrying is atomic. step_created\n // is also serialized so duplicate-create races don't leave extra\n // step_created events in the log.\n const isStepEvent =\n data.eventType === 'step_created' ||\n data.eventType === 'step_started' ||\n data.eventType === 'step_completed' ||\n data.eventType === 'step_failed' ||\n data.eventType === 'step_retrying';\n if (isStepEvent && runId && data.correlationId) {\n const lockKey = tag\n ? `${runId}-${data.correlationId}.${tag}`\n : `${runId}-${data.correlationId}`;\n return withStepLock(lockKey, () => createImpl());\n }\n return createImpl();\n\n async function createImpl(): Promise<EventResult> {\n const eventId = `evnt_${monotonicUlid()}`;\n const now = new Date();\n\n // For run_created events, use client-provided runId or generate one server-side\n let effectiveRunId: string;\n if (data.eventType === 'run_created' && (!runId || runId === '')) {\n effectiveRunId = `wrun_${monotonicUlid()}`;\n } else if (!runId) {\n throw new Error('runId is required for non-run_created events');\n } else {\n effectiveRunId = runId;\n }\n\n // Validate client-provided runId timestamp is within acceptable threshold\n if (data.eventType === 'run_created' && runId && runId !== '') {\n const validationError = validateUlidTimestamp(\n effectiveRunId,\n 'wrun_'\n );\n if (validationError) {\n throw new WorkflowWorldError(validationError);\n }\n }\n\n // specVersion is always sent by the runtime, but we provide a fallback for safety\n const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;\n\n // Helper to check if run is in terminal state\n const isRunTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Helper to check if step is in terminal state\n const isStepTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Get current run state for validation (if not creating a new run)\n // Skip run validation for step_completed and step_retrying - they only operate\n // on running steps, and running steps are always allowed to modify regardless\n // of run state. This optimization saves filesystem reads per step event.\n let currentRun: WorkflowRun | null = null;\n const skipRunValidationEvents = ['step_completed', 'step_retrying'];\n if (\n data.eventType !== 'run_created' &&\n !skipRunValidationEvents.includes(data.eventType)\n ) {\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n\n // Resilient start: run_started on non-existent run with eventData\n // creates the run first, so the queue can bootstrap a run that\n // failed to create during start().\n if (\n data.eventType === 'run_started' &&\n !currentRun &&\n 'eventData' in data &&\n data.eventData\n ) {\n const runInputData = data.eventData as {\n deploymentId?: string;\n workflowName?: string;\n input?: any;\n executionContext?: Record<string, any>;\n };\n if (\n runInputData.deploymentId &&\n runInputData.workflowName &&\n runInputData.input !== undefined\n ) {\n // Atomically try to create the run entity. writeExclusive\n // uses O_CREAT|O_EXCL so only the first writer wins,\n // preventing a TOCTOU race where a concurrent run_created\n // from start() could overwrite a run that was already\n // transitioned to 'running'.\n const createdRun: WorkflowRun = {\n runId: effectiveRunId,\n deploymentId: runInputData.deploymentId,\n status: 'pending',\n workflowName: runInputData.workflowName,\n specVersion: effectiveSpecVersion,\n executionContext: runInputData.executionContext,\n input: runInputData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(createdRun, jsonReplacer)\n );\n\n if (created) {\n // We created the run — also write the run_created event.\n const runCreatedEventId = `evnt_${monotonicUlid()}`;\n const runCreatedEvent: Event = {\n eventType: 'run_created',\n runId: effectiveRunId,\n eventId: runCreatedEventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n eventData: {\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n },\n };\n const createdCompositeKey = `${effectiveRunId}-${runCreatedEventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', createdCompositeKey, tag),\n runCreatedEvent\n );\n currentRun = createdRun;\n } else {\n // Run already exists (concurrent run_created won the\n // race). Re-read it so downstream logic sees the real state.\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n }\n }\n }\n }\n\n // run_failed on a non-existent run is rejected to match the\n // postgres and vercel worlds, which both surface this as a\n // WorkflowRunNotFoundError rather than silently persisting an\n // event for a run that was never created.\n if (data.eventType === 'run_failed' && !currentRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n\n // ============================================================\n // VERSION COMPATIBILITY: Check run spec version\n // ============================================================\n // For events that have fetched the run, check version compatibility.\n // Skip for run_created (no existing run) and runtime events (step_completed, step_retrying).\n if (currentRun) {\n // Check if run requires a newer world version\n if (requiresNewerWorld(currentRun.specVersion)) {\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n SPEC_VERSION_CURRENT\n );\n }\n\n // Route to legacy handler for pre-event-sourcing runs\n if (isLegacySpecVersion(currentRun.specVersion)) {\n return handleLegacyEvent(\n basedir,\n effectiveRunId,\n data,\n currentRun,\n params\n );\n }\n }\n\n // ============================================================\n // VALIDATION: Terminal state and event ordering checks\n // ============================================================\n\n // Run terminal state validation\n if (currentRun && isRunTerminal(currentRun.status)) {\n const runTerminalEvents = [\n 'run_started',\n 'run_completed',\n 'run_failed',\n ];\n\n // Idempotent operation: run_cancelled on already cancelled run is allowed\n if (\n data.eventType === 'run_cancelled' &&\n currentRun.status === 'cancelled'\n ) {\n // Return existing state (idempotent)\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return {\n event: stripEventDataRefs(event, resolveData),\n run: currentRun,\n };\n }\n\n // For run_started on terminal runs, use RunExpiredError so the\n // runtime knows to exit without retrying.\n if (data.eventType === 'run_started') {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${currentRun.status}\"`\n );\n }\n\n // Other run state transitions are not allowed on terminal runs\n if (\n runTerminalEvents.includes(data.eventType) ||\n data.eventType === 'run_cancelled'\n ) {\n throw new EntityConflictError(\n `Cannot transition run from terminal state \"${currentRun.status}\"`\n );\n }\n\n // Creating new entities on terminal runs is not allowed\n if (\n data.eventType === 'step_created' ||\n data.eventType === 'hook_created' ||\n data.eventType === 'wait_created'\n ) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n\n // Step-related event validation (ordering and terminal state)\n // Store existingStep so we can reuse it later (avoid double read)\n let validatedStep: Step | null = null;\n const stepEvents = [\n 'step_started',\n 'step_completed',\n 'step_failed',\n 'step_retrying',\n ];\n if (stepEvents.includes(data.eventType) && data.correlationId) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n validatedStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n\n // Event ordering: step must exist before these events\n if (!validatedStep) {\n throw new WorkflowWorldError(\n `Step \"${data.correlationId}\" not found`\n );\n }\n\n // Step terminal state validation\n if (isStepTerminal(validatedStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${validatedStep.status}\"`\n );\n }\n\n // On terminal runs: only allow completing/failing in-progress steps\n if (currentRun && isRunTerminal(currentRun.status)) {\n if (validatedStep.status !== 'running') {\n throw new RunExpiredError(\n `Cannot modify non-running step on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n }\n\n // Hook-related event validation (ordering)\n const hookEventsRequiringExistence = ['hook_disposed', 'hook_received'];\n if (\n hookEventsRequiringExistence.includes(data.eventType) &&\n data.correlationId\n ) {\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n\n if (!existingHook) {\n throw new HookNotFoundError(data.correlationId);\n }\n }\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n // Strip eventData from run_started — it belongs on run_created only.\n if (data.eventType === 'run_started' && 'eventData' in event) {\n delete (event as any).eventData;\n }\n\n // Track entity created/updated for EventResult\n let run: WorkflowRun | undefined;\n let step: Step | undefined;\n let hook: Hook | undefined;\n let wait: Wait | undefined;\n\n // Create/update entity based on event type (event-sourced architecture)\n // Run lifecycle events\n if (data.eventType === 'run_created' && 'eventData' in data) {\n const runData = data.eventData as {\n deploymentId: string;\n workflowName: string;\n input: SerializedData;\n executionContext?: Record<string, any>;\n };\n run = {\n runId: effectiveRunId,\n deploymentId: runData.deploymentId,\n status: 'pending',\n workflowName: runData.workflowName,\n // Propagate specVersion from the event to the run entity\n specVersion: effectiveSpecVersion,\n executionContext: runData.executionContext,\n input: runData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n // Use writeExclusive (O_CREAT|O_EXCL) to atomically create the\n // run entity file. This prevents a TOCTOU race with the resilient\n // start path (run_started on non-existent run) that could result\n // in duplicate run_created events in the event log.\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(run, jsonReplacer, 2)\n );\n if (!created) {\n throw new EntityConflictError(\n `Workflow run \"${effectiveRunId}\" already exists`\n );\n }\n } else if (data.eventType === 'run_started') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // If already running, return the run without inserting a\n // duplicate event. This makes run_started idempotent for\n // concurrent invocations. We omit preloaded events here\n // because this is a rare race-condition path — the runtime\n // falls back to loadWorkflowRunEvents().\n if (currentRun.status === 'running') {\n return { run: currentRun };\n }\n\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n status: 'running',\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: currentRun.startedAt ?? now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'run_completed' && 'eventData' in data) {\n const completedData = data.eventData as { output?: any };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'completed',\n output: completedData.output,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_failed' && 'eventData' in data) {\n const failedData = data.eventData as {\n error: unknown;\n errorCode?: string;\n };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateRunError. We store it verbatim — consumers hydrate it\n // via hydrateRunError to reconstruct the original thrown value.\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'failed',\n output: undefined,\n error: failedData.error as Uint8Array,\n errorCode: failedData.errorCode,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_cancelled') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'cancelled',\n output: undefined,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (\n // Step lifecycle events\n data.eventType === 'step_created' &&\n 'eventData' in data\n ) {\n // step_created: Creates step entity with status 'pending', attempt=0, createdAt set.\n // Two concurrent invocations with identical correlationIds (e.g. the\n // snapshot runtime's deterministic correlationIds across replays)\n // must be deduped — otherwise both writes succeed and the event log\n // ends up with duplicate step_created entries. The outer\n // withStepLock mutex serializes within a single process; this\n // O_CREAT|O_EXCL constraint file additionally protects against\n // cross-process races (two pnpm workers, redelivered queue\n // messages, etc.). The loser throws EntityConflictError so the\n // runtime's existing catch path can swallow it and avoid\n // double-queuing the step.\n const stepCreatedLockName = tag\n ? `${effectiveRunId}-${data.correlationId}.created.${tag}`\n : `${effectiveRunId}-${data.correlationId}.created`;\n const stepCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n stepCreatedLockName\n );\n const stepCreatedClaimed = await writeExclusive(\n stepCreatedLockPath,\n ''\n );\n if (!stepCreatedClaimed) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`\n );\n }\n const stepData = data.eventData as {\n stepName: string;\n input: any;\n };\n step = {\n runId: effectiveRunId,\n stepId: data.correlationId,\n stepName: stepData.stepName,\n status: 'pending',\n input: stepData.input,\n output: undefined,\n error: undefined,\n attempt: 0,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n // Propagate specVersion from the event to the step entity\n specVersion: effectiveSpecVersion,\n };\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step\n );\n } else if (data.eventType === 'step_started') {\n // step_started: Increments attempt, sets status to 'running'\n // Sets startedAt only on the first start (not updated on retries)\n // Reuse validatedStep from validation (already read above)\n if (validatedStep) {\n // Check if retryAfter timestamp hasn't been reached yet\n if (\n validatedStep.retryAfter &&\n validatedStep.retryAfter.getTime() > Date.now()\n ) {\n throw new TooEarlyError(\n `Cannot start step \"${data.correlationId}\": retryAfter timestamp has not been reached yet`,\n {\n retryAfter: Math.ceil(\n (validatedStep.retryAfter.getTime() - Date.now()) / 1000\n ),\n }\n );\n }\n\n // Best-effort guard: re-read the step entity to check if it\n // reached terminal state between the validation read and now.\n // This narrows the TOCTOU window but does not fully eliminate it\n // (the local world is single-process / dev-only; the postgres\n // world uses SQL-level atomic guards for production).\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const freshStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n if (freshStep && isStepTerminal(freshStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${freshStep.status}\"`\n );\n }\n\n step = {\n ...validatedStep,\n status: 'running',\n // Only set startedAt on the first start\n startedAt: validatedStep.startedAt ?? now,\n // Increment attempt counter on every start\n attempt: validatedStep.attempt + 1,\n // Clear retryAfter now that the step has started\n retryAfter: undefined,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_completed' && 'eventData' in data) {\n // step_completed: Terminal state with output\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same step (TOCTOU race).\n const completedData = data.eventData as { result: any };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n step = {\n ...validatedStep,\n status: 'completed',\n output: completedData.result,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_failed' && 'eventData' in data) {\n // step_failed: Terminal state with error\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both failing the same step (TOCTOU race).\n const failedData = data.eventData as {\n error: unknown;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateStepError. We store it verbatim — consumers hydrate it\n // via hydrateStepError to reconstruct the original thrown value.\n step = {\n ...validatedStep,\n status: 'failed',\n error: failedData.error as Uint8Array,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_retrying' && 'eventData' in data) {\n // step_retrying: Sets status back to 'pending', records error\n // Reuse validatedStep from validation (already read above)\n const retryData = data.eventData as {\n error: unknown;\n retryAfter?: Date;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n step = {\n ...validatedStep,\n status: 'pending',\n error: retryData.error as Uint8Array,\n retryAfter: retryData.retryAfter,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (\n // Hook lifecycle events\n data.eventType === 'hook_created' &&\n 'eventData' in data\n ) {\n const hookData = data.eventData as {\n token: string;\n metadata?: any;\n isWebhook?: boolean;\n isSystem?: boolean;\n };\n\n // Atomically claim the token using an exclusive-create constraint file.\n // This avoids the TOCTOU race of the previous read-all-then-check approach.\n const constraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(hookData.token)}.json`\n );\n const tokenClaimed = await writeExclusive(\n constraintPath,\n JSON.stringify({\n token: hookData.token,\n hookId: data.correlationId,\n runId: effectiveRunId,\n })\n );\n\n if (!tokenClaimed) {\n const existingClaim = await readHookTokenClaim(constraintPath);\n\n // Create hook_conflict event instead of hook_created\n // This allows the workflow to continue and fail gracefully when the hook is awaited\n const conflictEvent: Event = {\n eventType: 'hook_conflict',\n correlationId: data.correlationId,\n eventData: {\n token: hookData.token,\n ...(existingClaim\n ? { conflictingRunId: existingClaim.runId }\n : {}),\n },\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n\n // Store the conflict event\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n conflictEvent\n );\n\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(\n conflictEvent,\n resolveData\n );\n\n // Return EventResult with conflict event (no hook entity created)\n return {\n event: filteredEvent,\n run,\n step,\n hook: undefined,\n };\n }\n\n hook = {\n runId: effectiveRunId,\n hookId: data.correlationId,\n token: hookData.token,\n metadata: hookData.metadata,\n ownerId: 'local-owner',\n projectId: 'local-project',\n environment: 'local',\n createdAt: now,\n // Propagate specVersion from the event to the hook entity\n specVersion: effectiveSpecVersion,\n isWebhook: hookData.isWebhook ?? false,\n isSystem: hookData.isSystem ?? false,\n };\n await writeJSON(\n taggedPath(basedir, 'hooks', data.correlationId, tag),\n hook\n );\n } else if (data.eventType === 'hook_disposed') {\n // hook_disposed: Deletes hook entity, rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both disposing the same hook (TOCTOU race).\n const hookLockName = tag\n ? `${data.correlationId}.disposed.${tag}`\n : `${data.correlationId}.disposed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'hooks',\n hookLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`\n );\n }\n // Read the hook to get its token before deleting\n const hookPath = taggedPath(\n basedir,\n 'hooks',\n data.correlationId,\n tag\n );\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n if (existingHook) {\n // Delete the token constraint file to free up the token for reuse\n const disposedConstraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(existingHook.token)}.json`\n );\n await deleteJSON(disposedConstraintPath);\n }\n await deleteJSON(hookPath);\n } else if (data.eventType === 'wait_created' && 'eventData' in data) {\n // wait_created: Creates wait entity with status 'waiting'.\n // Atomic claim on a per-(runId, correlationId) constraint file\n // ensures duplicate wait_created from concurrent invocations\n // surfaces as EntityConflictError (replaces a prior TOCTOU\n // read-then-check that could let both writers through).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitCreatedLockName = tag\n ? `${waitCompositeKey}.created.${tag}`\n : `${waitCompositeKey}.created`;\n const waitCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitCreatedLockName\n );\n const waitCreatedClaimed = await writeExclusive(\n waitCreatedLockPath,\n ''\n );\n if (!waitCreatedClaimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already exists`\n );\n }\n const waitData = data.eventData as {\n resumeAt?: Date;\n };\n wait = {\n waitId: waitCompositeKey,\n runId: effectiveRunId,\n status: 'waiting',\n resumeAt: waitData.resumeAt,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n specVersion: effectiveSpecVersion,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait\n );\n } else if (data.eventType === 'wait_completed') {\n // wait_completed: Transitions wait to 'completed', rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same wait (TOCTOU race).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitLockName = tag\n ? `${waitCompositeKey}.completed.${tag}`\n : `${waitCompositeKey}.completed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already completed`\n );\n }\n const existingWait = await readJSONWithFallback(\n basedir,\n 'waits',\n waitCompositeKey,\n WaitSchema,\n tag\n );\n if (!existingWait) {\n // Clean up the lock file we just claimed — the wait doesn't exist\n await fs.unlink(lockPath).catch(() => {});\n throw new WorkflowWorldError(\n `Wait \"${data.correlationId}\" not found`\n );\n }\n // The lock file (writeExclusive above) already prevents concurrent\n // completions — no additional status check needed.\n wait = {\n ...existingWait,\n status: 'completed',\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait,\n { overwrite: true }\n );\n }\n // Note: hook_received events are stored in the event log but don't\n // modify the Hook entity (which doesn't have a payload field)\n\n // Store event using composite key {runId}-{eventId}\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(event, resolveData);\n\n // For run_started: include all events so the runtime can skip\n // the initial events.list call and reduce TTFB.\n let events: Event[] | undefined;\n if (data.eventType === 'run_started' && run) {\n const allEvents = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${effectiveRunId}-`,\n sortOrder: 'asc',\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (e) => e.eventId,\n });\n events = allEvents.data;\n }\n\n // Return EventResult with event and any created/updated entity\n return {\n event: filteredEvent,\n run,\n step,\n hook,\n wait,\n events,\n };\n } // end createImpl\n },\n\n async get(runId, eventId, params) {\n assertSafeEntityId('runId', runId);\n assertSafeEntityId('eventId', eventId);\n const compositeKey = `${runId}-${eventId}`;\n const event = await readJSONWithFallback(\n basedir,\n 'events',\n compositeKey,\n EventSchema,\n tag\n );\n if (!event) {\n throw new Error(`Event ${eventId} in run ${runId} not found`);\n }\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return stripEventDataRefs(event, resolveData);\n },\n\n async list(params) {\n const { runId } = params;\n assertSafeEntityId('runId', runId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${runId}-`,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n\n async listByCorrelationId(params) {\n const correlationId = params.correlationId;\n assertSafeEntityId('correlationId', correlationId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n // No filePrefix - search all events\n filter: (event) => event.correlationId === correlationId,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"filters.js","sourceRoot":"","sources":["../../src/storage/filters.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAkBrD,MAAM,UAAU,aAAa,CAC3B,GAAgB,EAChB,WAA2B;IAE3B,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;QAC3B,OAAO;YACL,GAAG,GAAG;YACN,KAAK,EAAE,SAAS;YAChB,MAAM,EAAE,SAAS;SACQ,CAAC;IAC9B,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAeD,MAAM,UAAU,cAAc,CAC5B,IAAU,EACV,WAA2B;IAE3B,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;QAC3B,OAAO;YACL,GAAG,IAAI;YACP,KAAK,EAAE,SAAS;YAChB,MAAM,EAAE,SAAS;SACC,CAAC;IACvB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,IAAU,EAAE,WAA2B;IACpE,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;QAC3B,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,IAAW,CAAC;QACrD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n Hook,\n Step,\n StepWithoutData,\n WorkflowRun,\n WorkflowRunWithoutData,\n} from '@workflow/world';\n\nexport { stripEventDataRefs } from '@workflow/world';\n\n/**\n * Filter run data based on resolveData setting.\n * When resolveData is 'none', strips input/output to reduce payload size.\n */\nexport function filterRunData(\n run: WorkflowRun,\n resolveData: 'none'\n): WorkflowRunWithoutData;\nexport function filterRunData(\n run: WorkflowRun,\n resolveData: 'all'\n): WorkflowRun;\nexport function filterRunData(\n run: WorkflowRun,\n resolveData: 'none' | 'all'\n): WorkflowRun | WorkflowRunWithoutData;\nexport function filterRunData(\n run: WorkflowRun,\n resolveData: 'none' | 'all'\n): WorkflowRun | WorkflowRunWithoutData {\n if (resolveData === 'none') {\n return {\n ...run,\n input: undefined,\n output: undefined,\n } as WorkflowRunWithoutData;\n }\n return run;\n}\n\n/**\n * Filter step data based on resolveData setting.\n * When resolveData is 'none', strips input/output to reduce payload size.\n */\nexport function filterStepData(\n step: Step,\n resolveData: 'none'\n): StepWithoutData;\nexport function filterStepData(step: Step, resolveData: 'all'): Step;\nexport function filterStepData(\n step: Step,\n resolveData: 'none' | 'all'\n): Step | StepWithoutData;\nexport function filterStepData(\n step: Step,\n resolveData: 'none' | 'all'\n): Step | StepWithoutData {\n if (resolveData === 'none') {\n return {\n ...step,\n input: undefined,\n output: undefined,\n } as StepWithoutData;\n }\n return step;\n}\n\n/**\n * Filter hook data based on resolveData setting.\n * When resolveData is 'none', strips metadata to reduce payload size.\n */\nexport function filterHookData(hook: Hook, resolveData: 'none' | 'all'): Hook {\n if (resolveData === 'none') {\n const { metadata: _metadata, ...rest } = hook as any;\n return rest;\n }\n return hook;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/storage/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE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,SAAS,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;IACrE,MAAM,IAAI,GAAG,EAAE,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;IAC1C,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC,CAAC","sourcesContent":["import { createHash } from 'node:crypto';\nimport { monotonicFactory } from 'ulid';\nimport { stripTag, ulidToDate } from '../fs.js';\n\n/**\n * Hash a hook token to produce a filesystem-safe constraint filename.\n */\nexport function hashToken(token: string): string {\n return createHash('sha256').update(token).digest('hex');\n}\n\n/**\n * Create a monotonic ULID factory that ensures ULIDs are always increasing\n * even when generated within the same millisecond.\n */\nexport const monotonicUlid = monotonicFactory(() => Math.random());\n\n/**\n * Creates a function to extract createdAt date from a filename based on ULID.\n * Used for efficient pagination without reading file contents.\n *\n * @param idPrefix - The prefix to strip from filenames (e.g., 'wrun', 'evnt', 'step')\n * @returns A function that extracts Date from filename, or null if not extractable\n */\nexport const getObjectCreatedAt =\n (idPrefix: string) =>\n (filename: string): Date | null => {\n // Strip tag suffix before ULID extraction\n // e.g., \"wrun_ABC.vitest-0.json\" → \"wrun_ABC.json\"\n const cleanName = stripTag(filename.replace(/\\.json$/, '')) + '.json';\n\n const replaceRegex = new RegExp(`^${idPrefix}_`, 'g');\n const dashIndex = cleanName.indexOf('-');\n\n if (dashIndex === -1) {\n // No dash - extract ULID from the filename (e.g., wrun_ULID.json, evnt_ULID.json)\n const ulid = cleanName.replace(/\\.json$/, '').replace(replaceRegex, '');\n return ulidToDate(ulid);\n }\n\n // For composite keys like {runId}-{stepId}, extract from the appropriate part\n if (idPrefix === 'step') {\n // Steps use sequential IDs (step_0, step_1, etc.) - no timestamp in filename.\n // Return null to skip filename-based optimization and defer to JSON-based filtering.\n return null;\n }\n\n // For events: wrun_ULID-evnt_ULID.json - extract from the eventId part\n const id = cleanName.substring(dashIndex + 1).replace(/\\.json$/, '');\n const ulid = id.replace(replaceRegex, '');\n return ulidToDate(ulid);\n };\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"hooks-storage.js","sourceRoot":"","sources":["../../src/storage/hooks-storage.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAQrD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,wBAAwB,EACxB,QAAQ,EACR,oBAAoB,GACrB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAe,EACf,GAAY;IAEZ,sEAAsE;IACtE,KAAK,UAAU,eAAe,CAAC,KAAa;QAC1C,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC7C,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,QAAQ,CAAC,CAAC;QAE5C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,IAAI,OAAO,CAAC,CAAC;YACrD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;YAClD,IAAI,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,KAAK,EAAE,CAAC;gBACjC,OAAO,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,IAAI,IAAI,EAAE,CAAC;YACxD,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAA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,QAAQ,EACR,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAChC,CAAC;YACF,MAAM,UAAU,CAAC,cAAc,CAAC,CAAC;YACjC,MAAM,UAAU,CAAC,QAAQ,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import path from 'node:path';\nimport { HookNotFoundError } from '@workflow/errors';\nimport type {\n GetHookParams,\n Hook,\n ListHooksParams,\n PaginatedResponse,\n Storage,\n} from '@workflow/world';\nimport { HookSchema } from '@workflow/world';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n deleteJSON,\n listJSONFiles,\n paginatedFileSystemQuery,\n readJSON,\n readJSONWithFallback,\n} from '../fs.js';\nimport { filterHookData } from './filters.js';\nimport { hashToken } from './helpers.js';\n\n/**\n * Creates a hooks storage implementation using the filesystem.\n * Implements the Storage['hooks'] interface with hook CRUD operations.\n */\nexport function createHooksStorage(\n basedir: string,\n tag?: string\n): Storage['hooks'] {\n // Helper function to find a hook by token (shared between getByToken)\n async function findHookByToken(token: string): Promise<Hook | null> {\n const hooksDir = path.join(basedir, 'hooks');\n const files = await listJSONFiles(hooksDir);\n\n for (const file of files) {\n const hookPath = path.join(hooksDir, `${file}.json`);\n const hook = await readJSON(hookPath, HookSchema);\n if (hook && hook.token === token) {\n return { ...hook, isWebhook: hook.isWebhook ?? true };\n }\n }\n\n return null;\n }\n\n async function get(hookId: string, params?: GetHookParams): Promise<Hook> {\n assertSafeEntityId('hookId', hookId);\n const hook = await readJSONWithFallback(\n basedir,\n 'hooks',\n hookId,\n HookSchema,\n tag\n );\n if (!hook) {\n throw new HookNotFoundError(hookId);\n }\n const resolveData = params?.resolveData || DEFAULT_RESOLVE_DATA_OPTION;\n return filterHookData(\n { ...hook, isWebhook: hook.isWebhook ?? true },\n resolveData\n );\n }\n\n async function getByToken(token: string): Promise<Hook> {\n const hook = await findHookByToken(token);\n if (!hook) {\n throw new HookNotFoundError(token);\n }\n return hook;\n }\n\n async function list(\n params: ListHooksParams\n ): Promise<PaginatedResponse<Hook>> {\n const hooksDir = path.join(basedir, 'hooks');\n const resolveData = params.resolveData || DEFAULT_RESOLVE_DATA_OPTION;\n\n const result = await paginatedFileSystemQuery({\n directory: hooksDir,\n schema: HookSchema,\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n filePrefix: undefined, // Hooks don't have ULIDs, so we can't optimize by filename\n filter: (hook) => {\n // Filter by runId if provided\n if (params.runId && hook.runId !== params.runId) {\n return false;\n }\n return true;\n },\n getCreatedAt: () => {\n // Hook files don't have ULID timestamps in filename, so return null\n // to skip the filename-based optimization and defer to JSON-based\n // cursor filtering which uses the actual createdAt from the file.\n return null;\n },\n getId: (hook) => hook.hookId,\n });\n\n // Transform the data after pagination\n return {\n ...result,\n data: result.data.map((hook) => filterHookData(hook, resolveData)),\n };\n }\n\n return { get, getByToken, list };\n}\n\n/**\n * Helper function to delete all hooks associated with a workflow run.\n * Called when a run reaches a terminal state.\n */\nexport async function deleteAllHooksForRun(\n basedir: string,\n runId: string\n): Promise<void> {\n const hooksDir = path.join(basedir, 'hooks');\n const files = await listJSONFiles(hooksDir);\n\n for (const file of files) {\n const hookPath = path.join(hooksDir, `${file}.json`);\n const hook = await readJSON(hookPath, HookSchema);\n if (hook && hook.runId === runId) {\n // Delete the token constraint file to free up the token\n const constraintPath = path.join(\n hooksDir,\n 'tokens',\n `${hashToken(hook.token)}.json`\n );\n await deleteJSON(constraintPath);\n await deleteJSON(hookPath);\n }\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/storage/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAyB,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AASxD;;;;;;;;GAQG;AACH,MAAM,UAAU,aAAa,CAAC,OAAe,EAAE,GAAY;IACzD,qCAAqC;IACrC,MAAM,IAAI,GAAG,iBAAiB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IAC7C,MAAM,KAAK,GAAG,kBAAkB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IAC/C,MAAM,MAAM,GAAG,mBAAmB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IACjD,MAAM,KAAK,GAAG,kBAAkB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;IAE/C,8CAA8C;IAC9C,+DAA+D;IAC/D,OAAO;QACL,IAAI,EAAE,gBAAgB,CAAC,YAAY,EAAE,IAAI,CAAC;QAC1C,KAAK,EAAE,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC;QAC7C,MAAM,EAAE,gBAAgB,CAAC,cAAc,EAAE,MAAM,CAAC;QAChD,KAAK,EAAE,gBAAgB,CAAC,aAAa,EAAE,KAAK,CAAC;KAC9C,CAAC;AACJ,CAAC","sourcesContent":["import type { Storage } from '@workflow/world';\nimport { instrumentObject } from '../instrumentObject.js';\nimport { createEventsStorage } from './events-storage.js';\nimport { createHooksStorage } from './hooks-storage.js';\nimport { createRunsStorage, type LocalRunsStorage } from './runs-storage.js';\nimport { createStepsStorage } from './steps-storage.js';\n\n/**\n * Storage shape used inside world-local: identical to `Storage`, but `runs`\n * exposes the internal `fileIdFilter` option on `list()`. Structurally\n * assignable to `Storage` at public boundaries (e.g., `reenqueueActiveRuns`).\n */\nexport type LocalStorage = Omit<Storage, 'runs'> & { runs: LocalRunsStorage };\n\n/**\n * Creates a complete storage implementation using the filesystem.\n * This is the main entry point that composes all storage implementations.\n *\n * All storage methods are instrumented with tracing spans for observability.\n *\n * @param basedir - The base directory for storing workflow data\n * @returns A complete Storage implementation with tracing\n */\nexport function createStorage(basedir: string, tag?: string): LocalStorage {\n // Create raw storage implementations\n const runs = createRunsStorage(basedir, tag);\n const steps = createStepsStorage(basedir, tag);\n const events = createEventsStorage(basedir, tag);\n const hooks = createHooksStorage(basedir, tag);\n\n // Instrument all storage methods with tracing\n // NOTE: Span names are lowercase per OTEL semantic conventions\n return {\n runs: instrumentObject('world.runs', runs),\n steps: instrumentObject('world.steps', steps),\n events: instrumentObject('world.events', events),\n hooks: instrumentObject('world.hooks', hooks),\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"legacy.js","sourceRoot":"","sources":["../../src/storage/legacy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAAe,EACf,KAAa,EACb,IAAS,EACT,UAAuB,EACvB,MAAyC;IAEzC,yEAAyE;IACzE,oEAAoE;IACpE,0EAA0E;IAC1E,QAAQ;IACR,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAEnC,MAAM,WAAW,GAAG,MAAM,EAAE,WAAW,IAAI,2BAA2B,CAAC;IAEvE,QAAQ,IAAI,CAAC,SAAS,EAAE,CAAC;QACvB,KAAK,eAAe,CAAC,CAAC,CAAC;YACrB,+DAA+D;YAC/D,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;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;YACF,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,OAAO,EAAE,CAAC;YAC3C,MAAM,SAAS,GAAG,iBAAiB,CACjC,OAAO,EACP,QAAQ,EACR,GAAG,YAAY,OAAO,CACvB,CAAC;YACF,MAAM,SAAS,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;YAClC,OAAO,EAAE,KAAK,EAAE,kBAAkB,CAAC,KAAK,EAAE,WAAW,CAAC,EAAE,CAAC;QAC3D,CAAC;QAED;YACE,MAAM,IAAI,KAAK,CACb,eAAe,IAAI,CAAC,SAAS,kCAAkC;gBAC7D,iBAAiB,UAAU,CAAC,WAAW,IAAI,WAAW,KAAK;gBAC3D,oCAAoC,CACvC,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["import type { Event, EventResult, WorkflowRun } from '@workflow/world';\nimport { SPEC_VERSION_CURRENT } from '@workflow/world';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport { assertSafeEntityId, resolveWithinBase, writeJSON } from '../fs.js';\nimport { filterRunData, stripEventDataRefs } from './filters.js';\nimport { monotonicUlid } from './helpers.js';\nimport { deleteAllHooksForRun } from './hooks-storage.js';\n\n/**\n * Handle events for legacy runs (pre-event-sourcing, specVersion < 2).\n * Legacy runs use different behavior:\n * - run_cancelled: Skip event storage, directly update run\n * - wait_completed: Store event only (no entity mutation)\n * - hook_received: Store event only (hooks exist via old system, no entity mutation)\n * - Other events: Throw error (not supported for legacy runs)\n */\nexport async function handleLegacyEvent(\n basedir: string,\n runId: string,\n data: any,\n currentRun: WorkflowRun,\n params?: { resolveData?: 'none' | 'all' }\n): Promise<EventResult> {\n // Defense in depth: events.create already validates runId before routing\n // here, but handleLegacyEvent is exported and its signature doesn't\n // document that invariant. Validating locally keeps the guarantee in this\n // file.\n assertSafeEntityId('runId', runId);\n\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n\n switch (data.eventType) {\n case 'run_cancelled': {\n // Legacy: Skip event storage, directly update run to cancelled\n const now = new Date();\n const run: WorkflowRun = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'cancelled',\n output: undefined,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n const runPath = resolveWithinBase(basedir, 'runs', `${runId}.json`);\n await writeJSON(runPath, run, { overwrite: true });\n await deleteAllHooksForRun(basedir, runId);\n // Return without event (legacy behavior skips event storage)\n // Type assertion: EventResult expects WorkflowRun, filterRunData may return WorkflowRunWithoutData\n return {\n event: undefined,\n run: filterRunData(run, resolveData) as WorkflowRun,\n };\n }\n\n case 'wait_completed':\n case 'hook_received': {\n // Legacy: Store event only (no entity mutation)\n // - wait_completed: for replay purposes\n // - hook_received: hooks exist via old system, just record the event\n const eventId = `evnt_${monotonicUlid()}`;\n const now = new Date();\n const event: Event = {\n ...data,\n runId,\n eventId,\n createdAt: now,\n specVersion: SPEC_VERSION_CURRENT,\n };\n const compositeKey = `${runId}-${eventId}`;\n const eventPath = resolveWithinBase(\n basedir,\n 'events',\n `${compositeKey}.json`\n );\n await writeJSON(eventPath, event);\n return { event: stripEventDataRefs(event, resolveData) };\n }\n\n default:\n throw new Error(\n `Event type '${data.eventType}' not supported for legacy runs ` +\n `(specVersion: ${currentRun.specVersion || 'undefined'}). ` +\n `Please upgrade 'workflow' package.`\n );\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runs-storage.js","sourceRoot":"","sources":["../../src/storage/runs-storage.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAQ5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,2BAA2B,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MAAM,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC;wBACnD,OAAO,KAAK,CAAC;oBACf,CAAC;oBACD,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,IAAI,MAAM;gBAClD,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK;gBAChC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM;gBAClC,YAAY,EAAE,kBAAkB,CAAC,MAAM,CAAC;gBACxC,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK;aAC1B,CAAC,CAAC;YAEH,gEAAgE;YAChE,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO;oBACL,GAAG,MAAM;oBACT,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;wBAC9B,GAAG,GAAG;wBACN,KAAK,EAAE,SAAS;wBAChB,MAAM,EAAE,SAAS;qBAClB,CAAC,CAA6B;iBAChC,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC,CAA6B;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import path from 'node:path';\nimport { WorkflowRunNotFoundError } from '@workflow/errors';\nimport type {\n ListWorkflowRunsParams,\n PaginatedResponse,\n Storage,\n WorkflowRun,\n WorkflowRunWithoutData,\n} from '@workflow/world';\nimport { WorkflowRunSchema } from '@workflow/world';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n paginatedFileSystemQuery,\n readJSONWithFallback,\n} from '../fs.js';\nimport { filterRunData } from './filters.js';\nimport { getObjectCreatedAt } from './helpers.js';\n\n/**\n * Internal extension of `ListWorkflowRunsParams` that adds a `fileIdFilter`\n * for scoping queries by raw filename (e.g., by tag suffix). Kept out of the\n * public `Storage['runs']['list']` surface — consumers of `@workflow/world`\n * must not see this option.\n */\nexport interface LocalListWorkflowRunsParams extends ListWorkflowRunsParams {\n fileIdFilter?: (fileId: string) => boolean;\n}\n\nexport interface LocalRunsStorage {\n get: Storage['runs']['get'];\n list: {\n (\n params: LocalListWorkflowRunsParams & { resolveData: 'none' }\n ): Promise<PaginatedResponse<WorkflowRunWithoutData>>;\n (\n params?: LocalListWorkflowRunsParams & { resolveData?: 'all' }\n ): Promise<PaginatedResponse<WorkflowRun>>;\n (\n params?: LocalListWorkflowRunsParams\n ): Promise<PaginatedResponse<WorkflowRun | WorkflowRunWithoutData>>;\n };\n}\n\n/**\n * Creates the runs storage implementation using the filesystem.\n * Implements the Storage['runs'] interface with get and list operations,\n * plus an internal `fileIdFilter` on `list` for tag-scoped recovery queries.\n */\nexport function createRunsStorage(\n basedir: string,\n tag?: string\n): LocalRunsStorage {\n return {\n get: (async (id: string, params?: any) => {\n assertSafeEntityId('runId', id);\n const run = await readJSONWithFallback(\n basedir,\n 'runs',\n id,\n WorkflowRunSchema,\n tag\n );\n if (!run) {\n throw new WorkflowRunNotFoundError(id);\n }\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return filterRunData(run, resolveData);\n }) as Storage['runs']['get'],\n\n list: (async (params?: LocalListWorkflowRunsParams) => {\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'runs'),\n schema: WorkflowRunSchema,\n fileIdFilter: params?.fileIdFilter,\n filter: (run) => {\n if (\n params?.workflowName &&\n run.workflowName !== params.workflowName\n ) {\n return false;\n }\n if (params?.status && run.status !== params.status) {\n return false;\n }\n return true;\n },\n sortOrder: params?.pagination?.sortOrder ?? 'desc',\n limit: params?.pagination?.limit,\n cursor: params?.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('wrun'),\n getId: (run) => run.runId,\n });\n\n // If resolveData is \"none\", replace input/output with undefined\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((run) => ({\n ...run,\n input: undefined,\n output: undefined,\n })) as WorkflowRunWithoutData[],\n };\n }\n\n return result;\n }) as LocalRunsStorage['list'],\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"steps-storage.js","sourceRoot":"","sources":["../../src/storage/steps-storage.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAElD;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAe,EACf,GAAY;IAEZ,OAAO;QACL,GAAG,EAAE,CAAC,KAAK,EAAE,KAAa,EAAE,MAAc,EAAE,MAAY,EAAE,EAAE;YAC1D,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YACnC,kBAAkB,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;YACrC,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,MAAM,EAAE,CAAC;YAC1C,MAAM,IAAI,GAAG,MAAM,oBAAoB,CACrC,OAAO,EACP,OAAO,EACP,YAAY,EACZ,UAAU,EACV,GAAG,CACJ,CAAC;YACF,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,MAAM,IAAI,KAAK,CAAC,QAAQ,MAAM,WAAW,KAAK,YAAY,CAAC,CAAC;YAC9D,CAAC;YACD,MAAM,WAAW,GAAG,MAAM,EAAE,WAAW,IAAI,2BAA2B,CAAC;YACvE,OAAO,cAAc,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QAC3C,CAAC,CAA4B;QAE7B,IAAI,EAAE,CAAC,KAAK,EAAE,MAAW,EAAE,EAAE;YAC3B,kBAAkB,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;YAC1C,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,IAAI,2BAA2B,CAAC;YACtE,MAAM,MAAM,GAAG,MAAM,wBAAwB,CAAC;gBAC5C,SAAS,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC;gBACtC,MAAM,EAAE,UAAU;gBAClB,UAAU,EAAE,GAAG,MAAM,CAAC,KAAK,GAAG;gBAC9B,SAAS,EAAE,MAAM,CAAC,UAAU,EAAE,SAAS,IAAI,MAAM;gBACjD,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK;gBAC/B,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM;gBACjC,YAAY,EAAE,kBAAkB,CAAC,MAAM,CAAC;gBACxC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM;aAC7B,CAAC,CAAC;YAEH,gEAAgE;YAChE,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO;oBACL,GAAG,MAAM;oBACT,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;wBAC/B,GAAG,IAAI;wBACP,KAAK,EAAE,SAAS;wBAChB,MAAM,EAAE,SAAS;qBAClB,CAAC,CAAsB;iBACzB,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC,CAA6B;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import path from 'node:path';\nimport type { StepWithoutData, Storage } from '@workflow/world';\nimport { StepSchema } from '@workflow/world';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n paginatedFileSystemQuery,\n readJSONWithFallback,\n} from '../fs.js';\nimport { filterStepData } from './filters.js';\nimport { getObjectCreatedAt } from './helpers.js';\n\n/**\n * Creates the steps storage implementation using the filesystem.\n * Implements the Storage['steps'] interface with get and list operations.\n */\nexport function createStepsStorage(\n basedir: string,\n tag?: string\n): Storage['steps'] {\n return {\n get: (async (runId: string, stepId: string, params?: any) => {\n assertSafeEntityId('runId', runId);\n assertSafeEntityId('stepId', stepId);\n const compositeKey = `${runId}-${stepId}`;\n const step = await readJSONWithFallback(\n basedir,\n 'steps',\n compositeKey,\n StepSchema,\n tag\n );\n if (!step) {\n throw new Error(`Step ${stepId} in run ${runId} not found`);\n }\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return filterStepData(step, resolveData);\n }) as Storage['steps']['get'],\n\n list: (async (params: any) => {\n assertSafeEntityId('runId', params.runId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'steps'),\n schema: StepSchema,\n filePrefix: `${params.runId}-`,\n sortOrder: params.pagination?.sortOrder ?? 'desc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('step'),\n getId: (step) => step.stepId,\n });\n\n // If resolveData is \"none\", replace input/output with undefined\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((step) => ({\n ...step,\n input: undefined,\n output: undefined,\n })) as StepWithoutData[],\n };\n }\n\n return result;\n }) as Storage['steps']['list'],\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage.js","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,oDAAoD;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC","sourcesContent":["/**\n * Filesystem-based storage implementation for workflow data.\n *\n * This module provides a complete Storage implementation that persists\n * workflow runs, steps, events, and hooks to the local filesystem.\n *\n * @module\n */\n\n// Re-export from the modular storage implementation\nexport { createStorage } from './storage/index.js';\n"]}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CAAC;4BACH,CAAC;4BAAC,OAAO,GAAY,EAAE,CAAC;gCACtB,qEAAqE;gCACrE,kDAAkD;gCAClD,IAAI,CAAC,CAAC,GAAG,YAAY,KAAK,IAAI,MAAM,IAAI,GAAG,CAAC,EAAE,CAAC;oCAC7C,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,GAAG,CAAC,CAAC;gCAChE,CAAC;4BACH,CAAC;oCAAS,CAAC;gCACT,SAAS,GAAG,KAAK,CAAC;4BACpB,CAAC;wBACH,CAAC,EAAE,GAAG,CAAC,CAAC;oBACV,CAAC;oBAED,MAAM;wBACJ,eAAe,EAAE,CAAC;wBAClB,IAAI,YAAY,EAAE,CAAC;4BACjB,aAAa,CAAC,YAAY,CAAC,CAAC;4BAC5B,YAAY,GAAG,IAAI,CAAC;wBACtB,CAAC;oBACH,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;SACF;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { EventEmitter } from 'node:events';\nimport path from 'node:path';\nimport type {\n GetChunksOptions,\n StreamChunksResponse,\n Streamer,\n StreamInfoResponse,\n} from '@workflow/world';\nimport { monotonicFactory } from 'ulid';\nimport { z } from 'zod';\nimport {\n assertSafeEntityId,\n listFilesByExtension,\n readBuffer,\n readJSONWithFallback,\n taggedPath,\n write,\n writeJSON,\n} from './fs.js';\n\n// Create a monotonic ULID factory that ensures ULIDs are always increasing\n// even when generated within the same millisecond\nconst monotonicUlid = monotonicFactory(() => Math.random());\n\n// Schema for the run-to-streams mapping file\nconst RunStreamsSchema = z.object({\n streams: z.array(z.string()),\n});\n\n/**\n * A chunk consists of a boolean `eof` indicating if it's the last chunk,\n * and a `chunk` which is a Buffer of data.\n * The serialized format is:\n * - 1 byte for `eof` (0 or 1)\n * - and the rest is the chunk data.\n */\nexport interface Chunk {\n eof: boolean;\n chunk: Buffer;\n}\n\nexport function serializeChunk(chunk: Chunk) {\n const eofByte = Buffer.from([chunk.eof ? 1 : 0]);\n return Buffer.concat([eofByte, chunk.chunk]);\n}\n\n/** Check only the EOF flag byte without copying chunk payload. */\nexport function isEofChunk(serialized: Buffer): boolean {\n return serialized[0] === 1;\n}\n\nexport function deserializeChunk(serialized: Buffer) {\n const eof = serialized[0] === 1;\n // Create a copy instead of a view to prevent ArrayBuffer detachment\n const chunk = Buffer.from(serialized.subarray(1));\n return { eof, chunk };\n}\n\n/**\n * List chunk files for a stream, sorted chronologically (ULID order).\n * Returns both the sorted file names and a map of file → extension for\n * resolving the full path. Handles tagged and legacy (.json) formats.\n */\nasync function listChunkFilesForStream(\n chunksDir: string,\n name: string,\n tag?: string\n): Promise<{ files: string[]; extMap: Map<string, string> }> {\n // Name is used as a filename prefix below; validate it can't escape chunksDir.\n assertSafeEntityId('streamName', name);\n const listPromises: Promise<string[]>[] = [\n listFilesByExtension(chunksDir, '.bin'),\n listFilesByExtension(chunksDir, '.json'),\n ];\n if (tag) {\n listPromises.push(listFilesByExtension(chunksDir, `.${tag}.bin`));\n }\n const [binFiles, jsonFiles, ...taggedResults] =\n await Promise.all(listPromises);\n const taggedBinFiles = taggedResults[0] ?? [];\n\n const extMap = new Map<string, string>();\n for (const f of jsonFiles) extMap.set(f, '.json');\n const tagSfx = tag ? `.${tag}` : '';\n for (const f of binFiles) {\n if (tag && f.endsWith(tagSfx)) continue;\n extMap.set(f, '.bin');\n }\n for (const f of taggedBinFiles) extMap.set(f, `.${tag}.bin`);\n\n const files = [...extMap.keys()]\n .filter((file) => file.startsWith(`${name}-`))\n .sort();\n\n return { files, extMap };\n}\n\nexport function createStreamer(basedir: string, tag?: string): Streamer {\n const tagSuffix = tag ? `.${tag}` : '';\n const streamEmitter = new EventEmitter<{\n [key: `chunk:${string}`]: [\n {\n streamName: string;\n chunkData: Uint8Array;\n chunkId: string;\n },\n ];\n [key: `close:${string}`]: [\n {\n streamName: string;\n },\n ];\n }>();\n\n // Track which streams have already been registered for a run (in-memory cache)\n const registeredStreams = new Set<string>();\n\n // Helper to record the runId <> streamId association\n async function registerStreamForRun(\n runId: string,\n streamName: string\n ): Promise<void> {\n assertSafeEntityId('runId', runId);\n assertSafeEntityId('streamName', streamName);\n const cacheKey = `${runId}:${streamName}`;\n if (registeredStreams.has(cacheKey)) {\n return; // Already registered in this session\n }\n\n const runStreamsPath = taggedPath(basedir, 'streams/runs', runId, tag);\n\n // Read existing streams for this run (try tagged first, fall back to untagged)\n const existing = await readJSONWithFallback(\n basedir,\n 'streams/runs',\n runId,\n RunStreamsSchema,\n tag\n );\n const streams = existing?.streams ?? [];\n\n // Add stream if not already present\n if (!streams.includes(streamName)) {\n streams.push(streamName);\n await writeJSON(runStreamsPath, { streams }, { overwrite: true });\n }\n\n registeredStreams.add(cacheKey);\n }\n\n // Helper to convert a chunk to a Buffer\n function toBuffer(chunk: string | Uint8Array): Buffer {\n if (typeof chunk === 'string') {\n return Buffer.from(new TextEncoder().encode(chunk));\n } else if (chunk instanceof Buffer) {\n return chunk;\n } else {\n return Buffer.from(chunk);\n }\n }\n\n return {\n streams: {\n async write(\n _runId: string | Promise<string>,\n name: string,\n chunk: string | Uint8Array\n ) {\n // Generate ULID synchronously BEFORE any await to preserve call order.\n // This ensures that chunks written in sequence maintain their order even\n // when runId is a promise that multiple writes are waiting on.\n const chunkId = `chnk_${monotonicUlid()}`;\n\n // Await runId if it's a promise to ensure proper flushing\n const runId = await _runId;\n\n // Register this stream for the run\n await registerStreamForRun(runId, name);\n\n // Convert chunk to buffer for serialization\n const chunkBuffer = toBuffer(chunk);\n\n const serialized = serializeChunk({\n chunk: chunkBuffer,\n eof: false,\n });\n\n const chunkPath = path.join(\n basedir,\n 'streams',\n 'chunks',\n `${name}-${chunkId}${tagSuffix}.bin`\n );\n\n await write(chunkPath, serialized);\n\n // Emit real-time event with Uint8Array (create copy to prevent ArrayBuffer detachment)\n const chunkData = Uint8Array.from(chunkBuffer);\n\n streamEmitter.emit(`chunk:${name}` as const, {\n streamName: name,\n chunkData,\n chunkId,\n });\n },\n\n async writeMulti(\n _runId: string | Promise<string>,\n name: string,\n chunks: (string | Uint8Array)[]\n ) {\n if (chunks.length === 0) return;\n\n // Generate all ULIDs synchronously BEFORE any await to preserve call order.\n // This ensures that chunks maintain their order even when runId is a promise.\n const chunkIds = chunks.map(() => `chnk_${monotonicUlid()}`);\n\n // Await runId if it's a promise\n const runId = await _runId;\n\n // Register this stream for the run\n await registerStreamForRun(runId, name);\n\n // Prepare chunk data for parallel writes\n const chunkBuffers = chunks.map((chunk) => toBuffer(chunk));\n\n // Write all chunks in parallel for efficiency, but track individual completion\n const writePromises = chunkBuffers.map(async (chunkBuffer, i) => {\n const chunkId = chunkIds[i];\n\n const serialized = serializeChunk({\n chunk: chunkBuffer,\n eof: false,\n });\n\n const chunkPath = path.join(\n basedir,\n 'streams',\n 'chunks',\n `${name}-${chunkId}${tagSuffix}.bin`\n );\n\n await write(chunkPath, serialized);\n\n // Return data needed for event emission\n return {\n chunkId,\n chunkData: Uint8Array.from(chunkBuffer),\n };\n });\n\n // Emit events in order, waiting for each chunk's write to complete\n // This ensures events are emitted in order while writes happen in parallel\n for (const writePromise of writePromises) {\n const { chunkId, chunkData } = await writePromise;\n\n streamEmitter.emit(`chunk:${name}` as const, {\n streamName: name,\n chunkData,\n chunkId,\n });\n }\n },\n\n async close(_runId: string | Promise<string>, name: string) {\n // Generate ULID synchronously BEFORE any await to preserve call order.\n const chunkId = `chnk_${monotonicUlid()}`;\n\n // Await runId if it's a promise to ensure proper flushing\n const runId = await _runId;\n\n // Register this stream for the run (in case write wasn't called)\n await registerStreamForRun(runId, name);\n const chunkPath = path.join(\n basedir,\n 'streams',\n 'chunks',\n `${name}-${chunkId}${tagSuffix}.bin`\n );\n\n await write(\n chunkPath,\n serializeChunk({ chunk: Buffer.from([]), eof: true })\n );\n\n streamEmitter.emit(`close:${name}` as const, { streamName: name });\n },\n\n async list(runId: string) {\n assertSafeEntityId('runId', runId);\n const data = await readJSONWithFallback(\n basedir,\n 'streams/runs',\n runId,\n RunStreamsSchema,\n tag\n );\n return data?.streams ?? [];\n },\n\n async getChunks(\n _runId: string,\n name: string,\n options?: GetChunksOptions\n ): Promise<StreamChunksResponse> {\n const limit = options?.limit ?? 100;\n const chunksDir = path.join(basedir, 'streams', 'chunks');\n const { files: chunkFiles, extMap: fileExtMap } =\n await listChunkFilesForStream(chunksDir, name, tag);\n\n // Decode cursor\n let startIndex = 0;\n if (options?.cursor) {\n try {\n const decoded = JSON.parse(\n Buffer.from(options.cursor, 'base64').toString('utf-8')\n );\n startIndex = decoded.i;\n } catch {\n startIndex = 0;\n }\n }\n\n // Walk from startIndex, reading only the files we need.\n // Files before the cursor are skipped entirely.\n let streamDone = false;\n const resultChunks: { index: number; data: Uint8Array }[] = [];\n let dataIndex = 0; // running count of data (non-EOF) files seen\n\n for (const file of chunkFiles) {\n const ext = fileExtMap.get(file) ?? '.bin';\n const filePath = path.join(chunksDir, `${file}${ext}`);\n\n // Before the cursor: only need to check EOF (1 byte), skip content\n if (dataIndex < startIndex) {\n if (isEofChunk(await readBuffer(filePath))) {\n streamDone = true;\n break;\n }\n dataIndex++;\n continue;\n }\n\n // Collected enough data chunks — peek at the next file for EOF/hasMore\n if (resultChunks.length >= limit) {\n if (isEofChunk(await readBuffer(filePath))) {\n streamDone = true;\n } else {\n // More data files exist beyond this page\n dataIndex++;\n }\n break;\n }\n\n // In the page window: deserialize fully\n const chunk = deserializeChunk(await readBuffer(filePath));\n if (chunk.eof) {\n streamDone = true;\n break;\n }\n resultChunks.push({\n index: dataIndex,\n data: Uint8Array.from(chunk.chunk),\n });\n dataIndex++;\n }\n\n // hasMore = we know there are data files beyond this page\n const hasMore =\n !streamDone && dataIndex > startIndex + resultChunks.length;\n const nextIndex = startIndex + resultChunks.length;\n const nextCursor = hasMore\n ? Buffer.from(JSON.stringify({ i: nextIndex })).toString('base64')\n : null;\n\n return {\n data: resultChunks,\n cursor: nextCursor,\n hasMore,\n done: streamDone,\n };\n },\n\n async getInfo(_runId: string, name: string): Promise<StreamInfoResponse> {\n const chunksDir = path.join(basedir, 'streams', 'chunks');\n const { files: chunkFiles, extMap: fileExtMap } =\n await listChunkFilesForStream(chunksDir, name, tag);\n\n // Only read the first byte of each file to check EOF — no full\n // deserialization needed since we just need a count.\n let streamDone = false;\n let dataCount = 0;\n for (const file of chunkFiles) {\n const ext = fileExtMap.get(file) ?? '.bin';\n if (\n isEofChunk(await readBuffer(path.join(chunksDir, `${file}${ext}`)))\n ) {\n streamDone = true;\n break;\n }\n dataCount++;\n }\n\n return { tailIndex: dataCount - 1, done: streamDone };\n },\n\n async get(_runId: string, name: string, startIndex = 0) {\n const chunksDir = path.join(basedir, 'streams', 'chunks');\n let removeListeners = () => {};\n let pollInterval: ReturnType<typeof setInterval> | null = null;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n // Track chunks delivered via events to prevent duplicates and maintain order.\n const deliveredChunkIds = new Set<string>();\n // Buffer for chunks that arrive via events during disk reading\n const bufferedEventChunks: Array<{\n chunkId: string;\n chunkData: Uint8Array;\n }> = [];\n let isReadingFromDisk = true;\n // Buffer close event if it arrives during disk reading\n let pendingClose = false;\n // Set when the controller is closed; guards against enqueue-after-close\n // in the polling callback when closeListener fires mid-iteration.\n let streamClosed = false;\n\n const chunkListener = (event: {\n streamName: string;\n chunkData: Uint8Array;\n chunkId: string;\n }) => {\n // Skip empty chunks to maintain consistency with disk reading behavior\n if (event.chunkData.byteLength === 0) {\n deliveredChunkIds.add(event.chunkId);\n return;\n }\n\n if (isReadingFromDisk) {\n deliveredChunkIds.add(event.chunkId);\n // Buffer chunks that arrive during disk reading to maintain order\n // Create a copy to prevent ArrayBuffer detachment when enqueued later\n bufferedEventChunks.push({\n chunkId: event.chunkId,\n chunkData: Uint8Array.from(event.chunkData),\n });\n } else if (!deliveredChunkIds.has(event.chunkId)) {\n // Guard against duplicates: polling may have already claimed this\n // chunk between its has() check and readBuffer() yield.\n deliveredChunkIds.add(event.chunkId);\n // After disk reading is complete, deliver chunks immediately\n // Create a copy to prevent ArrayBuffer detachment\n controller.enqueue(Uint8Array.from(event.chunkData));\n }\n };\n\n const closeListener = () => {\n // Buffer close event if disk reading is still in progress\n if (isReadingFromDisk) {\n pendingClose = true;\n return;\n }\n // Remove listeners before closing\n streamClosed = true;\n streamEmitter.off(`chunk:${name}` as const, chunkListener);\n streamEmitter.off(`close:${name}` as const, closeListener);\n if (pollInterval) {\n clearInterval(pollInterval);\n pollInterval = null;\n }\n try {\n controller.close();\n } catch {\n // Ignore if controller is already closed (e.g., from cancel() or EOF)\n }\n };\n removeListeners = closeListener;\n\n // Set up listeners FIRST to avoid missing events\n streamEmitter.on(`chunk:${name}` as const, chunkListener);\n streamEmitter.on(`close:${name}` as const, closeListener);\n\n // Now load existing chunks from disk.\n const { files: chunkFiles, extMap: fileExtMap } =\n await listChunkFilesForStream(chunksDir, name, tag);\n\n // Resolve negative startIndex relative to the number of data chunks\n // (excluding the trailing EOF marker chunk, if present).\n let dataChunkCount = chunkFiles.length;\n if (\n typeof startIndex === 'number' &&\n startIndex < 0 &&\n chunkFiles.length > 0\n ) {\n const lastFile = chunkFiles[chunkFiles.length - 1];\n const lastExt = fileExtMap.get(lastFile) ?? '.bin';\n // Note: this incurs an extra disk read to check the EOF marker.\n // Acceptable since negative startIndex is not a hot path.\n const lastChunk = deserializeChunk(\n await readBuffer(path.join(chunksDir, `${lastFile}${lastExt}`))\n );\n if (lastChunk?.eof === true) {\n dataChunkCount--;\n }\n }\n const resolvedStartIndex =\n typeof startIndex === 'number' && startIndex < 0\n ? Math.max(0, dataChunkCount + startIndex)\n : startIndex;\n\n // Process existing chunks, skipping any already delivered via events\n let isComplete = false;\n for (let i = resolvedStartIndex; i < chunkFiles.length; i++) {\n const file = chunkFiles[i];\n // Extract chunk ID from filename: \"streamName-chunkId\" or \"streamName-chunkId.tag\"\n const rawChunkId = file.substring(name.length + 1);\n // Strip tag suffix (e.g., \"chnk_ULID.vitest-0\" → \"chnk_ULID\")\n const chunkId = tag\n ? rawChunkId.replace(`.${tag}`, '')\n : rawChunkId;\n\n // Skip if already delivered via event\n if (deliveredChunkIds.has(chunkId)) {\n continue;\n }\n\n const ext = fileExtMap.get(file) ?? '.bin';\n const chunk = deserializeChunk(\n await readBuffer(path.join(chunksDir, `${file}${ext}`))\n );\n if (chunk?.eof === true) {\n isComplete = true;\n break;\n }\n // Track as handled so polling doesn't re-deliver\n deliveredChunkIds.add(chunkId);\n if (chunk.chunk.byteLength) {\n // Create a copy to prevent ArrayBuffer detachment\n controller.enqueue(Uint8Array.from(chunk.chunk));\n }\n }\n\n // Finished reading from disk - now deliver buffered event chunks in chronological order\n isReadingFromDisk = false;\n\n // Sort buffered chunks by ULID (chronological order)\n bufferedEventChunks.sort((a, b) =>\n a.chunkId.localeCompare(b.chunkId)\n );\n for (const buffered of bufferedEventChunks) {\n // Create a copy for defense in depth (already copied at storage, but be extra safe)\n controller.enqueue(Uint8Array.from(buffered.chunkData));\n }\n\n if (isComplete) {\n removeListeners();\n try {\n controller.close();\n } catch {\n // Ignore if controller is already closed (e.g., from closeListener event)\n }\n return;\n }\n\n // Process any pending close event that arrived during disk reading\n if (pendingClose) {\n streamEmitter.off(`chunk:${name}` as const, chunkListener);\n streamEmitter.off(`close:${name}` as const, closeListener);\n try {\n controller.close();\n } catch {\n // Ignore if controller is already closed\n }\n return;\n }\n\n // Track pre-startIndex chunks so polling doesn't re-deliver them\n for (\n let i = 0;\n i < resolvedStartIndex && i < chunkFiles.length;\n i++\n ) {\n const file = chunkFiles[i];\n const rawChunkId = file.substring(name.length + 1);\n const chunkId = tag\n ? rawChunkId.replace(`.${tag}`, '')\n : rawChunkId;\n deliveredChunkIds.add(chunkId);\n }\n\n // Start filesystem polling for cross-process streaming support.\n // The EventEmitter only works in-process; when the writer is in a\n // separate process (e.g. e2e test runner ↔ workbench app), polling\n // the shared filesystem is the fallback delivery mechanism.\n let isPolling = false;\n pollInterval = setInterval(async () => {\n if (isPolling) return;\n isPolling = true;\n try {\n const { files: currentFiles, extMap: currentExtMap } =\n await listChunkFilesForStream(chunksDir, name, tag);\n\n for (const file of currentFiles) {\n const rawChunkId = file.substring(name.length + 1);\n const chunkId = tag\n ? rawChunkId.replace(`.${tag}`, '')\n : rawChunkId;\n\n if (deliveredChunkIds.has(chunkId)) continue;\n deliveredChunkIds.add(chunkId);\n\n const ext = currentExtMap.get(file) ?? '.bin';\n const chunk = deserializeChunk(\n await readBuffer(path.join(chunksDir, `${file}${ext}`))\n );\n\n if (chunk?.eof === true) {\n streamClosed = true;\n if (pollInterval) {\n clearInterval(pollInterval);\n pollInterval = null;\n }\n streamEmitter.off(`chunk:${name}` as const, chunkListener);\n streamEmitter.off(`close:${name}` as const, closeListener);\n try {\n controller.close();\n } catch {\n // Ignore if controller is already closed\n }\n return;\n }\n\n // Guard against enqueue-after-close: closeListener may have\n // fired between our readBuffer() yield and this point.\n if (streamClosed) return;\n\n if (chunk.chunk.byteLength) {\n controller.enqueue(Uint8Array.from(chunk.chunk));\n }\n }\n } catch (err: unknown) {\n // Silently ignore transient filesystem errors (ENOENT, EACCES, etc.)\n // Surface unexpected errors so bugs aren't hidden\n if (!(err instanceof Error && 'code' in err)) {\n console.error('[world-local] Unexpected polling error:', err);\n }\n } finally {\n isPolling = false;\n }\n }, 100);\n },\n\n cancel() {\n removeListeners();\n if (pollInterval) {\n clearInterval(pollInterval);\n pollInterval = null;\n }\n },\n });\n },\n },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAaA,kDAAkD;AAClD,IAAI,cAAc,GAAsC,IAAI,CAAC;AAE7D,KAAK,UAAU,UAAU;IACvB,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,cAAc,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,cAAc,CAAC;AACxB,CAAC;AAED,IAAI,aAAa,GAAsC,IAAI,CAAC;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EAAE,CAAC,CAAC;YACjD,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,IAAI,CAAC,SAAS,CAAC;gBACb,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,KAAK;gBAC/B,OAAO,EAAG,CAAW,CAAC,OAAO;aAC9B,CAAC,CAAC;YACH,MAAM,CAAC,CAAC;QACV,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,GAAG,EAAE,CAAC;QACb,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,KAA4B;IAE5B,MAAM,IAAI,GAAG,MAAM,UAAU,EAAE,CAAC;IAChC,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,iDAAiD;AACjD,qDAAqD;AACrD,SAAS,kBAAkB,CAAI,GAAG,KAAe;IAC/C,OAAO,CAAC,KAAQ,EAAE,EAAE,CAClB,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,CAAU,CAAC,CAAC,CAAC;AACpE,CAAC;AAED,wFAAwF;AACxF,MAAM,CAAC,MAAM,WAAW,GAAG,kBAAkB,CAAS,cAAc,CAAC,CAAC;AAEtE,wDAAwD;AACxD,MAAM,CAAC,MAAM,SAAS,GAAG,kBAAkB,CAAS,YAAY,CAAC,CAAC;AAElE,oDAAoD;AACpD,MAAM,CAAC,MAAM,UAAU,GAAG,kBAAkB,CAAS,aAAa,CAAC,CAAC;AAEpE,kDAAkD;AAClD,MAAM,CAAC,MAAM,SAAS,GAAG,kBAAkB,CAAS,YAAY,CAAC,CAAC","sourcesContent":["/**\n * Minimal telemetry utilities for world-local package.\n *\n * NOTE: This module is a simplified version of world-vercel's telemetry.\n * It provides tracing capabilities for local development to match\n * the observability experience in production.\n *\n * IMPORTANT: This module uses the same tracer name 'workflow' as @workflow/core to ensure\n * all spans are reported under the parent application's service, not as a separate service.\n */\nimport type * as api from '@opentelemetry/api';\nimport type { Span, SpanKind, SpanOptions } from '@opentelemetry/api';\n\n// Lazy load OpenTelemetry API to make it optional\nlet otelApiPromise: Promise<typeof api | null> | null = null;\n\nasync function getOtelApi(): Promise<typeof api | null> {\n if (!otelApiPromise) {\n otelApiPromise = import('@opentelemetry/api').catch(() => null);\n }\n return otelApiPromise;\n}\n\nlet tracerPromise: Promise<api.Tracer | null> | null = null;\n\nasync function getTracer(): Promise<api.Tracer | null> {\n if (!tracerPromise) {\n tracerPromise = getOtelApi().then((otel) =>\n otel ? otel.trace.getTracer('workflow') : null\n );\n }\n return tracerPromise;\n}\n\n/**\n * Wrap an async function with a trace span.\n * No-op if OpenTelemetry is not available.\n */\nexport async function trace<T>(\n spanName: string,\n ...args:\n | [fn: (span?: Span) => Promise<T>]\n | [opts: SpanOptions, fn: (span?: Span) => Promise<T>]\n): Promise<T> {\n const [tracer, otel] = await Promise.all([getTracer(), getOtelApi()]);\n const { fn, opts } =\n typeof args[0] === 'function'\n ? { fn: args[0], opts: {} }\n : { fn: args[1], opts: args[0] };\n if (!fn) throw new Error('Function to trace must be provided');\n\n if (!tracer || !otel) {\n return await fn();\n }\n\n return tracer.startActiveSpan(spanName, opts, async (span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: otel.SpanStatusCode.OK });\n return result;\n } catch (e) {\n span.setStatus({\n code: otel.SpanStatusCode.ERROR,\n message: (e as Error).message,\n });\n throw e;\n } finally {\n span.end();\n }\n });\n}\n\n/**\n * Get SpanKind enum value by name.\n * Returns undefined if OpenTelemetry is not available.\n */\nexport async function getSpanKind(\n field: keyof typeof SpanKind\n): Promise<SpanKind | undefined> {\n const otel = await getOtelApi();\n if (!otel) return undefined;\n return otel.SpanKind[field];\n}\n\n// Semantic conventions for World/Storage tracing\n// Standard OTEL conventions for peer service mapping\nfunction SemanticConvention<T>(...names: string[]) {\n return (value: T) =>\n Object.fromEntries(names.map((name) => [name, value] as const));\n}\n\n/** The remote service name for Datadog service maps (Datadog-specific: peer.service) */\nexport const PeerService = SemanticConvention<string>('peer.service');\n\n/** RPC system identifier (standard OTEL: rpc.system) */\nexport const RpcSystem = SemanticConvention<string>('rpc.system');\n\n/** RPC service name (standard OTEL: rpc.service) */\nexport const RpcService = SemanticConvention<string>('rpc.service');\n\n/** RPC method name (standard OTEL: rpc.method) */\nexport const RpcMethod = SemanticConvention<string>('rpc.method');\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"test-helpers.js","sourceRoot":"","sources":["../src/test-helpers.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEvD;;;GAGG;AAEH;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,OAAgB,EAChB,IAKC;IAED,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QAC/C,SAAS,EAAE,aAAa;QACxB,WAAW,EAAE,oBAAoB;QACjC,SAAS,EAAE,IAAI;KAChB,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAChD,CAAC;IACD,OAAO,MAAM,CAAC,GAAG,CAAC;AACpB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,OAAgB,EAChB,KAAa,EACb,SAA2E,EAC3E,SAAmC;IAEnC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE;QAChD,SAAS;QACT,WAAW,EAAE,oBAAoB;QACjC,SAAS;KACH,CAAC,CAAC;IACV,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;QAChB,MA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C,KAAK,EAAE;QAChD,SAAS,EAAE,gBAAgB;QAC3B,WAAW,EAAE,oBAAoB;QACjC,aAAa,EAAE,MAAM;KACtB,CAAC,CAAC;IACH,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC","sourcesContent":["import type {\n Hook,\n SerializedData,\n Step,\n Storage,\n Wait,\n WorkflowRun,\n} from '@workflow/world';\nimport { SPEC_VERSION_CURRENT } from '@workflow/world';\n\n/**\n * Test helper functions for creating and updating storage entities through events.\n * These helpers simplify test setup by providing a convenient API for common operations.\n */\n\n/**\n * Create a new workflow run through the run_created event.\n */\nexport async function createRun(\n storage: Storage,\n data: {\n deploymentId: string;\n workflowName: string;\n input: SerializedData;\n executionContext?: Record<string, unknown>;\n }\n): Promise<WorkflowRun> {\n const result = await storage.events.create(null, {\n eventType: 'run_created',\n specVersion: SPEC_VERSION_CURRENT,\n eventData: data,\n });\n if (!result.run) {\n throw new Error('Expected run to be created');\n }\n return result.run;\n}\n\n/**\n * Update a workflow run's status through lifecycle events.\n */\nexport async function updateRun(\n storage: Storage,\n runId: string,\n eventType: 'run_started' | 'run_completed' | 'run_failed' | 'run_cancelled',\n eventData?: Record<string, unknown>\n): Promise<WorkflowRun> {\n const result = await storage.events.create(runId, {\n eventType,\n specVersion: SPEC_VERSION_CURRENT,\n eventData,\n } as any);\n if (!result.run) {\n throw new Error('Expected run to be updated');\n }\n return result.run;\n}\n\n/**\n * Create a new step through the step_created event.\n */\nexport async function createStep(\n storage: Storage,\n runId: string,\n data: {\n stepId: string;\n stepName: string;\n input: SerializedData;\n }\n): Promise<Step> {\n const result = await storage.events.create(runId, {\n eventType: 'step_created',\n specVersion: SPEC_VERSION_CURRENT,\n correlationId: data.stepId,\n eventData: { stepName: data.stepName, input: data.input },\n });\n if (!result.step) {\n throw new Error('Expected step to be created');\n }\n return result.step;\n}\n\n/**\n * Update a step's status through lifecycle events.\n */\nexport async function updateStep(\n storage: Storage,\n runId: string,\n stepId: string,\n eventType:\n | 'step_started'\n | 'step_completed'\n | 'step_failed'\n | 'step_retrying',\n eventData?: Record<string, unknown>\n): Promise<Step> {\n const result = await storage.events.create(runId, {\n eventType,\n specVersion: SPEC_VERSION_CURRENT,\n correlationId: stepId,\n eventData,\n } as any);\n if (!result.step) {\n throw new Error('Expected step to be updated');\n }\n return result.step;\n}\n\n/**\n * Create a new hook through the hook_created event.\n */\nexport async function createHook(\n storage: Storage,\n runId: string,\n data: {\n hookId: string;\n token: string;\n metadata?: SerializedData;\n }\n): Promise<Hook> {\n const result = await storage.events.create(runId, {\n eventType: 'hook_created',\n specVersion: SPEC_VERSION_CURRENT,\n correlationId: data.hookId,\n eventData: { token: data.token, metadata: data.metadata },\n });\n if (!result.hook) {\n throw new Error('Expected hook to be created');\n }\n return result.hook;\n}\n\n/**\n * Dispose a hook through the hook_disposed event.\n */\nexport async function disposeHook(\n storage: Storage,\n runId: string,\n hookId: string\n): Promise<void> {\n await storage.events.create(runId, {\n eventType: 'hook_disposed',\n specVersion: SPEC_VERSION_CURRENT,\n correlationId: hookId,\n });\n}\n\n/**\n * Create a new wait through the wait_created event.\n */\nexport async function createWait(\n storage: Storage,\n runId: string,\n data: {\n waitId: string;\n resumeAt: Date;\n }\n): Promise<Wait> {\n const result = await storage.events.create(runId, {\n eventType: 'wait_created',\n specVersion: SPEC_VERSION_CURRENT,\n correlationId: data.waitId,\n eventData: { resumeAt: data.resumeAt },\n });\n if (!result.wait) {\n throw new Error('Expected wait to be created');\n }\n return result.wait;\n}\n\n/**\n * Complete a wait through the wait_completed event.\n */\nexport async function completeWait(\n storage: Storage,\n runId: string,\n waitId: string\n): Promise<Wait> {\n const result = await storage.events.create(runId, {\n eventType: 'wait_completed',\n specVersion: SPEC_VERSION_CURRENT,\n correlationId: waitId,\n });\n if (!result.wait) {\n throw new Error('Expected wait to be completed');\n }\n return result.wait;\n}\n"]}
package/dist/util.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,UAAU,IAAI,CAAI,EAAW;IACjC,MAAM,MAAM,GAAG;QACb,IAAI,KAAK;YACP,MAAM,KAAK,GAAG,EAAE,EAAE,CAAC;YACnB,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YAClD,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Creates a lazily-evaluated, memoized version of the provided function.\n *\n * The returned object exposes a `value` getter that calls `fn` only once,\n * caches its result, and returns the cached value on subsequent accesses.\n *\n * @typeParam T - The return type of the provided function.\n * @param fn - The function to be called once and whose result will be cached.\n * @returns An object with a `value` property that returns the memoized result of `fn`.\n */\nexport function once<T>(fn: () => T) {\n const result = {\n get value() {\n const value = fn();\n Object.defineProperty(result, 'value', { value });\n return value;\n },\n };\n return result;\n}\n"]}