semola 0.5.2 → 0.5.4

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 (160) hide show
  1. package/README.md +88 -13
  2. package/dist/index-BhGNDjPq.d.mts +13 -0
  3. package/dist/index-DxSbeGP-.d.cts +13 -0
  4. package/dist/lib/api/index.cjs +522 -4
  5. package/dist/lib/api/index.d.cts +270 -4
  6. package/dist/lib/api/index.d.mts +270 -4
  7. package/dist/lib/api/index.mjs +520 -2
  8. package/dist/lib/cache/index.d.cts +19 -7
  9. package/dist/lib/cache/index.d.mts +19 -7
  10. package/dist/lib/cache/index.mjs +0 -2
  11. package/dist/lib/cron/index.cjs +470 -11
  12. package/dist/lib/cron/index.d.cts +112 -5
  13. package/dist/lib/cron/index.d.mts +112 -5
  14. package/dist/lib/cron/index.mjs +461 -12
  15. package/dist/lib/errors/index.d.cts +2 -13
  16. package/dist/lib/errors/index.d.mts +2 -13
  17. package/dist/lib/errors/index.mjs +0 -2
  18. package/dist/lib/i18n/index.cjs +6 -1
  19. package/dist/lib/i18n/index.d.cts +12 -4
  20. package/dist/lib/i18n/index.d.mts +12 -4
  21. package/dist/lib/i18n/index.mjs +6 -3
  22. package/dist/lib/logging/index.cjs +387 -0
  23. package/dist/lib/logging/index.d.cts +108 -0
  24. package/dist/lib/logging/index.d.mts +108 -0
  25. package/dist/lib/logging/index.mjs +374 -0
  26. package/dist/lib/policy/index.cjs +206 -20
  27. package/dist/lib/policy/index.d.cts +61 -5
  28. package/dist/lib/policy/index.d.mts +61 -5
  29. package/dist/lib/policy/index.mjs +187 -3
  30. package/dist/lib/prompts/index.cjs +374 -14
  31. package/dist/lib/prompts/index.d.cts +77 -12
  32. package/dist/lib/prompts/index.d.mts +77 -12
  33. package/dist/lib/prompts/index.mjs +362 -4
  34. package/dist/lib/pubsub/index.cjs +82 -13
  35. package/dist/lib/pubsub/index.d.cts +23 -9
  36. package/dist/lib/pubsub/index.d.mts +23 -9
  37. package/dist/lib/pubsub/index.mjs +82 -15
  38. package/dist/lib/queue/index.d.cts +46 -4
  39. package/dist/lib/queue/index.d.mts +46 -4
  40. package/dist/lib/queue/index.mjs +0 -2
  41. package/dist/lib/workflow/index.cjs +534 -0
  42. package/dist/lib/workflow/index.d.cts +85 -0
  43. package/dist/lib/workflow/index.d.mts +85 -0
  44. package/dist/lib/workflow/index.mjs +533 -0
  45. package/package.json +29 -3
  46. package/dist/api/core/index.cjs +0 -206
  47. package/dist/api/core/index.d.cts +0 -21
  48. package/dist/api/core/index.d.cts.map +0 -1
  49. package/dist/api/core/index.d.mts +0 -21
  50. package/dist/api/core/index.d.mts.map +0 -1
  51. package/dist/api/core/index.mjs +0 -208
  52. package/dist/api/core/index.mjs.map +0 -1
  53. package/dist/api/core/types.d.cts +0 -107
  54. package/dist/api/core/types.d.cts.map +0 -1
  55. package/dist/api/core/types.d.mts +0 -107
  56. package/dist/api/core/types.d.mts.map +0 -1
  57. package/dist/api/middleware/index.cjs +0 -8
  58. package/dist/api/middleware/index.d.cts +0 -11
  59. package/dist/api/middleware/index.d.cts.map +0 -1
  60. package/dist/api/middleware/index.d.mts +0 -11
  61. package/dist/api/middleware/index.d.mts.map +0 -1
  62. package/dist/api/middleware/index.mjs +0 -10
  63. package/dist/api/middleware/index.mjs.map +0 -1
  64. package/dist/api/middleware/types.d.cts +0 -16
  65. package/dist/api/middleware/types.d.cts.map +0 -1
  66. package/dist/api/middleware/types.d.mts +0 -16
  67. package/dist/api/middleware/types.d.mts.map +0 -1
  68. package/dist/api/openapi/index.cjs +0 -254
  69. package/dist/api/openapi/index.mjs +0 -256
  70. package/dist/api/openapi/index.mjs.map +0 -1
  71. package/dist/api/openapi/types.d.cts +0 -60
  72. package/dist/api/openapi/types.d.cts.map +0 -1
  73. package/dist/api/openapi/types.d.mts +0 -60
  74. package/dist/api/openapi/types.d.mts.map +0 -1
  75. package/dist/api/validation/index.cjs +0 -64
  76. package/dist/api/validation/index.mjs +0 -61
  77. package/dist/api/validation/index.mjs.map +0 -1
  78. package/dist/cache/types.d.cts +0 -17
  79. package/dist/cache/types.d.cts.map +0 -1
  80. package/dist/cache/types.d.mts +0 -17
  81. package/dist/cache/types.d.mts.map +0 -1
  82. package/dist/cron/scanner.cjs +0 -237
  83. package/dist/cron/scanner.mjs +0 -238
  84. package/dist/cron/scanner.mjs.map +0 -1
  85. package/dist/cron/types.d.cts +0 -11
  86. package/dist/cron/types.d.cts.map +0 -1
  87. package/dist/cron/types.d.mts +0 -11
  88. package/dist/cron/types.d.mts.map +0 -1
  89. package/dist/errors/types.d.cts +0 -5
  90. package/dist/errors/types.d.cts.map +0 -1
  91. package/dist/errors/types.d.mts +0 -5
  92. package/dist/errors/types.d.mts.map +0 -1
  93. package/dist/i18n/types.d.cts +0 -13
  94. package/dist/i18n/types.d.cts.map +0 -1
  95. package/dist/i18n/types.d.mts +0 -13
  96. package/dist/i18n/types.d.mts.map +0 -1
  97. package/dist/lib/cache/index.d.cts.map +0 -1
  98. package/dist/lib/cache/index.d.mts.map +0 -1
  99. package/dist/lib/cache/index.mjs.map +0 -1
  100. package/dist/lib/cron/index.d.cts.map +0 -1
  101. package/dist/lib/cron/index.d.mts.map +0 -1
  102. package/dist/lib/cron/index.mjs.map +0 -1
  103. package/dist/lib/errors/index.d.cts.map +0 -1
  104. package/dist/lib/errors/index.d.mts.map +0 -1
  105. package/dist/lib/errors/index.mjs.map +0 -1
  106. package/dist/lib/i18n/index.d.cts.map +0 -1
  107. package/dist/lib/i18n/index.d.mts.map +0 -1
  108. package/dist/lib/i18n/index.mjs.map +0 -1
  109. package/dist/lib/policy/index.d.cts.map +0 -1
  110. package/dist/lib/policy/index.d.mts.map +0 -1
  111. package/dist/lib/policy/index.mjs.map +0 -1
  112. package/dist/lib/prompts/index.d.cts.map +0 -1
  113. package/dist/lib/prompts/index.d.mts.map +0 -1
  114. package/dist/lib/prompts/index.mjs.map +0 -1
  115. package/dist/lib/pubsub/index.d.cts.map +0 -1
  116. package/dist/lib/pubsub/index.d.mts.map +0 -1
  117. package/dist/lib/pubsub/index.mjs.map +0 -1
  118. package/dist/lib/queue/index.d.cts.map +0 -1
  119. package/dist/lib/queue/index.d.mts.map +0 -1
  120. package/dist/lib/queue/index.mjs.map +0 -1
  121. package/dist/node_modules/@standard-schema/spec/dist/index.d.cts +0 -80
  122. package/dist/node_modules/@standard-schema/spec/dist/index.d.cts.map +0 -1
  123. package/dist/node_modules/@standard-schema/spec/dist/index.d.mts +0 -80
  124. package/dist/node_modules/@standard-schema/spec/dist/index.d.mts.map +0 -1
  125. package/dist/policy/helpers.cjs +0 -206
  126. package/dist/policy/helpers.d.cts +0 -50
  127. package/dist/policy/helpers.d.cts.map +0 -1
  128. package/dist/policy/helpers.d.mts +0 -50
  129. package/dist/policy/helpers.d.mts.map +0 -1
  130. package/dist/policy/helpers.mjs +0 -190
  131. package/dist/policy/helpers.mjs.map +0 -1
  132. package/dist/policy/types.d.cts +0 -16
  133. package/dist/policy/types.d.cts.map +0 -1
  134. package/dist/policy/types.d.mts +0 -16
  135. package/dist/policy/types.d.mts.map +0 -1
  136. package/dist/prompts/core/keys.cjs +0 -165
  137. package/dist/prompts/core/keys.mjs +0 -167
  138. package/dist/prompts/core/keys.mjs.map +0 -1
  139. package/dist/prompts/core/runtime.cjs +0 -104
  140. package/dist/prompts/core/runtime.mjs +0 -106
  141. package/dist/prompts/core/runtime.mjs.map +0 -1
  142. package/dist/prompts/core/session.cjs +0 -98
  143. package/dist/prompts/core/session.mjs +0 -100
  144. package/dist/prompts/core/session.mjs.map +0 -1
  145. package/dist/prompts/core/types.d.cts +0 -21
  146. package/dist/prompts/core/types.d.cts.map +0 -1
  147. package/dist/prompts/core/types.d.mts +0 -21
  148. package/dist/prompts/core/types.d.mts.map +0 -1
  149. package/dist/prompts/types.d.cts +0 -52
  150. package/dist/prompts/types.d.cts.map +0 -1
  151. package/dist/prompts/types.d.mts +0 -52
  152. package/dist/prompts/types.d.mts.map +0 -1
  153. package/dist/pubsub/types.d.cts +0 -10
  154. package/dist/pubsub/types.d.cts.map +0 -1
  155. package/dist/pubsub/types.d.mts +0 -10
  156. package/dist/pubsub/types.d.mts.map +0 -1
  157. package/dist/queue/types.d.cts +0 -47
  158. package/dist/queue/types.d.cts.map +0 -1
  159. package/dist/queue/types.d.mts +0 -47
  160. package/dist/queue/types.d.mts.map +0 -1
@@ -0,0 +1,85 @@
1
+ //#region src/lib/workflow/types.d.ts
2
+ type WorkflowStatus = "pending" | "running" | "completed" | "failed" | "cancelled";
3
+ type WorkflowErrorType = "WorkflowError" | "WorkflowNotFoundError" | "WorkflowStateError" | "WorkflowSerializationError" | "WorkflowLockError" | "WorkflowExecutionError" | "WorkflowCancelledError";
4
+ type WorkflowError = {
5
+ type: WorkflowErrorType;
6
+ message: string;
7
+ };
8
+ type StepSnapshot = {
9
+ name: string;
10
+ completedAt: number;
11
+ };
12
+ type WorkflowExecution<TInput, TResult> = {
13
+ id: string;
14
+ name: string;
15
+ status: WorkflowStatus;
16
+ input: TInput;
17
+ result: TResult | null;
18
+ error: string | null;
19
+ createdAt: number;
20
+ updatedAt: number;
21
+ completedAt: number | null;
22
+ failedAt: number | null;
23
+ cancelledAt: number | null;
24
+ steps: StepSnapshot[];
25
+ };
26
+ type StepHandler<TInput, TStep> = (input: TInput, signal: AbortSignal) => TStep | Promise<TStep>;
27
+ type WorkflowHandlerContext<TInput> = {
28
+ input: TInput;
29
+ executionId: string;
30
+ signal: AbortSignal;
31
+ step: <TStep>(name: string, handler: StepHandler<TInput, TStep>) => Promise<TStep>;
32
+ };
33
+ type SerializeValue<T> = (value: T) => string;
34
+ type DeserializeValue<T> = (raw: string) => T;
35
+ type WorkflowOptions<TInput, TResult> = {
36
+ name: string;
37
+ redis: Bun.RedisClient;
38
+ handler: (context: WorkflowHandlerContext<TInput>) => TResult | Promise<TResult>;
39
+ lockTTL?: number;
40
+ serializeInput?: SerializeValue<TInput>;
41
+ deserializeInput?: DeserializeValue<TInput>;
42
+ serializeResult?: SerializeValue<TResult>;
43
+ deserializeResult?: DeserializeValue<TResult>;
44
+ serializeStepOutput?: SerializeValue<unknown>;
45
+ deserializeStepOutput?: DeserializeValue<unknown>;
46
+ };
47
+ type WorkflowStartOptions = {
48
+ executionId?: string;
49
+ };
50
+ type WorkflowStartResult = {
51
+ executionId: string;
52
+ status: WorkflowStatus;
53
+ };
54
+ type WorkflowCancelResult = {
55
+ status: WorkflowStatus;
56
+ executionId: string;
57
+ updatedAt: number;
58
+ cancelledAt: number;
59
+ createdAt: number;
60
+ };
61
+ type WorkflowMeta = {
62
+ status: string;
63
+ input: string;
64
+ result: string;
65
+ error: string;
66
+ createdAt: string;
67
+ updatedAt: string;
68
+ completedAt: string;
69
+ failedAt: string;
70
+ cancelledAt: string;
71
+ steps: string;
72
+ };
73
+ type WorkflowMetaField = keyof WorkflowMeta;
74
+ type Workflow<TInput, TResult> = {
75
+ start: (input: TInput, options?: WorkflowStartOptions) => Promise<readonly [WorkflowError | null, WorkflowStartResult | null]>;
76
+ run: (input: TInput, options?: WorkflowStartOptions) => Promise<readonly [WorkflowError | null, TResult | null]>;
77
+ resume: (executionId: string) => Promise<readonly [WorkflowError | null, WorkflowStartResult | null]>;
78
+ get: (executionId: string) => Promise<readonly [WorkflowError | null, WorkflowExecution<TInput, TResult> | null]>;
79
+ cancel: (executionId: string) => Promise<readonly [WorkflowError | null, WorkflowCancelResult | null]>;
80
+ };
81
+ //#endregion
82
+ //#region src/lib/workflow/index.d.ts
83
+ declare const defineWorkflow: <TInput, TResult = void>(options: WorkflowOptions<TInput, TResult>) => Workflow<TInput, TResult>;
84
+ //#endregion
85
+ export { type StepHandler, type Workflow, type WorkflowError, type WorkflowExecution, type WorkflowHandlerContext, type WorkflowMeta, type WorkflowMetaField, type WorkflowOptions, type WorkflowStartOptions, type WorkflowStartResult, type WorkflowStatus, defineWorkflow };
@@ -0,0 +1,533 @@
1
+ import { err, mightThrow, mightThrowSync, ok } from "../errors/index.mjs";
2
+ //#region src/lib/workflow/index.ts
3
+ const DEFAULT_LOCK_TTL = 300 * 1e3;
4
+ const now = () => Date.now();
5
+ const toErrorMessage = (error) => {
6
+ if (error instanceof Error) return error.message;
7
+ return String(error);
8
+ };
9
+ const envelopeSerialize = (value) => {
10
+ return JSON.stringify({ value });
11
+ };
12
+ const envelopeDeserialize = (raw) => {
13
+ const [parseError, parsed] = mightThrowSync(() => JSON.parse(raw));
14
+ if (parseError) throw parseError;
15
+ if (parsed === null) return;
16
+ if (typeof parsed !== "object") return;
17
+ if ("value" in parsed) return parsed.value;
18
+ };
19
+ const knownStatuses = [
20
+ "pending",
21
+ "running",
22
+ "completed",
23
+ "failed",
24
+ "cancelled"
25
+ ];
26
+ var WorkflowDefinition = class {
27
+ options;
28
+ lockTTL;
29
+ constructor(options) {
30
+ this.options = options;
31
+ this.lockTTL = options.lockTTL ?? DEFAULT_LOCK_TTL;
32
+ }
33
+ async start(input, options) {
34
+ const executionId = options?.executionId ?? crypto.randomUUID();
35
+ const [createError] = await this.createExecution(executionId, input);
36
+ if (createError) return err(createError.type, createError.message);
37
+ return this.execute(executionId, input);
38
+ }
39
+ async run(input, options) {
40
+ const [startError, startData] = await this.start(input, options);
41
+ if (startError) return err(startError.type, startError.message);
42
+ if (!startData) return err("WorkflowError", "Unexpected empty start result");
43
+ if (startData.status === "cancelled") return err("WorkflowCancelledError", `Workflow execution ${startData.executionId} was cancelled`);
44
+ if (startData.status !== "completed") return err("WorkflowExecutionError", `Workflow execution ${startData.executionId} did not complete`);
45
+ const [getError, execution] = await this.get(startData.executionId);
46
+ if (getError) return err(getError.type, getError.message);
47
+ if (!execution) return err("WorkflowError", "Unexpected empty execution");
48
+ return ok(execution.result);
49
+ }
50
+ async resume(executionId) {
51
+ const [getError, execution] = await this.get(executionId);
52
+ if (getError) return err(getError.type, getError.message);
53
+ if (!execution) return err("WorkflowNotFoundError", `Workflow execution ${executionId} not found`);
54
+ if (execution.status === "completed") return ok({
55
+ executionId,
56
+ status: execution.status
57
+ });
58
+ if (execution.status === "cancelled") return ok({
59
+ executionId,
60
+ status: execution.status
61
+ });
62
+ return this.execute(executionId, execution.input);
63
+ }
64
+ async get(executionId) {
65
+ const [statusError, status] = await this.getMeta(executionId, "status");
66
+ if (statusError) return err(statusError.type, statusError.message);
67
+ if (!status) return err("WorkflowNotFoundError", `Workflow execution ${executionId} not found`);
68
+ const normalizedStatus = this.normalizeStatus(status);
69
+ if (!normalizedStatus) return err("WorkflowStateError", `Workflow execution ${executionId} has invalid status ${status}`);
70
+ const [inputError, input] = await this.readInput(executionId);
71
+ if (inputError) return err(inputError.type, inputError.message);
72
+ if (input === null) return err("WorkflowStateError", `Workflow execution ${executionId} has invalid input`);
73
+ const [resultError, result] = await this.readResult(executionId);
74
+ if (resultError) return err(resultError.type, resultError.message);
75
+ const [stepsError, steps] = await this.readStepSnapshots(executionId);
76
+ if (stepsError) return err(stepsError.type, stepsError.message);
77
+ const [createdAtError, createdAt] = await this.readNumberMeta(executionId, "createdAt");
78
+ if (createdAtError) return err(createdAtError.type, createdAtError.message);
79
+ if (createdAt === null) return err("WorkflowStateError", `Workflow execution ${executionId} is missing createdAt`);
80
+ const [updatedAtError, updatedAt] = await this.readNumberMeta(executionId, "updatedAt");
81
+ if (updatedAtError) return err(updatedAtError.type, updatedAtError.message);
82
+ if (updatedAt === null) return err("WorkflowStateError", `Workflow execution ${executionId} is missing updatedAt`);
83
+ const [metaError, errorMessage] = await this.getMeta(executionId, "error");
84
+ if (metaError) return err(metaError.type, metaError.message);
85
+ const [completedAtError, completedAt] = await this.readNumberMeta(executionId, "completedAt");
86
+ if (completedAtError) return err(completedAtError.type, completedAtError.message);
87
+ const [failedAtError, failedAt] = await this.readNumberMeta(executionId, "failedAt");
88
+ if (failedAtError) return err(failedAtError.type, failedAtError.message);
89
+ const [cancelledAtError, cancelledAt] = await this.readNumberMeta(executionId, "cancelledAt");
90
+ if (cancelledAtError) return err(cancelledAtError.type, cancelledAtError.message);
91
+ return ok({
92
+ id: executionId,
93
+ name: this.options.name,
94
+ status: normalizedStatus,
95
+ input,
96
+ result,
97
+ error: errorMessage,
98
+ createdAt,
99
+ updatedAt,
100
+ completedAt,
101
+ failedAt,
102
+ cancelledAt,
103
+ steps
104
+ });
105
+ }
106
+ async cancel(executionId) {
107
+ const [getError, execution] = await this.get(executionId);
108
+ if (getError) return err(getError.type, getError.message);
109
+ if (!execution) return err("WorkflowNotFoundError", `Workflow execution ${executionId} not found`);
110
+ if (execution.status === "completed") return err("WorkflowStateError", `Workflow execution ${executionId} is already completed`);
111
+ const timestamp = now();
112
+ const [statusError] = await this.setMeta(executionId, "status", "cancelled");
113
+ if (statusError) return err(statusError.type, statusError.message);
114
+ const [updatedAtError] = await this.setMeta(executionId, "updatedAt", String(timestamp));
115
+ if (updatedAtError) return err(updatedAtError.type, updatedAtError.message);
116
+ const [cancelledAtError] = await this.setMeta(executionId, "cancelledAt", String(timestamp));
117
+ if (cancelledAtError) return err(cancelledAtError.type, cancelledAtError.message);
118
+ const [clearErrorError] = await this.setMeta(executionId, "error", "");
119
+ if (clearErrorError) return err(clearErrorError.type, clearErrorError.message);
120
+ const [clearFailedAtError] = await this.setMeta(executionId, "failedAt", "");
121
+ if (clearFailedAtError) return err(clearFailedAtError.type, clearFailedAtError.message);
122
+ return ok({
123
+ executionId,
124
+ createdAt: execution.createdAt,
125
+ cancelledAt: timestamp,
126
+ updatedAt: timestamp,
127
+ status: "cancelled"
128
+ });
129
+ }
130
+ executionKey(executionId) {
131
+ return `workflow:${this.options.name}:execution:${executionId}`;
132
+ }
133
+ metaKey(executionId) {
134
+ return `${this.executionKey(executionId)}:meta`;
135
+ }
136
+ stepsKey(executionId) {
137
+ return `${this.executionKey(executionId)}:steps`;
138
+ }
139
+ lockKey(executionId) {
140
+ return `${this.executionKey(executionId)}:lock`;
141
+ }
142
+ async createExecution(executionId, input) {
143
+ const [serializeError, serializedInput] = this.serializeInput(input);
144
+ if (serializeError) return err("WorkflowSerializationError", `Unable to serialize workflow input for ${executionId}`);
145
+ const timestamp = now();
146
+ const [statusReadError, existingStatus] = await this.getMeta(executionId, "status");
147
+ if (statusReadError) return err(statusReadError.type, statusReadError.message);
148
+ if (existingStatus) return err("WorkflowStateError", `Workflow execution ${executionId} already exists`);
149
+ const metadata = {
150
+ status: "pending",
151
+ input: serializedInput,
152
+ result: "",
153
+ error: "",
154
+ createdAt: String(timestamp),
155
+ updatedAt: String(timestamp),
156
+ completedAt: "",
157
+ failedAt: "",
158
+ cancelledAt: "",
159
+ steps: "[]"
160
+ };
161
+ const [writeError] = await mightThrow(this.options.redis.hset(this.metaKey(executionId), metadata));
162
+ if (writeError) return err("WorkflowError", `Unable to persist metadata for execution ${executionId}`);
163
+ return ok(null);
164
+ }
165
+ async execute(executionId, input) {
166
+ const token = crypto.randomUUID();
167
+ const [lockError] = await this.acquireLock(executionId, token);
168
+ if (lockError) return err(lockError.type, lockError.message);
169
+ const [statusCheckError, currentStatus] = await this.getMeta(executionId, "status");
170
+ if (statusCheckError) {
171
+ await this.releaseLock(executionId, token);
172
+ return err(statusCheckError.type, statusCheckError.message);
173
+ }
174
+ if (currentStatus === "cancelled") {
175
+ await this.releaseLock(executionId, token);
176
+ return err("WorkflowStateError", `Workflow execution ${executionId} was cancelled`);
177
+ }
178
+ const timestamp = now();
179
+ const [runningStatusError] = await this.setMeta(executionId, "status", "running");
180
+ if (runningStatusError) {
181
+ await this.releaseLock(executionId, token);
182
+ return err(runningStatusError.type, runningStatusError.message);
183
+ }
184
+ const [runningUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(timestamp));
185
+ if (runningUpdatedAtError) {
186
+ await this.releaseLock(executionId, token);
187
+ return err(runningUpdatedAtError.type, runningUpdatedAtError.message);
188
+ }
189
+ const controller = new AbortController();
190
+ const renewInterval = Math.floor(this.lockTTL / 3);
191
+ let lockLost = false;
192
+ const renewTimer = setInterval(async () => {
193
+ const [renewError] = await this.extendLock(executionId, token);
194
+ if (renewError) {
195
+ lockLost = true;
196
+ controller.abort();
197
+ clearInterval(renewTimer);
198
+ }
199
+ }, renewInterval);
200
+ const step = async (name, handler) => {
201
+ const [cancelledError, cancelled] = await this.isCancelled(executionId);
202
+ if (cancelledError) return Promise.reject(new Error(cancelledError.message));
203
+ if (cancelled) {
204
+ controller.abort();
205
+ return Promise.reject(/* @__PURE__ */ new Error("Workflow cancelled"));
206
+ }
207
+ const [readError, cachedStep] = await this.readStepOutput(executionId, name);
208
+ if (readError) return Promise.reject(new Error(readError.message));
209
+ if (cachedStep.found) return cachedStep.value;
210
+ const [stepError, output] = await mightThrow(Promise.resolve(handler(input, controller.signal)));
211
+ if (stepError) return Promise.reject(stepError);
212
+ const [writeError] = await this.writeStepOutput(executionId, name, output);
213
+ if (writeError) return Promise.reject(new Error(writeError.message));
214
+ return output;
215
+ };
216
+ const [handlerError, result] = await mightThrow(Promise.resolve(this.options.handler({
217
+ input,
218
+ executionId,
219
+ signal: controller.signal,
220
+ step
221
+ })));
222
+ clearInterval(renewTimer);
223
+ if (lockLost) {
224
+ await this.releaseLock(executionId, token);
225
+ return err("WorkflowLockError", `Lock expired during execution ${executionId}`);
226
+ }
227
+ const [cancelledError, cancelled] = await this.isCancelled(executionId);
228
+ if (cancelledError) {
229
+ await this.releaseLock(executionId, token);
230
+ return err(cancelledError.type, cancelledError.message);
231
+ }
232
+ if (cancelled) {
233
+ const cancelledAt = now();
234
+ const [cancelledStatusError] = await this.setMeta(executionId, "status", "cancelled");
235
+ if (cancelledStatusError) {
236
+ await this.releaseLock(executionId, token);
237
+ return err(cancelledStatusError.type, cancelledStatusError.message);
238
+ }
239
+ const [cancelledUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(cancelledAt));
240
+ if (cancelledUpdatedAtError) {
241
+ await this.releaseLock(executionId, token);
242
+ return err(cancelledUpdatedAtError.type, cancelledUpdatedAtError.message);
243
+ }
244
+ const [cancelledAtError] = await this.setMeta(executionId, "cancelledAt", String(cancelledAt));
245
+ if (cancelledAtError) {
246
+ await this.releaseLock(executionId, token);
247
+ return err(cancelledAtError.type, cancelledAtError.message);
248
+ }
249
+ await this.releaseLock(executionId, token);
250
+ return ok({
251
+ executionId,
252
+ status: "cancelled"
253
+ });
254
+ }
255
+ if (handlerError) {
256
+ const failedAt = now();
257
+ const [failedStatusError] = await this.setMeta(executionId, "status", "failed");
258
+ if (failedStatusError) {
259
+ await this.releaseLock(executionId, token);
260
+ return err(failedStatusError.type, failedStatusError.message);
261
+ }
262
+ const [failedMessageError] = await this.setMeta(executionId, "error", toErrorMessage(handlerError));
263
+ if (failedMessageError) {
264
+ await this.releaseLock(executionId, token);
265
+ return err(failedMessageError.type, failedMessageError.message);
266
+ }
267
+ const [failedUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(failedAt));
268
+ if (failedUpdatedAtError) {
269
+ await this.releaseLock(executionId, token);
270
+ return err(failedUpdatedAtError.type, failedUpdatedAtError.message);
271
+ }
272
+ const [failedAtError] = await this.setMeta(executionId, "failedAt", String(failedAt));
273
+ if (failedAtError) {
274
+ await this.releaseLock(executionId, token);
275
+ return err(failedAtError.type, failedAtError.message);
276
+ }
277
+ await this.releaseLock(executionId, token);
278
+ return err("WorkflowExecutionError", `Workflow execution ${executionId} failed: ${toErrorMessage(handlerError)}`);
279
+ }
280
+ const [serializeResultError, serializedResult] = this.serializeResult(result);
281
+ if (serializeResultError) {
282
+ const failedAt = now();
283
+ const [failedStatusError] = await this.setMeta(executionId, "status", "failed");
284
+ if (failedStatusError) {
285
+ await this.releaseLock(executionId, token);
286
+ return err(failedStatusError.type, failedStatusError.message);
287
+ }
288
+ const [failedMessageError] = await this.setMeta(executionId, "error", serializeResultError.message);
289
+ if (failedMessageError) {
290
+ await this.releaseLock(executionId, token);
291
+ return err(failedMessageError.type, failedMessageError.message);
292
+ }
293
+ const [failedUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(failedAt));
294
+ if (failedUpdatedAtError) {
295
+ await this.releaseLock(executionId, token);
296
+ return err(failedUpdatedAtError.type, failedUpdatedAtError.message);
297
+ }
298
+ const [failedAtError] = await this.setMeta(executionId, "failedAt", String(failedAt));
299
+ if (failedAtError) {
300
+ await this.releaseLock(executionId, token);
301
+ return err(failedAtError.type, failedAtError.message);
302
+ }
303
+ await this.releaseLock(executionId, token);
304
+ return err("WorkflowSerializationError", `Unable to serialize workflow result for ${executionId}`);
305
+ }
306
+ const completedAt = now();
307
+ const [completedResultError] = await this.setMeta(executionId, "result", serializedResult);
308
+ if (completedResultError) {
309
+ await this.releaseLock(executionId, token);
310
+ return err(completedResultError.type, completedResultError.message);
311
+ }
312
+ const [completedStatusError] = await this.setMeta(executionId, "status", "completed");
313
+ if (completedStatusError) {
314
+ await this.releaseLock(executionId, token);
315
+ return err(completedStatusError.type, completedStatusError.message);
316
+ }
317
+ const [completedClearErrorError] = await this.setMeta(executionId, "error", "");
318
+ if (completedClearErrorError) {
319
+ await this.releaseLock(executionId, token);
320
+ return err(completedClearErrorError.type, completedClearErrorError.message);
321
+ }
322
+ const [completedClearFailedAtError] = await this.setMeta(executionId, "failedAt", "");
323
+ if (completedClearFailedAtError) {
324
+ await this.releaseLock(executionId, token);
325
+ return err(completedClearFailedAtError.type, completedClearFailedAtError.message);
326
+ }
327
+ const [completedUpdatedAtError] = await this.setMeta(executionId, "updatedAt", String(completedAt));
328
+ if (completedUpdatedAtError) {
329
+ await this.releaseLock(executionId, token);
330
+ return err(completedUpdatedAtError.type, completedUpdatedAtError.message);
331
+ }
332
+ const [completedAtError] = await this.setMeta(executionId, "completedAt", String(completedAt));
333
+ if (completedAtError) {
334
+ await this.releaseLock(executionId, token);
335
+ return err(completedAtError.type, completedAtError.message);
336
+ }
337
+ await this.releaseLock(executionId, token);
338
+ return ok({
339
+ executionId,
340
+ status: "completed"
341
+ });
342
+ }
343
+ async acquireLock(executionId, token) {
344
+ const [lockError, lockResult] = await mightThrow(this.options.redis.set(this.lockKey(executionId), token, "PX", String(this.lockTTL), "NX"));
345
+ if (lockError) return err("WorkflowLockError", `Unable to acquire lock for execution ${executionId}`);
346
+ if (lockResult !== "OK") return err("WorkflowLockError", `Workflow execution ${executionId} is already running`);
347
+ return ok(null);
348
+ }
349
+ async releaseLock(executionId, token) {
350
+ const [evalError] = await mightThrow(this.options.redis.send("EVAL", [
351
+ "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end",
352
+ "1",
353
+ this.lockKey(executionId),
354
+ token
355
+ ]));
356
+ if (evalError) return err("WorkflowLockError", `Unable to release lock for execution ${executionId}`);
357
+ return ok(null);
358
+ }
359
+ async extendLock(executionId, token) {
360
+ const [evalError, result] = await mightThrow(this.options.redis.send("EVAL", [
361
+ "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end",
362
+ "1",
363
+ this.lockKey(executionId),
364
+ token,
365
+ String(this.lockTTL)
366
+ ]));
367
+ if (evalError) return err("WorkflowLockError", `Unable to extend lock for execution ${executionId}`);
368
+ if (result === 0) return err("WorkflowLockError", `Lock ownership lost for execution ${executionId}`);
369
+ return ok(null);
370
+ }
371
+ async isCancelled(executionId) {
372
+ const [statusError, status] = await this.getMeta(executionId, "status");
373
+ if (statusError) return err(statusError.type, statusError.message);
374
+ return ok(status === "cancelled");
375
+ }
376
+ async setMeta(executionId, field, value) {
377
+ const [writeError] = await mightThrow(this.options.redis.hset(this.metaKey(executionId), field, value));
378
+ if (writeError) return err("WorkflowError", `Unable to persist ${field} for execution ${executionId}`);
379
+ return ok(null);
380
+ }
381
+ async getMeta(executionId, field) {
382
+ const [readError, value] = await mightThrow(this.options.redis.hget(this.metaKey(executionId), field));
383
+ if (readError) return err("WorkflowError", `Unable to read ${field} for execution ${executionId}`);
384
+ if (value === null || value === void 0) return ok(null);
385
+ if (typeof value !== "string") return err("WorkflowStateError", `Invalid ${field} value for execution ${executionId}`);
386
+ if (value.length === 0) return ok(null);
387
+ return ok(value);
388
+ }
389
+ async readNumberMeta(executionId, field) {
390
+ const [readError, value] = await this.getMeta(executionId, field);
391
+ if (readError) return err(readError.type, readError.message);
392
+ if (!value) return ok(null);
393
+ const parsed = Number(value);
394
+ if (!Number.isFinite(parsed)) return err("WorkflowStateError", `Invalid ${field} value for execution ${executionId}`);
395
+ return ok(parsed);
396
+ }
397
+ runSerializer(value, serializer, label) {
398
+ const [serializeError, serialized] = mightThrowSync(() => serializer(value));
399
+ if (serializeError) return err("WorkflowSerializationError", `Unable to serialize ${label}: ${toErrorMessage(serializeError)}`);
400
+ if (typeof serialized !== "string") return err("WorkflowSerializationError", `${label} serializer must return a string`);
401
+ return ok(serialized);
402
+ }
403
+ runDeserializer(raw, deserializer, label) {
404
+ const [deserializeError, value] = mightThrowSync(() => deserializer(raw));
405
+ if (deserializeError) return err("WorkflowSerializationError", `Unable to deserialize ${label}: ${toErrorMessage(deserializeError)}`);
406
+ return ok(value);
407
+ }
408
+ serializeInput(input) {
409
+ return this.runSerializer(input, this.options.serializeInput ?? envelopeSerialize, "workflow input");
410
+ }
411
+ deserializeInput(raw) {
412
+ const deserializer = this.options.deserializeInput ?? ((value) => envelopeDeserialize(value));
413
+ return this.runDeserializer(raw, deserializer, "workflow input");
414
+ }
415
+ serializeResult(result) {
416
+ if (result === null) return ok(envelopeSerialize(null));
417
+ return this.runSerializer(result, this.options.serializeResult ?? envelopeSerialize, "workflow result");
418
+ }
419
+ deserializeResult(raw) {
420
+ const deserializer = this.options.deserializeResult ?? ((value) => envelopeDeserialize(value));
421
+ return this.runDeserializer(raw, deserializer, "workflow result");
422
+ }
423
+ serializeStepOutput(output) {
424
+ return this.runSerializer(output, this.options.serializeStepOutput ?? envelopeSerialize, "step output");
425
+ }
426
+ deserializeStepOutput(raw) {
427
+ const deserializer = this.options.deserializeStepOutput ?? ((value) => envelopeDeserialize(value));
428
+ return this.runDeserializer(raw, deserializer, "step output");
429
+ }
430
+ async readInput(executionId) {
431
+ const [readError, raw] = await this.getMeta(executionId, "input");
432
+ if (readError) return err(readError.type, readError.message);
433
+ if (!raw) return err("WorkflowStateError", `Workflow execution ${executionId} input not found`);
434
+ return this.deserializeInput(raw);
435
+ }
436
+ async readResult(executionId) {
437
+ const [readError, raw] = await this.getMeta(executionId, "result");
438
+ if (readError) return err(readError.type, readError.message);
439
+ if (!raw) return ok(null);
440
+ const [deserializeError, result] = this.deserializeResult(raw);
441
+ if (deserializeError) return err(deserializeError.type, deserializeError.message);
442
+ return ok(result);
443
+ }
444
+ async writeStepOutput(executionId, stepName, output) {
445
+ const [serializeError, serializedOutput] = this.serializeStepOutput(output);
446
+ if (serializeError) return err("WorkflowSerializationError", `Unable to serialize step ${stepName} output`);
447
+ const payload = {
448
+ output: serializedOutput,
449
+ completedAt: now()
450
+ };
451
+ const [payloadError, payloadRaw] = mightThrowSync(() => JSON.stringify(payload));
452
+ if (payloadError || typeof payloadRaw !== "string") return err("WorkflowSerializationError", `Unable to persist step ${stepName} output`);
453
+ const [writeError] = await mightThrow(this.options.redis.hset(this.stepsKey(executionId), stepName, payloadRaw));
454
+ if (writeError) return err("WorkflowError", `Unable to persist step ${stepName} for execution ${executionId}`);
455
+ const [stepNamesError, stepNames] = await this.readStepNames(executionId);
456
+ if (stepNamesError) return err(stepNamesError.type, stepNamesError.message);
457
+ if (!stepNames.includes(stepName)) {
458
+ const nextStepNames = [...stepNames, stepName];
459
+ const [serializeStepsError, serializedSteps] = mightThrowSync(() => JSON.stringify(nextStepNames));
460
+ if (serializeStepsError || typeof serializedSteps !== "string") return err("WorkflowSerializationError", `Unable to persist step history for execution ${executionId}`);
461
+ const [updateStepsError] = await this.setMeta(executionId, "steps", serializedSteps);
462
+ if (updateStepsError) return err(updateStepsError.type, updateStepsError.message);
463
+ }
464
+ const [updatedError] = await this.setMeta(executionId, "updatedAt", String(now()));
465
+ if (updatedError) return err(updatedError.type, updatedError.message);
466
+ return ok(null);
467
+ }
468
+ async readStepOutput(executionId, stepName) {
469
+ const [readError, payloadRaw] = await mightThrow(this.options.redis.hget(this.stepsKey(executionId), stepName));
470
+ if (readError) return err("WorkflowError", `Unable to read step ${stepName} for execution ${executionId}`);
471
+ if (!payloadRaw) return ok({
472
+ found: false,
473
+ value: null
474
+ });
475
+ if (typeof payloadRaw !== "string") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
476
+ const [parseError, parsed] = mightThrowSync(() => JSON.parse(payloadRaw));
477
+ if (parseError || parsed === null || typeof parsed !== "object") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
478
+ if (typeof parsed.output !== "string") return err("WorkflowStateError", `Invalid step output for ${stepName} in execution ${executionId}`);
479
+ const outputRaw = parsed.output;
480
+ const [deserializeError, value] = this.deserializeStepOutput(outputRaw);
481
+ if (deserializeError) return err(deserializeError.type, deserializeError.message);
482
+ return ok({
483
+ found: true,
484
+ value
485
+ });
486
+ }
487
+ async readStepNames(executionId) {
488
+ const [readError, stepsRaw] = await this.getMeta(executionId, "steps");
489
+ if (readError) return [readError, []];
490
+ if (!stepsRaw) return ok([]);
491
+ const [parseError, values] = mightThrowSync(() => JSON.parse(stepsRaw));
492
+ if (parseError || !Array.isArray(values)) return err("WorkflowStateError", `Invalid step index for execution ${executionId}`);
493
+ const stepNames = [];
494
+ for (const value of values) if (typeof value === "string") stepNames.push(value);
495
+ return ok(stepNames);
496
+ }
497
+ async readStepSnapshots(executionId) {
498
+ const [stepNamesError, stepNames] = await this.readStepNames(executionId);
499
+ if (stepNamesError) return [stepNamesError, []];
500
+ const steps = [];
501
+ for (const stepName of stepNames) {
502
+ const [readError, payloadRaw] = await mightThrow(this.options.redis.hget(this.stepsKey(executionId), stepName));
503
+ if (readError) return err("WorkflowError", `Unable to read step ${stepName} for execution ${executionId}`);
504
+ if (!payloadRaw) continue;
505
+ if (typeof payloadRaw !== "string") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
506
+ const [parseError, parsed] = mightThrowSync(() => JSON.parse(payloadRaw));
507
+ if (parseError || parsed === null || typeof parsed !== "object") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
508
+ if (typeof parsed.completedAt !== "number") return err("WorkflowStateError", `Invalid step payload for ${stepName} in execution ${executionId}`);
509
+ const completedAt = parsed.completedAt;
510
+ steps.push({
511
+ name: stepName,
512
+ completedAt
513
+ });
514
+ }
515
+ return ok(steps);
516
+ }
517
+ normalizeStatus(value) {
518
+ for (const status of knownStatuses) if (status === value) return status;
519
+ return null;
520
+ }
521
+ };
522
+ const defineWorkflow = (options) => {
523
+ const workflow = new WorkflowDefinition(options);
524
+ return {
525
+ start: (input, startOptions) => workflow.start(input, startOptions),
526
+ run: (input, startOptions) => workflow.run(input, startOptions),
527
+ resume: (executionId) => workflow.resume(executionId),
528
+ get: (executionId) => workflow.get(executionId),
529
+ cancel: (executionId) => workflow.cancel(executionId)
530
+ };
531
+ };
532
+ //#endregion
533
+ export { defineWorkflow };
package/package.json CHANGED
@@ -1,9 +1,16 @@
1
1
  {
2
2
  "name": "semola",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
4
4
  "description": "Zero-dependency TypeScript utilities for Bun. Type-safe APIs, Redis queues, pub/sub, i18n, caching & auth with tree-shakeable imports.",
5
5
  "type": "module",
6
+ "bin": {
7
+ "semola": "./dist/cli/index.js"
8
+ },
6
9
  "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ },
7
14
  "./errors": {
8
15
  "import": {
9
16
  "types": "./dist/lib/errors/index.d.mts",
@@ -85,8 +92,14 @@
85
92
  }
86
93
  },
87
94
  "./logging": {
88
- "import": "./dist/lib/logging/index.js",
89
- "types": "./dist/lib/logging/index.d.ts"
95
+ "import": {
96
+ "types": "./dist/lib/logging/index.d.mts",
97
+ "default": "./dist/lib/logging/index.mjs"
98
+ },
99
+ "require": {
100
+ "types": "./dist/lib/logging/index.d.cts",
101
+ "default": "./dist/lib/logging/index.cjs"
102
+ }
90
103
  },
91
104
  "./prompts": {
92
105
  "import": {
@@ -97,6 +110,16 @@
97
110
  "types": "./dist/lib/prompts/index.d.cts",
98
111
  "default": "./dist/lib/prompts/index.cjs"
99
112
  }
113
+ },
114
+ "./workflow": {
115
+ "import": {
116
+ "types": "./dist/lib/workflow/index.d.mts",
117
+ "default": "./dist/lib/workflow/index.mjs"
118
+ },
119
+ "require": {
120
+ "types": "./dist/lib/workflow/index.d.cts",
121
+ "default": "./dist/lib/workflow/index.cjs"
122
+ }
100
123
  }
101
124
  },
102
125
  "files": [
@@ -124,6 +147,9 @@
124
147
  "cron",
125
148
  "scheduler",
126
149
  "job-scheduler",
150
+ "workflow",
151
+ "durable-workflow",
152
+ "resumable-workflow",
127
153
  "i18n",
128
154
  "internationalization",
129
155
  "authorization",