@multiplier-labs/stepflow 0.3.4 → 0.3.8

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 (109) hide show
  1. package/README.md +9 -0
  2. package/dist/{chunk-5XJBAPXF.js → chunk-4IDPWWGS.js} +15 -4
  3. package/dist/chunk-4IDPWWGS.js.map +1 -0
  4. package/dist/{chunk-U3PCVK6O.js → chunk-T6GAZBTQ.js} +70 -38
  5. package/dist/chunk-T6GAZBTQ.js.map +1 -0
  6. package/dist/{chunk-FMPJBK2N.js → chunk-TVSADUYU.js} +3 -5
  7. package/dist/{chunk-FMPJBK2N.js.map → chunk-TVSADUYU.js.map} +1 -1
  8. package/dist/events/index.d.ts +43 -3
  9. package/dist/events/index.js +7 -3
  10. package/dist/{index-Cd0IZ40L.d.ts → index-CdXDv30T.d.ts} +10 -2
  11. package/dist/index.d.ts +5 -4
  12. package/dist/index.js +159 -46
  13. package/dist/index.js.map +1 -1
  14. package/dist/scheduler/index.d.ts +2 -2
  15. package/dist/scheduler/index.js +1 -1
  16. package/dist/storage/index.d.ts +6 -4
  17. package/dist/storage/index.js +1 -1
  18. package/dist/{types-DSEjiLMj.d.ts → types-BfWe5yP6.d.ts} +2 -0
  19. package/package.json +26 -14
  20. package/.codekin/reports/code-review/2026-04-11_code-review-daily.md +0 -146
  21. package/.codekin/reports/code-review/2026-04-13_code-review-daily.md +0 -74
  22. package/.codekin/reports/comments/2026-04-04_comment-assessment.md +0 -179
  23. package/.codekin/reports/comments/2026-04-11_comment-assessment.md +0 -161
  24. package/.codekin/reports/comments/2026-04-14_comment-assessment.md +0 -34
  25. package/.codekin/reports/complexity/2026-04-03_complexity-report.md +0 -152
  26. package/.codekin/reports/complexity/2026-04-11_complexity-report.md +0 -152
  27. package/.codekin/reports/complexity/2026-04-14_complexity-report.md +0 -34
  28. package/.codekin/reports/dependencies/2026-04-04_dependency-health.md +0 -94
  29. package/.codekin/reports/dependencies/2026-04-11_dependency-health.md +0 -93
  30. package/.codekin/reports/docs-audit/2026-04-04_docs-audit.md +0 -10
  31. package/.codekin/reports/docs-audit/2026-04-11_docs-audit.md +0 -138
  32. package/.codekin/reports/docs-audit/2026-04-13_docs-audit.md +0 -121
  33. package/.codekin/reports/security/2026-04-03_security-audit.md +0 -208
  34. package/.codekin/reports/security/2026-04-11_security-audit.md +0 -297
  35. package/.github/CODEOWNERS +0 -15
  36. package/.github/dependabot.yml +0 -23
  37. package/.github/workflows/ci.yml +0 -38
  38. package/.github/workflows/publish.yml +0 -42
  39. package/.github/workflows/security.yml +0 -29
  40. package/CHANGELOG.md +0 -34
  41. package/SECURITY.md +0 -40
  42. package/dist/chunk-5XJBAPXF.js.map +0 -1
  43. package/dist/chunk-U3PCVK6O.js.map +0 -1
  44. package/docs/github-packages-setup.md +0 -97
  45. package/docs/stepflow-api-reference.md +0 -1663
  46. package/src/core/engine/concurrency.ts +0 -229
  47. package/src/core/engine/lifecycle.ts +0 -176
  48. package/src/core/engine.test.ts +0 -1435
  49. package/src/core/engine.ts +0 -598
  50. package/src/core/index.ts +0 -7
  51. package/src/core/orchestrator/persistence.ts +0 -165
  52. package/src/core/orchestrator/plan-resolution.ts +0 -140
  53. package/src/core/orchestrator/state-transitions.ts +0 -109
  54. package/src/core/orchestrator/step-runner.ts +0 -427
  55. package/src/core/orchestrator.ts +0 -252
  56. package/src/core/types.ts +0 -220
  57. package/src/events/index.ts +0 -8
  58. package/src/events/memory.test.ts +0 -107
  59. package/src/events/memory.ts +0 -92
  60. package/src/events/socketio.test.ts +0 -378
  61. package/src/events/socketio.ts +0 -262
  62. package/src/events/types.ts +0 -118
  63. package/src/events/webhook.test.ts +0 -949
  64. package/src/events/webhook.ts +0 -807
  65. package/src/index.ts +0 -270
  66. package/src/planning/evaluate-condition.test.ts +0 -153
  67. package/src/planning/evaluate-condition.ts +0 -105
  68. package/src/planning/index.ts +0 -55
  69. package/src/planning/planner.ts +0 -494
  70. package/src/planning/planning.test.ts +0 -727
  71. package/src/planning/registry.test.ts +0 -398
  72. package/src/planning/registry.ts +0 -283
  73. package/src/planning/types.ts +0 -566
  74. package/src/scheduler/cron.test.ts +0 -479
  75. package/src/scheduler/cron.ts +0 -438
  76. package/src/scheduler/index.ts +0 -8
  77. package/src/scheduler/postgres-persistence.ts +0 -530
  78. package/src/scheduler/sqlite-persistence.test.ts +0 -235
  79. package/src/scheduler/sqlite-persistence.ts +0 -286
  80. package/src/scheduler/types.ts +0 -73
  81. package/src/storage/index.ts +0 -27
  82. package/src/storage/memory.test.ts +0 -349
  83. package/src/storage/memory.ts +0 -227
  84. package/src/storage/postgres-core.ts +0 -550
  85. package/src/storage/postgres-migration.test.ts +0 -69
  86. package/src/storage/postgres-transaction-pagination.test.ts +0 -107
  87. package/src/storage/postgres.ts +0 -835
  88. package/src/storage/sqlite-core.ts +0 -151
  89. package/src/storage/sqlite.test.ts +0 -642
  90. package/src/storage/sqlite.ts +0 -717
  91. package/src/storage/types.ts +0 -343
  92. package/src/utils/errors.test.ts +0 -150
  93. package/src/utils/errors.ts +0 -161
  94. package/src/utils/id.ts +0 -21
  95. package/src/utils/index.ts +0 -10
  96. package/src/utils/logger.test.ts +0 -121
  97. package/src/utils/logger.ts +0 -96
  98. package/src/utils/pinned-fetch.test.ts +0 -84
  99. package/src/utils/pinned-fetch.ts +0 -118
  100. package/src/utils/postgres-deps.ts +0 -79
  101. package/src/utils/retry.test.ts +0 -177
  102. package/src/utils/retry.ts +0 -121
  103. package/src/utils/safe-json.test.ts +0 -166
  104. package/src/utils/safe-json.ts +0 -107
  105. package/src/utils/webhook-signature.test.ts +0 -111
  106. package/src/utils/webhook-signature.ts +0 -74
  107. package/tsconfig.json +0 -21
  108. package/tsup.config.ts +0 -14
  109. package/vitest.config.ts +0 -9
@@ -1,530 +0,0 @@
1
- /**
2
- * PostgreSQL persistence adapter for schedules.
3
- *
4
- * Stores workflow schedules in a PostgreSQL database table using Kysely.
5
- */
6
-
7
- import type { Kysely as KyselyType } from 'kysely';
8
- import type { Pool, PoolConfig } from 'pg';
9
- import { loadPostgresDeps } from '../utils/postgres-deps.js';
10
-
11
- // Lazy-loaded dependencies - populated by loadPostgresDeps() during initialize()
12
- let Kysely: any;
13
- let PostgresDialect: any;
14
- let sql: any;
15
- let pgModule: any;
16
- import type { WorkflowSchedule } from './types.js';
17
- import type { SchedulePersistence } from './cron.js';
18
- import type { Logger, RunStatus } from '../core/types.js';
19
- import { safeJsonParse as sharedSafeJsonParse } from '../utils/safe-json.js';
20
-
21
- // ============================================================================
22
- // Database Types (Kysely schema)
23
- // ============================================================================
24
-
25
- /** Kysely row type for the workflow_schedules table. */
26
- interface WorkflowSchedulesTable {
27
- id: string;
28
- /** Workflow kind this schedule targets. */
29
- workflow_kind: string;
30
- /** Trigger type: 'cron', 'workflow_completed', or 'manual'. */
31
- trigger_type: string;
32
- /** Cron expression for time-based triggers, null for non-cron schedules. */
33
- cron_expression: string | null;
34
- /** IANA timezone for cron evaluation, null defaults to UTC. */
35
- timezone: string | null;
36
- /** Workflow kind that triggers on completion, null for non-completion triggers. */
37
- trigger_on_workflow_kind: string | null;
38
- /** JSON-serialized array of RunStatus values that activate the trigger. */
39
- trigger_on_status: string | null;
40
- /** JSON-serialized input payload for spawned runs. */
41
- input_json: string | null;
42
- /** JSON-serialized arbitrary metadata for spawned runs. */
43
- metadata_json: string | null;
44
- /** Whether this schedule is active. */
45
- enabled: boolean;
46
- /** Timestamp of the most recent run spawned by this schedule. */
47
- last_run_at: Date | null;
48
- /** Run ID of the most recent run spawned by this schedule. */
49
- last_run_id: string | null;
50
- /** Next scheduled execution time. */
51
- next_run_at: Date | null;
52
- created_at: Date;
53
- updated_at: Date;
54
- }
55
-
56
- interface SchedulesDatabase {
57
- workflow_schedules: WorkflowSchedulesTable;
58
- }
59
-
60
- // ============================================================================
61
- // Configuration Types
62
- // ============================================================================
63
-
64
- /**
65
- * Configuration for PostgresSchedulePersistence.
66
- */
67
- export interface PostgresSchedulePersistenceConfig {
68
- /**
69
- * PostgreSQL connection string.
70
- * Example: "postgresql://user:pass@localhost:5432/dbname"
71
- */
72
- connectionString?: string;
73
-
74
- /**
75
- * Existing pg.Pool instance for connection sharing with application.
76
- * If provided, the adapter will not close this pool on close().
77
- */
78
- pool?: Pool;
79
-
80
- /**
81
- * Pool configuration options (if not providing pool or connectionString).
82
- */
83
- poolConfig?: PoolConfig;
84
-
85
- /**
86
- * Schema name for the schedules table.
87
- * @default 'public'
88
- */
89
- schema?: string;
90
-
91
- /**
92
- * Table name for schedules.
93
- * @default 'workflow_schedules'
94
- */
95
- tableName?: string;
96
-
97
- /**
98
- * Automatically create tables on initialization.
99
- * @default true
100
- */
101
- autoMigrate?: boolean;
102
-
103
- /**
104
- * Optional structured logger used to surface JSON corruption events.
105
- * Without one, parse failures still increment the corruption counter
106
- * exposed via `getJsonParseCorruptionCount()` but produce no log output.
107
- */
108
- logger?: Logger;
109
- }
110
-
111
- // ============================================================================
112
- // PostgresSchedulePersistence Class
113
- // ============================================================================
114
-
115
- /**
116
- * PostgreSQL-based persistence for workflow schedules.
117
- *
118
- * @example
119
- * ```typescript
120
- * const persistence = new PostgresSchedulePersistence({
121
- * connectionString: process.env.DATABASE_URL,
122
- * });
123
- *
124
- * await persistence.initialize();
125
- *
126
- * const scheduler = new CronScheduler({
127
- * engine,
128
- * persistence,
129
- * });
130
- * ```
131
- *
132
- * @example Sharing connection pool
133
- * ```typescript
134
- * import pg from 'pg';
135
- *
136
- * const pool = new pg.Pool({
137
- * connectionString: process.env.DATABASE_URL,
138
- * });
139
- *
140
- * const persistence = new PostgresSchedulePersistence({ pool });
141
- * await persistence.initialize();
142
- * ```
143
- */
144
- export class PostgresSchedulePersistence implements SchedulePersistence {
145
- private db!: KyselyType<SchedulesDatabase>;
146
- private pool!: Pool;
147
- private ownsPool = false;
148
- private schema: string;
149
- private tableName: string;
150
- private autoMigrate: boolean;
151
- private initialized = false;
152
- private config: PostgresSchedulePersistenceConfig;
153
- private logger: Logger | undefined;
154
-
155
- constructor(config: PostgresSchedulePersistenceConfig) {
156
- this.schema = config.schema ?? 'public';
157
- if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(this.schema)) {
158
- throw new Error(
159
- `Invalid schema name "${this.schema}". Schema must start with a letter or underscore, ` +
160
- `contain only alphanumeric characters and underscores, and be at most 63 characters.`
161
- );
162
- }
163
- this.tableName = config.tableName ?? 'workflow_schedules';
164
- if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(this.tableName)) {
165
- throw new Error(
166
- `Invalid table name "${this.tableName}". Table name must start with a letter or underscore, ` +
167
- `contain only alphanumeric characters and underscores, and be at most 63 characters.`
168
- );
169
- }
170
- this.autoMigrate = config.autoMigrate !== false;
171
- this.config = config;
172
- this.logger = config.logger;
173
- }
174
-
175
- /**
176
- * Get a schema-scoped query builder.
177
- * All queries MUST use this instead of this.db directly to respect config.schema.
178
- */
179
- private get qb() {
180
- return this.db.withSchema(this.schema);
181
- }
182
-
183
- private ensureInitialized(): void {
184
- if (!this.initialized) {
185
- throw new Error(
186
- 'PostgresSchedulePersistence is not initialized. Call initialize() before using the adapter.'
187
- );
188
- }
189
- }
190
-
191
- /**
192
- * Initialize the persistence layer.
193
- * Creates the schedules table if autoMigrate is enabled.
194
- */
195
- async initialize(): Promise<void> {
196
- if (this.initialized) {
197
- return;
198
- }
199
-
200
- const deps = await loadPostgresDeps();
201
- Kysely = deps.Kysely;
202
- PostgresDialect = deps.PostgresDialect;
203
- sql = deps.sql;
204
- pgModule = deps.pgModule;
205
-
206
- if (this.config.pool) {
207
- this.pool = this.config.pool;
208
- this.ownsPool = false;
209
- } else if (this.config.connectionString) {
210
- this.pool = new pgModule.Pool({ connectionString: this.config.connectionString });
211
- this.ownsPool = true;
212
- } else if (this.config.poolConfig) {
213
- this.pool = new pgModule.Pool(this.config.poolConfig);
214
- this.ownsPool = true;
215
- } else {
216
- throw new Error(
217
- 'PostgresSchedulePersistenceConfig must include either pool, connectionString, or poolConfig'
218
- );
219
- }
220
-
221
- this.db = new Kysely({
222
- dialect: new PostgresDialect({
223
- pool: this.pool,
224
- }),
225
- });
226
-
227
- if (this.autoMigrate) {
228
- await this.createTables();
229
- }
230
-
231
- this.initialized = true;
232
- }
233
-
234
- /**
235
- * Close the database connection.
236
- * Only closes the pool if it was created by this adapter.
237
- */
238
- async close(): Promise<void> {
239
- await this.db.destroy();
240
- if (this.ownsPool) {
241
- await this.pool.end();
242
- }
243
- }
244
-
245
- // ============================================================================
246
- // Database Initialization
247
- // ============================================================================
248
-
249
- private async createTables(): Promise<void> {
250
- const fullTableName = this.schema === 'public'
251
- ? this.tableName
252
- : `${this.schema}.${this.tableName}`;
253
-
254
- // Create schema if not public
255
- if (this.schema !== 'public') {
256
- await sql`CREATE SCHEMA IF NOT EXISTS ${sql.ref(this.schema)}`.execute(this.db);
257
- }
258
-
259
- // Create schedules table.
260
- // Schema layout:
261
- // id — unique schedule identifier (TEXT PK)
262
- // workflow_kind — target workflow type to spawn
263
- // trigger_type — constrained to 'cron' | 'workflow_completed' | 'manual'
264
- // cron_expression / timezone — cron trigger configuration
265
- // trigger_on_workflow_kind — completion trigger source kind
266
- // trigger_on_status — JSONB array of RunStatus values for completion triggers
267
- // input_json / metadata_json — JSONB payloads for spawned runs
268
- // enabled — whether this schedule is active
269
- // last_run_at / last_run_id — most recent execution tracking
270
- // next_run_at — next scheduled execution time
271
- // created_at / updated_at — audit timestamps (TIMESTAMPTZ)
272
- // No migration strategy is currently implemented; table is created idempotently.
273
- await sql`
274
- CREATE TABLE IF NOT EXISTS ${sql.table(fullTableName)} (
275
- id TEXT PRIMARY KEY,
276
- workflow_kind TEXT NOT NULL,
277
- trigger_type TEXT NOT NULL,
278
- cron_expression TEXT,
279
- timezone TEXT DEFAULT 'UTC',
280
- trigger_on_workflow_kind TEXT,
281
- trigger_on_status JSONB,
282
- input_json JSONB NOT NULL DEFAULT '{}',
283
- metadata_json JSONB NOT NULL DEFAULT '{}',
284
- enabled BOOLEAN NOT NULL DEFAULT true,
285
- last_run_at TIMESTAMPTZ,
286
- last_run_id TEXT,
287
- next_run_at TIMESTAMPTZ,
288
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
289
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
290
- CONSTRAINT ${sql.ref(`${this.tableName}_trigger_type_check`)} CHECK (
291
- trigger_type IN ('cron', 'workflow_completed', 'manual')
292
- )
293
- )
294
- `.execute(this.db);
295
-
296
- // Create indexes
297
- await sql`
298
- CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_workflow_kind`)}
299
- ON ${sql.table(fullTableName)} (workflow_kind)
300
- `.execute(this.db);
301
-
302
- await sql`
303
- CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_enabled`)}
304
- ON ${sql.table(fullTableName)} (enabled)
305
- `.execute(this.db);
306
-
307
- await sql`
308
- CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_trigger_type`)}
309
- ON ${sql.table(fullTableName)} (trigger_type)
310
- `.execute(this.db);
311
-
312
- await sql`
313
- CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_next_run`)}
314
- ON ${sql.table(fullTableName)} (next_run_at)
315
- WHERE enabled = true
316
- `.execute(this.db);
317
- }
318
-
319
- // ============================================================================
320
- // SchedulePersistence Interface Implementation
321
- // ============================================================================
322
-
323
- async loadSchedules(): Promise<WorkflowSchedule[]> {
324
- this.ensureInitialized();
325
- const rows = await this.qb
326
- .selectFrom(this.tableName as any)
327
- .selectAll()
328
- .execute() as WorkflowSchedulesTable[];
329
-
330
- return rows.map(row => this.rowToSchedule(row));
331
- }
332
-
333
- async saveSchedule(schedule: WorkflowSchedule): Promise<void> {
334
- this.ensureInitialized();
335
- await this.qb
336
- .insertInto(this.tableName as any)
337
- .values({
338
- id: schedule.id,
339
- workflow_kind: schedule.workflowKind,
340
- trigger_type: schedule.triggerType,
341
- cron_expression: schedule.cronExpression ?? null,
342
- timezone: schedule.timezone ?? null,
343
- trigger_on_workflow_kind: schedule.triggerOnWorkflowKind ?? null,
344
- trigger_on_status: schedule.triggerOnStatus ? JSON.stringify(schedule.triggerOnStatus) : null,
345
- input_json: schedule.input ? JSON.stringify(schedule.input) : null,
346
- metadata_json: schedule.metadata ? JSON.stringify(schedule.metadata) : null,
347
- enabled: schedule.enabled,
348
- last_run_at: schedule.lastRunAt ?? null,
349
- last_run_id: schedule.lastRunId ?? null,
350
- next_run_at: schedule.nextRunAt ?? null,
351
- created_at: new Date(),
352
- updated_at: new Date(),
353
- })
354
- .execute();
355
- }
356
-
357
- async updateSchedule(scheduleId: string, updates: Partial<WorkflowSchedule>): Promise<void> {
358
- this.ensureInitialized();
359
- // Partial update pattern: fetch the existing row, merge with incoming updates,
360
- // then build a column-level update object. Each field is only included if it was
361
- // explicitly provided in `updates` (or affected by the merge), so unchanged
362
- // columns are left untouched in the database.
363
- const existing = await this.qb
364
- .selectFrom(this.tableName as any)
365
- .selectAll()
366
- .where('id', '=', scheduleId)
367
- .executeTakeFirst() as WorkflowSchedulesTable | undefined;
368
-
369
- if (!existing) {
370
- throw new Error(`Schedule not found: ${scheduleId}`);
371
- }
372
-
373
- const merged = {
374
- ...this.rowToSchedule(existing),
375
- ...updates,
376
- };
377
-
378
- // Field mapping: { domainKey, dbKey, serialize? }
379
- // Each entry maps a WorkflowSchedule field to its DB column, with optional serialization.
380
- const fieldMappings: Array<{
381
- domainKey: keyof WorkflowSchedule;
382
- dbKey: keyof WorkflowSchedulesTable;
383
- serialize?: (value: any) => any;
384
- }> = [
385
- { domainKey: 'workflowKind', dbKey: 'workflow_kind' },
386
- { domainKey: 'triggerType', dbKey: 'trigger_type' },
387
- { domainKey: 'cronExpression', dbKey: 'cron_expression' },
388
- { domainKey: 'timezone', dbKey: 'timezone' },
389
- { domainKey: 'triggerOnWorkflowKind', dbKey: 'trigger_on_workflow_kind' },
390
- { domainKey: 'triggerOnStatus', dbKey: 'trigger_on_status', serialize: v => v ? JSON.stringify(v) : null },
391
- { domainKey: 'input', dbKey: 'input_json', serialize: v => v ? JSON.stringify(v) : null },
392
- { domainKey: 'metadata', dbKey: 'metadata_json', serialize: v => v ? JSON.stringify(v) : null },
393
- { domainKey: 'enabled', dbKey: 'enabled' },
394
- { domainKey: 'lastRunAt', dbKey: 'last_run_at' },
395
- { domainKey: 'lastRunId', dbKey: 'last_run_id' },
396
- { domainKey: 'nextRunAt', dbKey: 'next_run_at' },
397
- ];
398
-
399
- const updateData: Partial<WorkflowSchedulesTable> = {
400
- updated_at: new Date(),
401
- };
402
-
403
- for (const { domainKey, dbKey, serialize } of fieldMappings) {
404
- if (updates[domainKey] !== undefined || merged[domainKey] !== undefined) {
405
- const value = serialize
406
- ? serialize(merged[domainKey])
407
- : (merged[domainKey] ?? null);
408
- (updateData as any)[dbKey] = value;
409
- }
410
- }
411
-
412
- await this.qb
413
- .updateTable(this.tableName as any)
414
- .set(updateData)
415
- .where('id', '=', scheduleId)
416
- .execute();
417
- }
418
-
419
- async deleteSchedule(scheduleId: string): Promise<void> {
420
- this.ensureInitialized();
421
- await this.qb
422
- .deleteFrom(this.tableName as any)
423
- .where('id', '=', scheduleId)
424
- .execute();
425
- }
426
-
427
- // ============================================================================
428
- // Additional Methods
429
- // ============================================================================
430
-
431
- /**
432
- * Get a schedule by ID.
433
- */
434
- async getSchedule(scheduleId: string): Promise<WorkflowSchedule | null> {
435
- this.ensureInitialized();
436
- const row = await this.qb
437
- .selectFrom(this.tableName as any)
438
- .selectAll()
439
- .where('id', '=', scheduleId)
440
- .executeTakeFirst() as WorkflowSchedulesTable | undefined;
441
-
442
- return row ? this.rowToSchedule(row) : null;
443
- }
444
-
445
- /**
446
- * Get all enabled schedules that are due to run.
447
- */
448
- async getDueSchedules(): Promise<WorkflowSchedule[]> {
449
- this.ensureInitialized();
450
- const now = new Date();
451
-
452
- const rows = await this.qb
453
- .selectFrom(this.tableName as any)
454
- .selectAll()
455
- .where('enabled', '=', true)
456
- .where('trigger_type', '=', 'cron')
457
- .where('next_run_at', '<=', now)
458
- .execute() as WorkflowSchedulesTable[];
459
-
460
- return rows.map(row => this.rowToSchedule(row));
461
- }
462
-
463
- /**
464
- * Get schedules by workflow kind.
465
- */
466
- async getSchedulesByWorkflowKind(workflowKind: string): Promise<WorkflowSchedule[]> {
467
- this.ensureInitialized();
468
- const rows = await this.qb
469
- .selectFrom(this.tableName as any)
470
- .selectAll()
471
- .where('workflow_kind', '=', workflowKind)
472
- .execute() as WorkflowSchedulesTable[];
473
-
474
- return rows.map(row => this.rowToSchedule(row));
475
- }
476
-
477
- /**
478
- * Get workflow completion triggers for a specific workflow kind.
479
- */
480
- async getCompletionTriggers(triggerOnWorkflowKind: string): Promise<WorkflowSchedule[]> {
481
- this.ensureInitialized();
482
- const rows = await this.qb
483
- .selectFrom(this.tableName as any)
484
- .selectAll()
485
- .where('enabled', '=', true)
486
- .where('trigger_type', '=', 'workflow_completed')
487
- .where('trigger_on_workflow_kind', '=', triggerOnWorkflowKind)
488
- .execute() as WorkflowSchedulesTable[];
489
-
490
- return rows.map(row => this.rowToSchedule(row));
491
- }
492
-
493
- // ============================================================================
494
- // Helper Methods
495
- // ============================================================================
496
-
497
- private safeParseOptionalField(value: unknown, rowId: string, column: string): unknown {
498
- if (!value) return undefined;
499
- if (typeof value === 'string') {
500
- return sharedSafeJsonParse(value, undefined, {
501
- component: 'PostgresSchedulePersistence',
502
- rowId,
503
- column,
504
- logger: this.logger,
505
- });
506
- }
507
- return value;
508
- }
509
-
510
- private rowToSchedule(row: WorkflowSchedulesTable): WorkflowSchedule {
511
- return {
512
- id: row.id,
513
- workflowKind: row.workflow_kind,
514
- triggerType: row.trigger_type as WorkflowSchedule['triggerType'],
515
- cronExpression: row.cron_expression ?? undefined,
516
- timezone: row.timezone ?? undefined,
517
- triggerOnWorkflowKind: row.trigger_on_workflow_kind ?? undefined,
518
- triggerOnStatus: this.safeParseOptionalField(row.trigger_on_status, row.id, 'trigger_on_status') as RunStatus[] | undefined,
519
- input: this.safeParseOptionalField(row.input_json, row.id, 'input_json') as Record<string, unknown> | undefined,
520
- metadata: this.safeParseOptionalField(row.metadata_json, row.id, 'metadata_json') as Record<string, unknown> | undefined,
521
- enabled: row.enabled,
522
- lastRunAt: row.last_run_at ? new Date(row.last_run_at) : undefined,
523
- lastRunId: row.last_run_id ?? undefined,
524
- nextRunAt: row.next_run_at ? new Date(row.next_run_at) : undefined,
525
- };
526
- }
527
- }
528
-
529
- // Convenience alias for shorter naming
530
- export type { PostgresSchedulePersistenceConfig as PostgresSchedulePersistenceOptions };