@supacloud/commands 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @supacloud/commands
2
2
 
3
+ ## Schema and Execution Policies
4
+
5
+ `@supacloud/commands/typebox` exports `createTypeBoxTransactionalCommand`.
6
+ Pass `schemas: { input, result }` to derive both handler types and runtime
7
+ validation from TypeBox. The concrete store transaction type is retained,
8
+ including Drizzle `transaction.db`. Typed callers use `execute` / `lookup`;
9
+ transport adapters use `executeUnknown` / `lookupUnknown`. Both validate at
10
+ runtime without coercion, defaults or transforms.
11
+
12
+ `createExecutionPolicy` provides explicit cooperative timeouts, classified retries
13
+ and a circuit breaker per host-owned operation. Transactional commands accept
14
+ `executionPolicy` and forward an `AbortSignal` to the handler; pass it to drivers.
15
+ Read retries require classification as `retry` or `rolled-back`; command retries
16
+ require a driver-confirmed `rolled-back` failure. Unknown write outcomes and
17
+ external dispatches are never automatically retried. Recover via durable receipts.
18
+
19
+ Timeout requests cancellation but retains ownership until the driver settles.
20
+ An uncooperative driver can exceed the timeout. Transactional cancellation is
21
+ conservatively reported as `COMMAND_OUTCOME_UNKNOWN`, not proof of rollback.
22
+ Circuit `isFailure` should exclude authorization, schema and domain rejection.
23
+ Circuit state is local to the policy instance, not distributed.
24
+
3
25
  Storage-independent durable execution. Depends only on `@supacloud/contracts`;
4
26
  no SQL driver, HTTP server, Svelte lifecycle or scheduler is bundled.
5
27
 
package/dist/context.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type CommandAuthorization, type CommandIdentity, type ContractDecoder, type DurableCommandReceipt } from "@supacloud/contracts";
2
- import type { CommandStore, CommandStoreSession, OperationReference, StoredCommand } from "./store";
2
+ import type { CommandStore, CommandStoreSession, OperationReference, StoredCommand, ValidatedOperationReference } from "./store";
3
3
  export interface CommandInputCodec {
4
4
  encode(canonicalInput: string): string | Promise<string>;
5
5
  decode(payload: string): string | Promise<string>;
@@ -25,7 +25,7 @@ export interface PersistentCommandDefinition<Input, Result, Transaction> {
25
25
  };
26
26
  }
27
27
  interface Prepared<Input> {
28
- reference: OperationReference;
28
+ reference: ValidatedOperationReference;
29
29
  input: Input;
30
30
  fingerprint: string;
31
31
  payload: string;
@@ -0,0 +1,27 @@
1
+ export declare class ExecutionPolicyError extends Error {
2
+ readonly code: "CIRCUIT_OPEN" | "EXECUTION_ABORTED" | "EXECUTION_TIMEOUT" | "COMMAND_OUTCOME_UNKNOWN";
3
+ constructor(code: "CIRCUIT_OPEN" | "EXECUTION_ABORTED" | "EXECUTION_TIMEOUT" | "COMMAND_OUTCOME_UNKNOWN");
4
+ }
5
+ type RetryDecision = "retry" | "rolled-back" | "stop";
6
+ export interface ExecutionPolicyOptions {
7
+ kind: "read" | "command";
8
+ /** Cooperative cancellation. The operation must forward the signal to its driver. */
9
+ timeoutMs?: number;
10
+ retry?: {
11
+ maxAttempts: number;
12
+ delayMs: number;
13
+ /** Commands may retry only a driver-confirmed rollback, never an unknown outcome. */
14
+ classify(error: unknown): RetryDecision;
15
+ };
16
+ circuit?: {
17
+ failureThreshold: number;
18
+ resetAfterMs: number;
19
+ /** Exclude authorization, validation and business-rule rejection. */
20
+ isFailure(error: unknown): boolean;
21
+ };
22
+ }
23
+ /** One instance per named operation/authority boundary, explicitly constructed by the host. */
24
+ export declare function createExecutionPolicy(options: ExecutionPolicyOptions): Readonly<{
25
+ execute<Result>(run: (signal: AbortSignal) => Promise<Result>, parent?: AbortSignal): Promise<Result>;
26
+ }>;
27
+ export {};
@@ -3,6 +3,7 @@ import { type PersistentCommandDefinition, type RecoveryPrincipal } from "./cont
3
3
  import type { CommandStore, OperationReference } from "./store";
4
4
  export interface ExternalDispatch {
5
5
  idempotencyKey: string;
6
+ signal?: AbortSignal;
6
7
  }
7
8
  type TransactionOf<Store extends CommandStore<unknown>> = Store extends CommandStore<infer Transaction> ? Transaction : never;
8
9
  type ExternalCommandDefinition<Input, Result, Store extends CommandStore<unknown>> = Omit<PersistentCommandDefinition<Input, Result, TransactionOf<Store>>, "store"> & {
@@ -13,7 +14,7 @@ type ExternalCommandDefinition<Input, Result, Store extends CommandStore<unknown
13
14
  };
14
15
  export declare function createExternalCommand<Input, Result, Store extends CommandStore<unknown>>(definition: ExternalCommandDefinition<Input, Result, Store>): {
15
16
  kind: "external";
16
- execute(identity: CommandIdentity, key: string, value: unknown): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result>>;
17
+ execute(identity: CommandIdentity, key: string, value: unknown, signal?: AbortSignal): Promise<import("@supacloud/contracts").DurableCommandReceipt<Result>>;
17
18
  lookup: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
18
19
  reconcile: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
19
20
  flushAudit: (identity: CommandIdentity, key: string, value: unknown, principal?: RecoveryPrincipal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<Result> | null>;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createTransactionalCommand } from "./transactional";
2
+ export { createExecutionPolicy, ExecutionPolicyError, type ExecutionPolicyOptions } from "./execution-policy";
2
3
  export { createExternalCommand, type ExternalDispatch } from "./external";
3
4
  export { plaintextCommandInput, type CommandInputCodec, type PersistentCommandDefinition, type RecoveryPrincipal } from "./context";
4
5
  export { createCommandRecoveryHandler, type RecoverableCommand, type CommandWorkflowPort, type CommandWorkflowAttempt } from "./recovery";
package/dist/index.js CHANGED
@@ -1,12 +1,15 @@
1
1
  // src/transactional.ts
2
- import { CommandError as CommandError2, canonicalCommandJson as canonicalCommandJson2 } from "@supacloud/contracts";
2
+ import {
3
+ CommandError as CommandError2,
4
+ canonicalCommandJson as canonicalCommandJson2
5
+ } from "@supacloud/contracts";
3
6
 
4
7
  // src/context.ts
5
8
  import {
6
9
  CommandError,
7
10
  canonicalCommandJson,
8
11
  commandIdentifier,
9
- decodeCommandIdentity,
12
+ decodeValidatedCommandReference,
10
13
  decodeDurableCommandReceipt
11
14
  } from "@supacloud/contracts";
12
15
  var plaintextCommandInput = {
@@ -33,7 +36,14 @@ function commandContext(definition) {
33
36
  const name = commandIdentifier(definition.name), event = commandIdentifier(definition.audit.event);
34
37
  const reference = (identity, key) => {
35
38
  try {
36
- return { ...decodeCommandIdentity(identity), command: name, operationId: commandIdentifier(key) };
39
+ return {
40
+ ...decodeValidatedCommandReference({
41
+ ...identity,
42
+ command: name,
43
+ operationId: key,
44
+ dispatchKey: key
45
+ })
46
+ };
37
47
  } catch {
38
48
  throw new CommandError("COMMAND_INPUT_INVALID");
39
49
  }
@@ -141,26 +151,141 @@ function commandContext(definition) {
141
151
  return { prepare, lock, find, restore, transaction, audit, insert };
142
152
  }
143
153
 
154
+ // src/execution-policy.ts
155
+ class ExecutionPolicyError extends Error {
156
+ code;
157
+ constructor(code) {
158
+ super(code);
159
+ this.code = code;
160
+ this.name = "ExecutionPolicyError";
161
+ }
162
+ }
163
+ function createExecutionPolicy(options) {
164
+ const retry = options.retry ? { ...options.retry } : undefined;
165
+ const circuit = options.circuit ? { ...options.circuit } : undefined;
166
+ const { kind, timeoutMs } = options;
167
+ for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
168
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
169
+ throw new TypeError("Execution policy values must be positive bounded integers");
170
+ }
171
+ }
172
+ let failures = 0;
173
+ let openUntil = 0;
174
+ let probe = false;
175
+ let generation = 0;
176
+ return Object.freeze({
177
+ async execute(run, parent) {
178
+ if (parent?.aborted)
179
+ throw new ExecutionPolicyError("EXECUTION_ABORTED");
180
+ const halfOpen = openUntil !== 0;
181
+ if (halfOpen && (Date.now() < openUntil || probe))
182
+ throw new ExecutionPolicyError("CIRCUIT_OPEN");
183
+ if (halfOpen)
184
+ probe = true;
185
+ const currentGeneration = generation;
186
+ const controller = new AbortController;
187
+ let expired = false;
188
+ const abort = () => controller.abort();
189
+ parent?.addEventListener("abort", abort, { once: true });
190
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
191
+ expired = true;
192
+ controller.abort();
193
+ }, timeoutMs);
194
+ const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
195
+ try {
196
+ for (let attempt = 1;; attempt++) {
197
+ if (controller.signal.aborted)
198
+ throw cancelled();
199
+ try {
200
+ const result = await run(controller.signal);
201
+ if (controller.signal.aborted)
202
+ throw cancelled();
203
+ if (currentGeneration === generation) {
204
+ failures = 0;
205
+ if (halfOpen) {
206
+ openUntil = 0;
207
+ generation++;
208
+ }
209
+ }
210
+ return result;
211
+ } catch (error) {
212
+ if (controller.signal.aborted)
213
+ throw cancelled();
214
+ if (kind === "command" && error !== null && typeof error === "object" && "code" in error && error.code === "COMMAND_OUTCOME_UNKNOWN")
215
+ throw error;
216
+ if (!retry || halfOpen || attempt >= retry.maxAttempts)
217
+ throw error;
218
+ const decision = retry.classify(error);
219
+ if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
220
+ throw error;
221
+ await new Promise((resolve) => {
222
+ const done = () => {
223
+ clearTimeout(wait);
224
+ controller.signal.removeEventListener("abort", done);
225
+ resolve();
226
+ };
227
+ const wait = setTimeout(done, retry.delayMs);
228
+ controller.signal.addEventListener("abort", done, { once: true });
229
+ });
230
+ }
231
+ }
232
+ } catch (error) {
233
+ if (circuit && currentGeneration === generation) {
234
+ if (circuit.isFailure(error)) {
235
+ failures++;
236
+ if (halfOpen || failures >= circuit.failureThreshold) {
237
+ openUntil = Date.now() + circuit.resetAfterMs;
238
+ generation++;
239
+ }
240
+ } else if (halfOpen) {
241
+ openUntil = 0;
242
+ failures = 0;
243
+ generation++;
244
+ }
245
+ }
246
+ throw error;
247
+ } finally {
248
+ clearTimeout(timer);
249
+ parent?.removeEventListener("abort", abort);
250
+ if (halfOpen)
251
+ probe = false;
252
+ }
253
+ }
254
+ });
255
+ }
256
+
144
257
  // src/transactional.ts
145
258
  function createTransactionalCommand(definition) {
146
259
  const context = commandContext(definition);
260
+ const policy = createExecutionPolicy({ ...definition.executionPolicy, kind: "command" });
147
261
  return {
148
262
  kind: "transactional",
149
- async execute(identity, key, value) {
263
+ async execute(identity, key, value, signal) {
150
264
  const request = await context.prepare(identity, key, value);
151
- return context.transaction(async (session) => {
265
+ return policy.execute((signal) => context.transaction(async (session) => {
266
+ if (signal.aborted)
267
+ throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
152
268
  await context.lock(session, request);
153
269
  const existing = await context.find(session, request, "transactional");
154
270
  if (existing !== null)
155
271
  return existing;
156
- const raw = JSON.parse(canonicalCommandJson2(await definition.execute(session.transaction, request.input, request.reference)));
272
+ const raw = JSON.parse(canonicalCommandJson2(await definition.execute(session.transaction, request.input, request.reference, signal)));
157
273
  const result = definition.result(raw);
274
+ if (signal.aborted)
275
+ throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
158
276
  await context.insert(session, request, "transactional", { result: raw });
159
277
  await context.audit(session, request, result);
278
+ if (signal.aborted)
279
+ throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
160
280
  const receipt = await context.find(session, request, "transactional");
161
281
  if (receipt === null)
162
282
  throw new CommandError2("COMMAND_RECEIPT_INVALID");
163
283
  return receipt;
284
+ }), signal).catch((error) => {
285
+ if (error instanceof ExecutionPolicyError) {
286
+ throw new CommandError2(error.code === "COMMAND_OUTCOME_UNKNOWN" ? error.code : "COMMAND_UNAVAILABLE");
287
+ }
288
+ throw error;
164
289
  });
165
290
  },
166
291
  async lookup(identity, key, value) {
@@ -237,7 +362,9 @@ function createExternalCommand(definition) {
237
362
  };
238
363
  return {
239
364
  kind: "external",
240
- async execute(identity, key, value) {
365
+ async execute(identity, key, value, signal) {
366
+ if (signal?.aborted)
367
+ throw new CommandError3("COMMAND_UNAVAILABLE");
241
368
  const request = await context.prepare(identity, key, value);
242
369
  const acquired = await context.transaction(async (session) => {
243
370
  await context.lock(session, request);
@@ -253,7 +380,10 @@ function createExternalCommand(definition) {
253
380
  if (!acquired.fresh)
254
381
  return acquired.receipt;
255
382
  try {
256
- await definition.send(request.input, { idempotencyKey: acquired.receipt.dispatchKey });
383
+ await definition.send(request.input, {
384
+ idempotencyKey: acquired.receipt.dispatchKey,
385
+ ...signal === undefined ? {} : { signal }
386
+ });
257
387
  } catch {}
258
388
  try {
259
389
  const receipt = await reconcile(identity, key, request.input);
@@ -379,7 +509,9 @@ function createCommandRecoveryHandler(options) {
379
509
  };
380
510
  }
381
511
  export {
512
+ ExecutionPolicyError,
382
513
  createCommandRecoveryHandler,
514
+ createExecutionPolicy,
383
515
  createExternalCommand,
384
516
  createTransactionalCommand,
385
517
  plaintextCommandInput
package/dist/store.d.ts CHANGED
@@ -1 +1 @@
1
- export type { OperationReference, StoredCommand, CommandStoreSession, CommandStore, RecoveryScope, CommandRetentionStore, } from "@supacloud/contracts";
1
+ export type { OperationReference, ValidatedOperationReference, StoredCommand, CommandStoreSession, CommandStore, RecoveryScope, RecoveryClaim, CommandRecoveryStore, CommandRetentionStore, } from "@supacloud/contracts";
@@ -1,14 +1,16 @@
1
- import { type CommandIdentity, type DurableCommandReceipt } from "@supacloud/contracts";
1
+ import { type CommandIdentity, type DurableCommandReceipt, type ValidatedOperationReference } from "@supacloud/contracts";
2
2
  import { type PersistentCommandDefinition } from "./context";
3
3
  import type { CommandStore } from "./store";
4
+ import { type ExecutionPolicyOptions } from "./execution-policy";
4
5
  type TransactionOf<Store extends CommandStore<unknown>> = Store extends CommandStore<infer Transaction> ? Transaction : never;
5
6
  type TransactionalCommandDefinition<Input, Result, Store extends CommandStore<unknown>> = Omit<PersistentCommandDefinition<Input, Result, TransactionOf<Store>>, "store"> & {
7
+ executionPolicy?: Omit<ExecutionPolicyOptions, "kind">;
6
8
  store: Store;
7
- execute(transaction: TransactionOf<Store>, input: Input, identity: CommandIdentity): Promise<unknown>;
9
+ execute(transaction: TransactionOf<Store>, input: Input, identity: ValidatedOperationReference, signal: AbortSignal): Promise<unknown>;
8
10
  };
9
11
  export declare function createTransactionalCommand<Input, Result, Store extends CommandStore<unknown>>(definition: TransactionalCommandDefinition<Input, Result, Store>): {
10
12
  kind: "transactional";
11
- execute(identity: CommandIdentity, key: string, value: unknown): Promise<DurableCommandReceipt<Result>>;
13
+ execute(identity: CommandIdentity, key: string, value: unknown, signal?: AbortSignal): Promise<DurableCommandReceipt<Result>>;
12
14
  lookup(identity: CommandIdentity, key: string, value: unknown): Promise<DurableCommandReceipt<Result> | null>;
13
15
  lookupByReference(identity: CommandIdentity, key: string): Promise<DurableCommandReceipt<Result> | null>;
14
16
  };
@@ -0,0 +1,40 @@
1
+ import type { Static, TSchema } from "@sinclair/typebox";
2
+ import type { CommandIdentity } from "@supacloud/contracts";
3
+ import type { CommandStore } from "./store";
4
+ import type { PersistentCommandDefinition } from "./context";
5
+ import type { ExecutionPolicyOptions } from "./execution-policy";
6
+ type TransactionOf<Store extends CommandStore<unknown>> = Store extends CommandStore<infer Transaction> ? Transaction : never;
7
+ export interface TypeBoxCommandSchemas<InputSchema extends TSchema, ResultSchema extends TSchema> {
8
+ readonly input: InputSchema;
9
+ readonly result: ResultSchema;
10
+ }
11
+ export type TypeBoxCommandDefinition<InputSchema extends TSchema, ResultSchema extends TSchema, Store extends CommandStore<unknown>> = Omit<PersistentCommandDefinition<NoInfer<Static<InputSchema>>, NoInfer<Static<ResultSchema>>, NoInfer<TransactionOf<Store>>>, "store" | "input" | "result"> & {
12
+ readonly store: Store;
13
+ readonly executionPolicy?: Omit<ExecutionPolicyOptions, "kind">;
14
+ readonly schemas: TypeBoxCommandSchemas<InputSchema, ResultSchema>;
15
+ execute(transaction: NoInfer<TransactionOf<Store>>, input: NoInfer<Static<InputSchema>>, identity: CommandIdentity, signal: AbortSignal): Promise<NoInfer<Static<ResultSchema>>>;
16
+ };
17
+ /**
18
+ * Schema-first, JSON-preserving use case. Validation does not coerce, apply
19
+ * defaults or run TypeBox transforms; types describe the encoded JSON shape.
20
+ * Storage, authorization, receipts and audit stay with the existing executor.
21
+ */
22
+ export declare function createTypeBoxTransactionalCommand<const InputSchema extends TSchema, const ResultSchema extends TSchema, Store extends CommandStore<unknown>>(definition: TypeBoxCommandDefinition<InputSchema, ResultSchema, Store>): Readonly<{
23
+ kind: "transactional";
24
+ execute(identity: CommandIdentity, key: string, value: Static<InputSchema>, signal?: AbortSignal): Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
25
+ params: [];
26
+ })["static"]>>>;
27
+ lookup(identity: CommandIdentity, key: string, value: Static<InputSchema>): Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
28
+ params: [];
29
+ })["static"]>> | null>;
30
+ executeUnknown: (identity: CommandIdentity, key: string, value: unknown, signal?: AbortSignal) => Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
31
+ params: [];
32
+ })["static"]>>>;
33
+ lookupUnknown: (identity: CommandIdentity, key: string, value: unknown) => Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
34
+ params: [];
35
+ })["static"]>> | null>;
36
+ lookupByReference: (identity: CommandIdentity, key: string) => Promise<import("@supacloud/contracts").DurableCommandReceipt<NoInfer<(ResultSchema & {
37
+ params: [];
38
+ })["static"]>> | null>;
39
+ }>;
40
+ export {};
@@ -0,0 +1,344 @@
1
+ // src/typebox.ts
2
+ import { TypeCompiler } from "@sinclair/typebox/compiler";
3
+ import { Value } from "@sinclair/typebox/value";
4
+
5
+ // src/transactional.ts
6
+ import {
7
+ CommandError as CommandError2,
8
+ canonicalCommandJson as canonicalCommandJson2
9
+ } from "@supacloud/contracts";
10
+
11
+ // src/context.ts
12
+ import {
13
+ CommandError,
14
+ canonicalCommandJson,
15
+ commandIdentifier,
16
+ decodeValidatedCommandReference,
17
+ decodeDurableCommandReceipt
18
+ } from "@supacloud/contracts";
19
+ var plaintextCommandInput = {
20
+ encode: (value) => value,
21
+ decode: (value) => value
22
+ };
23
+ async function fingerprint(value) {
24
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
25
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
26
+ }
27
+ async function checkAuthorization(run) {
28
+ let decision;
29
+ try {
30
+ decision = await run();
31
+ } catch {
32
+ throw new CommandError("COMMAND_UNAVAILABLE");
33
+ }
34
+ if (decision === "deny")
35
+ throw new CommandError("COMMAND_REJECTED");
36
+ if (decision !== "allow")
37
+ throw new CommandError("COMMAND_UNAVAILABLE");
38
+ }
39
+ function commandContext(definition) {
40
+ const name = commandIdentifier(definition.name), event = commandIdentifier(definition.audit.event);
41
+ const reference = (identity, key) => {
42
+ try {
43
+ return {
44
+ ...decodeValidatedCommandReference({
45
+ ...identity,
46
+ command: name,
47
+ operationId: key,
48
+ dispatchKey: key
49
+ })
50
+ };
51
+ } catch {
52
+ throw new CommandError("COMMAND_INPUT_INVALID");
53
+ }
54
+ };
55
+ const prepare = async (identity, key, value) => {
56
+ const ref = reference(identity, key);
57
+ let input, canonical;
58
+ try {
59
+ canonical = canonicalCommandJson(definition.input(value));
60
+ const json = JSON.parse(canonical);
61
+ input = definition.input(json);
62
+ if (canonicalCommandJson(input) !== canonical)
63
+ throw new Error("Unstable input codec");
64
+ } catch {
65
+ throw new CommandError("COMMAND_INPUT_INVALID");
66
+ }
67
+ let payload;
68
+ try {
69
+ payload = await definition.inputCodec.encode(canonical);
70
+ } catch {
71
+ throw new CommandError("COMMAND_UNAVAILABLE");
72
+ }
73
+ if (typeof payload !== "string")
74
+ throw new CommandError("COMMAND_UNAVAILABLE");
75
+ return { reference: ref, input, fingerprint: await fingerprint(canonical), payload };
76
+ };
77
+ const authorize = async (session, request, principal) => {
78
+ if (principal !== undefined) {
79
+ commandIdentifier(principal.subject);
80
+ const authorizeRecovery = definition.authorizeRecovery;
81
+ if (!authorizeRecovery)
82
+ throw new CommandError("COMMAND_REJECTED");
83
+ await checkAuthorization(() => authorizeRecovery(principal, request.reference, session.transaction));
84
+ } else {
85
+ await checkAuthorization(() => definition.authorize(request.reference, request.input, session.transaction));
86
+ }
87
+ };
88
+ const lock = async (session, request, principal) => {
89
+ await session.lock(request.reference);
90
+ await authorize(session, request, principal);
91
+ };
92
+ const find = async (session, request, kind) => {
93
+ const stored = await session.read(request.reference);
94
+ if (stored === null)
95
+ return null;
96
+ if (stored.inputFingerprint !== request.fingerprint || stored.kind !== kind)
97
+ throw new CommandError("COMMAND_IDEMPOTENCY_CONFLICT");
98
+ try {
99
+ const receipt = decodeDurableCommandReceipt(stored.receipt, definition.result);
100
+ for (const key of ["tenantId", "actorId", "command", "operationId"]) {
101
+ if (receipt[key] !== request.reference[key])
102
+ throw new Error("Mismatched receipt");
103
+ }
104
+ if (kind === "transactional" && (receipt.status !== "confirmed" || receipt.audit !== "complete"))
105
+ throw new Error("Invalid receipt state");
106
+ return receipt;
107
+ } catch {
108
+ throw new CommandError("COMMAND_RECEIPT_INVALID");
109
+ }
110
+ };
111
+ const transaction = async (run) => {
112
+ try {
113
+ return await definition.store.transaction(run);
114
+ } catch (error) {
115
+ if (error instanceof CommandError)
116
+ throw error;
117
+ throw new CommandError("COMMAND_OUTCOME_UNKNOWN");
118
+ }
119
+ };
120
+ const restore = async (identity, key, principal) => {
121
+ const ref = reference(identity, key);
122
+ return transaction(async (session) => {
123
+ await session.lock(ref);
124
+ const stored = await session.read(ref);
125
+ if (stored === null)
126
+ return null;
127
+ if (stored.inputPayload === null)
128
+ throw new CommandError("COMMAND_INPUT_EXPIRED");
129
+ let json;
130
+ try {
131
+ const decoded = await definition.inputCodec.decode(stored.inputPayload);
132
+ if (typeof decoded !== "string")
133
+ throw new Error("Invalid payload");
134
+ json = JSON.parse(decoded);
135
+ } catch {
136
+ throw new CommandError("COMMAND_UNAVAILABLE");
137
+ }
138
+ const request = await prepare(identity, key, json);
139
+ if (request.fingerprint !== stored.inputFingerprint)
140
+ throw new CommandError("COMMAND_RECEIPT_INVALID");
141
+ await authorize(session, request, principal);
142
+ return request;
143
+ });
144
+ };
145
+ const audit = async (session, request, result) => {
146
+ const details = JSON.parse(canonicalCommandJson(definition.audit.details(request.input, result)));
147
+ await definition.audit.write?.(session.transaction, request.input, result);
148
+ await session.audit(request.reference, event, details);
149
+ };
150
+ const insert = async (session, request, kind, raw) => {
151
+ const reference = { ...request.reference, dispatchKey: crypto.randomUUID() };
152
+ const receipt = raw === undefined ? { ...reference, status: "pending", audit: "pending" } : { ...reference, status: "confirmed", audit: "complete", result: raw.result };
153
+ await session.insert({ receipt, kind, inputFingerprint: request.fingerprint, inputPayload: request.payload });
154
+ };
155
+ return { prepare, lock, find, restore, transaction, audit, insert };
156
+ }
157
+
158
+ // src/execution-policy.ts
159
+ class ExecutionPolicyError extends Error {
160
+ code;
161
+ constructor(code) {
162
+ super(code);
163
+ this.code = code;
164
+ this.name = "ExecutionPolicyError";
165
+ }
166
+ }
167
+ function createExecutionPolicy(options) {
168
+ const retry = options.retry ? { ...options.retry } : undefined;
169
+ const circuit = options.circuit ? { ...options.circuit } : undefined;
170
+ const { kind, timeoutMs } = options;
171
+ for (const value of [timeoutMs, retry?.maxAttempts, retry?.delayMs, circuit?.failureThreshold, circuit?.resetAfterMs]) {
172
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > 2147483647)) {
173
+ throw new TypeError("Execution policy values must be positive bounded integers");
174
+ }
175
+ }
176
+ let failures = 0;
177
+ let openUntil = 0;
178
+ let probe = false;
179
+ let generation = 0;
180
+ return Object.freeze({
181
+ async execute(run, parent) {
182
+ if (parent?.aborted)
183
+ throw new ExecutionPolicyError("EXECUTION_ABORTED");
184
+ const halfOpen = openUntil !== 0;
185
+ if (halfOpen && (Date.now() < openUntil || probe))
186
+ throw new ExecutionPolicyError("CIRCUIT_OPEN");
187
+ if (halfOpen)
188
+ probe = true;
189
+ const currentGeneration = generation;
190
+ const controller = new AbortController;
191
+ let expired = false;
192
+ const abort = () => controller.abort();
193
+ parent?.addEventListener("abort", abort, { once: true });
194
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
195
+ expired = true;
196
+ controller.abort();
197
+ }, timeoutMs);
198
+ const cancelled = () => new ExecutionPolicyError(kind === "command" ? "COMMAND_OUTCOME_UNKNOWN" : expired ? "EXECUTION_TIMEOUT" : "EXECUTION_ABORTED");
199
+ try {
200
+ for (let attempt = 1;; attempt++) {
201
+ if (controller.signal.aborted)
202
+ throw cancelled();
203
+ try {
204
+ const result = await run(controller.signal);
205
+ if (controller.signal.aborted)
206
+ throw cancelled();
207
+ if (currentGeneration === generation) {
208
+ failures = 0;
209
+ if (halfOpen) {
210
+ openUntil = 0;
211
+ generation++;
212
+ }
213
+ }
214
+ return result;
215
+ } catch (error) {
216
+ if (controller.signal.aborted)
217
+ throw cancelled();
218
+ if (kind === "command" && error !== null && typeof error === "object" && "code" in error && error.code === "COMMAND_OUTCOME_UNKNOWN")
219
+ throw error;
220
+ if (!retry || halfOpen || attempt >= retry.maxAttempts)
221
+ throw error;
222
+ const decision = retry.classify(error);
223
+ if (decision !== "rolled-back" && !(kind === "read" && decision === "retry"))
224
+ throw error;
225
+ await new Promise((resolve) => {
226
+ const done = () => {
227
+ clearTimeout(wait);
228
+ controller.signal.removeEventListener("abort", done);
229
+ resolve();
230
+ };
231
+ const wait = setTimeout(done, retry.delayMs);
232
+ controller.signal.addEventListener("abort", done, { once: true });
233
+ });
234
+ }
235
+ }
236
+ } catch (error) {
237
+ if (circuit && currentGeneration === generation) {
238
+ if (circuit.isFailure(error)) {
239
+ failures++;
240
+ if (halfOpen || failures >= circuit.failureThreshold) {
241
+ openUntil = Date.now() + circuit.resetAfterMs;
242
+ generation++;
243
+ }
244
+ } else if (halfOpen) {
245
+ openUntil = 0;
246
+ failures = 0;
247
+ generation++;
248
+ }
249
+ }
250
+ throw error;
251
+ } finally {
252
+ clearTimeout(timer);
253
+ parent?.removeEventListener("abort", abort);
254
+ if (halfOpen)
255
+ probe = false;
256
+ }
257
+ }
258
+ });
259
+ }
260
+
261
+ // src/transactional.ts
262
+ function createTransactionalCommand(definition) {
263
+ const context = commandContext(definition);
264
+ const policy = createExecutionPolicy({ ...definition.executionPolicy, kind: "command" });
265
+ return {
266
+ kind: "transactional",
267
+ async execute(identity, key, value, signal) {
268
+ const request = await context.prepare(identity, key, value);
269
+ return policy.execute((signal) => context.transaction(async (session) => {
270
+ if (signal.aborted)
271
+ throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
272
+ await context.lock(session, request);
273
+ const existing = await context.find(session, request, "transactional");
274
+ if (existing !== null)
275
+ return existing;
276
+ const raw = JSON.parse(canonicalCommandJson2(await definition.execute(session.transaction, request.input, request.reference, signal)));
277
+ const result = definition.result(raw);
278
+ if (signal.aborted)
279
+ throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
280
+ await context.insert(session, request, "transactional", { result: raw });
281
+ await context.audit(session, request, result);
282
+ if (signal.aborted)
283
+ throw new CommandError2("COMMAND_OUTCOME_UNKNOWN");
284
+ const receipt = await context.find(session, request, "transactional");
285
+ if (receipt === null)
286
+ throw new CommandError2("COMMAND_RECEIPT_INVALID");
287
+ return receipt;
288
+ }), signal).catch((error) => {
289
+ if (error instanceof ExecutionPolicyError) {
290
+ throw new CommandError2(error.code === "COMMAND_OUTCOME_UNKNOWN" ? error.code : "COMMAND_UNAVAILABLE");
291
+ }
292
+ throw error;
293
+ });
294
+ },
295
+ async lookup(identity, key, value) {
296
+ const request = await context.prepare(identity, key, value);
297
+ return context.transaction(async (session) => {
298
+ await context.lock(session, request);
299
+ return context.find(session, request, "transactional");
300
+ });
301
+ },
302
+ async lookupByReference(identity, key) {
303
+ const request = await context.restore(identity, key);
304
+ if (request === null)
305
+ return null;
306
+ return context.transaction(async (session) => {
307
+ await context.lock(session, request);
308
+ return context.find(session, request, "transactional");
309
+ });
310
+ }
311
+ };
312
+ }
313
+
314
+ // src/typebox.ts
315
+ function decoder(schema) {
316
+ const validator = TypeCompiler.Compile(Value.Clone(schema));
317
+ return (value) => {
318
+ if (!validator.Check(value))
319
+ throw new TypeError("Invalid command schema value");
320
+ return value;
321
+ };
322
+ }
323
+ function createTypeBoxTransactionalCommand(definition) {
324
+ const command = createTransactionalCommand({
325
+ ...definition,
326
+ input: decoder(definition.schemas.input),
327
+ result: decoder(definition.schemas.result)
328
+ });
329
+ return Object.freeze({
330
+ kind: command.kind,
331
+ execute(identity, key, value, signal) {
332
+ return command.execute(identity, key, value, signal);
333
+ },
334
+ lookup(identity, key, value) {
335
+ return command.lookup(identity, key, value);
336
+ },
337
+ executeUnknown: command.execute,
338
+ lookupUnknown: command.lookup,
339
+ lookupByReference: command.lookupByReference
340
+ });
341
+ }
342
+ export {
343
+ createTypeBoxTransactionalCommand
344
+ };
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@supacloud/commands",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Storage-independent durable command execution and recovery",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "exports": {
9
+ "./typebox": {
10
+ "types": "./dist/typebox.d.ts",
11
+ "import": "./dist/typebox.js"
12
+ },
9
13
  ".": {
10
14
  "types": "./dist/index.d.ts",
11
15
  "import": "./dist/index.js"
@@ -17,7 +21,7 @@
17
21
  ],
18
22
  "scripts": {
19
23
  "build": "bun run build:js && bun run build:types",
20
- "build:js": "bun build src/index.ts --outdir dist --target node --external @supacloud/contracts",
24
+ "build:js": "bun build src/index.ts src/typebox.ts --outdir dist --target node --external @supacloud/contracts --external @sinclair/typebox",
21
25
  "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
22
26
  "typecheck": "tsc -p tsconfig.json --noEmit",
23
27
  "typecheck:test": "tsc -p tsconfig.test.json --noEmit",
@@ -25,12 +29,21 @@
25
29
  "prepublishOnly": "bun run build"
26
30
  },
27
31
  "dependencies": {
28
- "@supacloud/contracts": "0.4.0"
32
+ "@supacloud/contracts": "0.5.0"
29
33
  },
30
34
  "devDependencies": {
35
+ "@sinclair/typebox": "0.34.52",
31
36
  "@types/bun": "1.4.2",
32
37
  "typescript": "7.0.2"
33
38
  },
39
+ "peerDependencies": {
40
+ "@sinclair/typebox": "0.34.52"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "@sinclair/typebox": {
44
+ "optional": true
45
+ }
46
+ },
34
47
  "license": "MIT",
35
48
  "repository": {
36
49
  "type": "git",