@restatedev/restate-sdk-gen 0.0.0 → 1.14.2

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/dist/index.js ADDED
@@ -0,0 +1,1078 @@
1
+ import * as restate from "@restatedev/restate-sdk";
2
+
3
+ //#region src/current.ts
4
+ let CURRENT = null;
5
+ /**
6
+ * Save the previous slot, install `value` as the current. Returns the
7
+ * previous value so `clearCurrent` can restore it (supports nested
8
+ * scheduler invocations on the same thread, even though we don't expect
9
+ * any in production).
10
+ */
11
+ function setCurrent(value) {
12
+ const prev = CURRENT;
13
+ CURRENT = value;
14
+ return prev;
15
+ }
16
+ /** Restore a slot previously captured by `setCurrent`. */
17
+ function clearCurrent(prev) {
18
+ CURRENT = prev;
19
+ }
20
+ /**
21
+ * Read the slot, throwing if no fiber is currently advancing. Callers
22
+ * cast the return type — the slot is intentionally `unknown` here so
23
+ * this module stays free of cycles.
24
+ */
25
+ function getCurrent() {
26
+ if (CURRENT === null) throw new Error("@restatedev/restate-sdk-gen: free-standing API called outside an active fiber. Call from inside `execute(ctx, gen(function*() { ... }))`.");
27
+ return CURRENT;
28
+ }
29
+
30
+ //#endregion
31
+ //#region src/free.ts
32
+ /**
33
+ * Read the active `RestateOperations` from the current-fiber slot.
34
+ * Throws if called outside a fiber's synchronous advance span (e.g.,
35
+ * at module init or inside an `ops.run` async closure that resolved
36
+ * after the fiber returned).
37
+ */
38
+ function currentOps() {
39
+ return getCurrent();
40
+ }
41
+ /**
42
+ * Run a side-effecting closure as a journal entry. See
43
+ * `RestateOperations.run` for full semantics.
44
+ *
45
+ * `name` is derived from `action.name` (works for named functions and
46
+ * arrow functions assigned to a `const`) or specified explicitly via
47
+ * `opts.name`. If neither resolves, throws.
48
+ */
49
+ const run = (action, opts) => currentOps().run(action, opts);
50
+ const sleep = (duration, name) => currentOps().sleep(duration, name);
51
+ const awakeable = (serde) => currentOps().awakeable(serde);
52
+ const resolveAwakeable = (id, payload, serde) => currentOps().resolveAwakeable(id, payload, serde);
53
+ const rejectAwakeable = (id, reason) => currentOps().rejectAwakeable(id, reason);
54
+ const signal = (name, serde) => currentOps().signal(name, serde);
55
+ const attach = (invocationId, serde) => currentOps().attach(invocationId, serde);
56
+ const serviceClient = (api) => currentOps().serviceClient(api);
57
+ const objectClient = (api, key) => currentOps().objectClient(api, key);
58
+ const workflowClient = (api, key) => currentOps().workflowClient(api, key);
59
+ const serviceSendClient = (api) => currentOps().serviceSendClient(api);
60
+ const objectSendClient = (api, key) => currentOps().objectSendClient(api, key);
61
+ const workflowSendClient = (api, key) => currentOps().workflowSendClient(api, key);
62
+ const genericCall = (call) => currentOps().genericCall(call);
63
+ const genericSend = (call) => currentOps().genericSend(call);
64
+ const cancel = (invocationId) => currentOps().cancel(invocationId);
65
+ const channel = () => currentOps().channel();
66
+ const state = () => currentOps().state();
67
+ const sharedState = () => currentOps().sharedState();
68
+ const workflowPromise = (name, serde) => currentOps().workflowPromise(name, serde);
69
+ /**
70
+ * Wait for every future to settle; return their values in input order.
71
+ * Heterogeneous-tuple typing — `all([fA, fB])` where `fA: Future<A>`
72
+ * and `fB: Future<B>` yields `Future<[A, B]>`. Mirrors `Promise.all`.
73
+ */
74
+ const all = (futures) => currentOps().all(futures);
75
+ /**
76
+ * Return the first future to settle; losers continue running but their
77
+ * results are discarded. Heterogeneous-tuple typing — `race([fA, fB])`
78
+ * yields `Future<A | B>`. Mirrors `Promise.race`.
79
+ */
80
+ const race = (futures) => currentOps().race(futures);
81
+ /**
82
+ * First-to-succeed wins (non-rejected). Rejects with `AggregateError(errors)`
83
+ * when every input rejects (including the empty input case). Tuple-aware —
84
+ * `any([fA, fB])` yields `Future<A | B>`. Mirrors `Promise.any`.
85
+ */
86
+ const any = (futures) => currentOps().any(futures);
87
+ /**
88
+ * Wait for every future to settle; never rejects. Tuple-aware —
89
+ * `allSettled([fA, fB])` yields
90
+ * `Future<[FutureSettledResult<A>, FutureSettledResult<B>]>`.
91
+ * Mirrors `Promise.allSettled`.
92
+ */
93
+ const allSettled = (futures) => currentOps().allSettled(futures);
94
+
95
+ //#endregion
96
+ //#region src/operation.ts
97
+ const opTag = Symbol("restateOperation");
98
+ function makePrimitive(node) {
99
+ const op = {
100
+ [opTag]: node,
101
+ *[Symbol.iterator]() {
102
+ return yield op;
103
+ }
104
+ };
105
+ return op;
106
+ }
107
+ function awaitRace(futures) {
108
+ const op = {
109
+ [opTag]: {
110
+ _tag: "AwaitRace",
111
+ futures
112
+ },
113
+ *[Symbol.iterator]() {
114
+ return yield op;
115
+ }
116
+ };
117
+ return op;
118
+ }
119
+ function gen(body) {
120
+ return { [Symbol.iterator]: body };
121
+ }
122
+ function spawn(op) {
123
+ return makePrimitive({
124
+ _tag: "Spawn",
125
+ child: op
126
+ });
127
+ }
128
+ function* select(branches) {
129
+ const tags = Object.keys(branches);
130
+ const tag = tags[(yield* awaitRace(tags.map((t) => branches[t]))).index];
131
+ return {
132
+ tag,
133
+ future: branches[tag]
134
+ };
135
+ }
136
+
137
+ //#endregion
138
+ //#region src/state.ts
139
+ /**
140
+ * Build a `State<TState>` over the given context. The runtime delegates
141
+ * straight to `ctx.get` / `ctx.set` / etc.; the TState generic is purely
142
+ * a TS-level convenience and gets erased at runtime.
143
+ *
144
+ * For shared (read-only) contexts, the returned State has the same
145
+ * runtime shape but the caller should use the `SharedState<TState>`
146
+ * type to drop the write methods. The convenience method
147
+ * `RestateOperations.sharedState()` does this cast.
148
+ */
149
+ function makeState(ctx, sched, adapt$1) {
150
+ const writeCtx = ctx;
151
+ return {
152
+ get(name, serde) {
153
+ return sched.makeJournalFuture(adapt$1(ctx.get(name, serde)));
154
+ },
155
+ keys() {
156
+ return sched.makeJournalFuture(adapt$1(ctx.stateKeys()));
157
+ },
158
+ set(name, value, serde) {
159
+ writeCtx.set(name, value, serde);
160
+ },
161
+ clear(name) {
162
+ writeCtx.clear(name);
163
+ },
164
+ clearAll() {
165
+ writeCtx.clearAll();
166
+ }
167
+ };
168
+ }
169
+
170
+ //#endregion
171
+ //#region src/clients.ts
172
+ /**
173
+ * Wrap an SDK `Client<M>` so each handler-invocation returns
174
+ * `Future<T>` (via the supplied `toFuture` adapter) instead of
175
+ * `InvocationPromise<T>`.
176
+ */
177
+ function wrapClient(client, toFuture) {
178
+ return new Proxy(client, { get(target, prop, receiver) {
179
+ const orig = Reflect.get(target, prop, receiver);
180
+ if (typeof orig !== "function") return orig;
181
+ return (...args) => {
182
+ return toFuture(orig.apply(target, args));
183
+ };
184
+ } });
185
+ }
186
+ /**
187
+ * Wrap an SDK `DurablePromise<T>` so each method returns `Future<...>`
188
+ * instead of `Promise<...>`/`RestatePromise<...>`.
189
+ */
190
+ function wrapDurablePromise(dp, toFuture) {
191
+ return {
192
+ peek: () => toFuture(dp.peek()),
193
+ resolve: (value) => toFuture(dp.resolve(value)),
194
+ reject: (errorMsg) => toFuture(dp.reject(errorMsg)),
195
+ get: () => toFuture(dp.get())
196
+ };
197
+ }
198
+
199
+ //#endregion
200
+ //#region src/default-lib.ts
201
+ const defaultLib = {
202
+ all(items) {
203
+ return restate.RestatePromise.all(items);
204
+ },
205
+ race(items) {
206
+ return restate.RestatePromise.race(items);
207
+ },
208
+ any(items) {
209
+ return restate.RestatePromise.any(items);
210
+ },
211
+ allSettled(items) {
212
+ return restate.RestatePromise.allSettled(items);
213
+ },
214
+ isCancellation(e) {
215
+ return e instanceof restate.CancelledError;
216
+ }
217
+ };
218
+
219
+ //#endregion
220
+ //#region src/future.ts
221
+ const futureBacking = Symbol("restateFutureBacking");
222
+ /**
223
+ * Internal accessor — read the backing off a Future. Only the scheduler
224
+ * and fiber call this; user code never sees Backing.
225
+ */
226
+ function getBacking(f) {
227
+ return f[futureBacking];
228
+ }
229
+ function makeFuture(backing) {
230
+ const future = {
231
+ [futureBacking]: backing,
232
+ *[Symbol.iterator]() {
233
+ return yield leafOp;
234
+ }
235
+ };
236
+ const leafOp = makePrimitive({
237
+ _tag: "Leaf",
238
+ future
239
+ });
240
+ return future;
241
+ }
242
+ function isJournalBacked(f) {
243
+ return getBacking(f).kind === "journal";
244
+ }
245
+
246
+ //#endregion
247
+ //#region src/fiber.ts
248
+ var Fiber = class {
249
+ it;
250
+ sched;
251
+ state = {
252
+ kind: "ready",
253
+ resume: null
254
+ };
255
+ waiters = [];
256
+ constructor(op, sched) {
257
+ this.it = op[Symbol.iterator]();
258
+ this.sched = sched;
259
+ }
260
+ isDone() {
261
+ return this.state.kind === "done";
262
+ }
263
+ /**
264
+ * For a fiber known to be done, return its settled outcome. Throws
265
+ * if called on a non-done fiber — callers must check `isDone()` first
266
+ * (or use `awaitCompletion` for the polymorphic version).
267
+ */
268
+ settledValue() {
269
+ if (this.state.kind !== "done") throw new Error("Fiber.settledValue called on non-done fiber");
270
+ return this.state.settled;
271
+ }
272
+ /**
273
+ * Returns the parked sources this fiber is currently racing against.
274
+ * Empty if the fiber is parked only on routine waiters (e.g.,
275
+ * waiting on a sibling fiber to finish), or in any non-parked state.
276
+ * The scheduler reads these to assemble its main-loop race.
277
+ */
278
+ parkedSources() {
279
+ return this.state.kind === "parked" ? this.state.promises : [];
280
+ }
281
+ /**
282
+ * "I want to be notified when this fiber is done." If the fiber is
283
+ * already done, returns its settled outcome immediately (caller
284
+ * should NOT also expect the waiter to be invoked). Otherwise
285
+ * returns null and queues the waiter for invocation when the fiber
286
+ * eventually finishes.
287
+ */
288
+ awaitCompletion(waiter) {
289
+ if (this.state.kind === "done") return this.state.settled;
290
+ this.waiters.push(waiter);
291
+ return null;
292
+ }
293
+ /**
294
+ * Wake this fiber with a resume value. Transitions to ready and
295
+ * notifies the scheduler. May be called from any state except done
296
+ * (waking a done fiber is a programming error and is ignored
297
+ * defensively).
298
+ */
299
+ wake(resume) {
300
+ if (this.state.kind === "done") return;
301
+ this.state = {
302
+ kind: "ready",
303
+ resume
304
+ };
305
+ this.sched.markReady(this);
306
+ }
307
+ /**
308
+ * Drive the fiber's iterator until it parks (yields a primitive
309
+ * whose dispatch ends with the fiber waiting on a source) or
310
+ * finishes (returns or throws).
311
+ *
312
+ * No-op if the fiber is not in the ready state — protects against
313
+ * stale entries in the scheduler's ready queue.
314
+ */
315
+ advance() {
316
+ if (this.state.kind !== "ready") return;
317
+ const prevSlot = setCurrent(this.sched.contextSlot);
318
+ try {
319
+ let resume = this.state.resume;
320
+ while (true) {
321
+ let next;
322
+ try {
323
+ next = stepIterator(this.it, resume);
324
+ } catch (e) {
325
+ this.finish({
326
+ ok: false,
327
+ e
328
+ });
329
+ return;
330
+ }
331
+ if (next.done) {
332
+ this.finish({
333
+ ok: true,
334
+ v: next.value
335
+ });
336
+ return;
337
+ }
338
+ const node = next.value[opTag];
339
+ let outcome;
340
+ switch (node._tag) {
341
+ case "Leaf":
342
+ outcome = this.parkOnLeaf(node);
343
+ break;
344
+ case "Spawn":
345
+ outcome = {
346
+ ok: true,
347
+ v: this.sched.spawnFuture(node.child)
348
+ };
349
+ break;
350
+ case "AwaitRace":
351
+ outcome = this.parkOnAwaitRace(node.futures);
352
+ break;
353
+ }
354
+ if (outcome === null) return;
355
+ resume = outcome;
356
+ }
357
+ } finally {
358
+ clearCurrent(prevSlot);
359
+ }
360
+ }
361
+ /**
362
+ * Park on a single Future, or short-circuit if the Future is already
363
+ * settled. Returns the Settled value to feed back into the iterator
364
+ * if a short-circuit is possible (routine-backed future whose target
365
+ * already finished); returns null if the fiber is parked and the
366
+ * caller should suspend.
367
+ */
368
+ parkOnLeaf(leaf) {
369
+ const backing = getBacking(leaf.future);
370
+ if (backing.kind === "journal") {
371
+ this.state = {
372
+ kind: "parked",
373
+ promises: [{
374
+ promise: backing.promise,
375
+ fire: (s) => this.wake(s)
376
+ }]
377
+ };
378
+ return null;
379
+ }
380
+ const settled = backing.target.awaitCompletion((s) => this.wake(s));
381
+ if (settled !== null) return settled;
382
+ this.state = {
383
+ kind: "parked",
384
+ promises: []
385
+ };
386
+ return null;
387
+ }
388
+ /**
389
+ * Park on the first-to-settle of a list of Futures, or short-circuit
390
+ * if any source is already settled. Returns `{index, settled}`
391
+ * (wrapped as Settled) on short-circuit, or null if parked.
392
+ *
393
+ * On the parked path, every source registers a one-shot fire
394
+ * callback that wakes the fiber with `{index, settled}`. The `won`
395
+ * flag guards against duplicate wakes when multiple sources settle
396
+ * in the same tick. Local sources (fibers, channels) park on the
397
+ * target's waiter list; journal sources race in the main loop's
398
+ * race promise.
399
+ */
400
+ parkOnAwaitRace(futures) {
401
+ for (let i = 0; i < futures.length; i++) {
402
+ const b = getBacking(futures[i]);
403
+ if (b.kind === "local" && b.target.isDone()) return {
404
+ ok: true,
405
+ v: {
406
+ index: i,
407
+ settled: b.target.settledValue()
408
+ }
409
+ };
410
+ }
411
+ let won = false;
412
+ const promises = [];
413
+ for (let i = 0; i < futures.length; i++) {
414
+ const idx = i;
415
+ const b = getBacking(futures[i]);
416
+ const fireOnce = (settled) => {
417
+ if (won) return;
418
+ won = true;
419
+ this.wake({
420
+ ok: true,
421
+ v: {
422
+ index: idx,
423
+ settled
424
+ }
425
+ });
426
+ };
427
+ if (b.kind === "local") b.target.awaitCompletion(fireOnce);
428
+ else promises.push({
429
+ promise: b.promise,
430
+ fire: fireOnce
431
+ });
432
+ }
433
+ this.state = {
434
+ kind: "parked",
435
+ promises
436
+ };
437
+ return null;
438
+ }
439
+ /**
440
+ * Iterator finished or threw. Transition to done, fire all waiters
441
+ * with the settled outcome, notify scheduler.
442
+ */
443
+ finish(settled) {
444
+ this.state = {
445
+ kind: "done",
446
+ settled
447
+ };
448
+ const waiters = this.waiters;
449
+ this.waiters = [];
450
+ for (const w of waiters) w(settled);
451
+ this.sched.markDone(this);
452
+ }
453
+ };
454
+ /**
455
+ * Drive a generator iterator one step, feeding it whatever value or
456
+ * exception the caller is resuming with. `resume === null` is the
457
+ * very first step; `{ok: true, v}` resumes with a value; `{ok: false,
458
+ * e}` throws into the iterator (or, if the iterator has no `throw`
459
+ * method, rethrows so the fiber fails).
460
+ */
461
+ function stepIterator(it, resume) {
462
+ if (resume === null) return it.next(void 0);
463
+ if (resume.ok) return it.next(resume.v);
464
+ if (it.throw) return it.throw(resume.e);
465
+ throw resume.e;
466
+ }
467
+
468
+ //#endregion
469
+ //#region src/channel.ts
470
+ var ChannelImpl = class {
471
+ state = { kind: "pending" };
472
+ waiters = [];
473
+ fire(value) {
474
+ if (this.state.kind === "settled") return;
475
+ this.state = {
476
+ kind: "settled",
477
+ value
478
+ };
479
+ const ws = this.waiters;
480
+ this.waiters = [];
481
+ const settled = {
482
+ ok: true,
483
+ v: value
484
+ };
485
+ for (const w of ws) w(settled);
486
+ }
487
+ isDone() {
488
+ return this.state.kind === "settled";
489
+ }
490
+ settledValue() {
491
+ if (this.state.kind !== "settled") throw new Error("ChannelImpl.settledValue called on a pending channel");
492
+ return {
493
+ ok: true,
494
+ v: this.state.value
495
+ };
496
+ }
497
+ awaitCompletion(waiter) {
498
+ if (this.state.kind === "settled") return {
499
+ ok: true,
500
+ v: this.state.value
501
+ };
502
+ this.waiters.push(waiter);
503
+ return null;
504
+ }
505
+ };
506
+ function makeChannel() {
507
+ const impl = new ChannelImpl();
508
+ return {
509
+ send: (v) => gen(function* () {
510
+ impl.fire(v);
511
+ }),
512
+ receive: makeFuture({
513
+ kind: "local",
514
+ target: impl
515
+ })
516
+ };
517
+ }
518
+
519
+ //#endregion
520
+ //#region src/scheduler.ts
521
+ var Scheduler = class {
522
+ fibers = /* @__PURE__ */ new Set();
523
+ ready = [];
524
+ lib;
525
+ abortController = new AbortController();
526
+ /**
527
+ * Slot for the RestateOperations bound to this scheduler. Set by
528
+ * `execute()` after construction (we can't pass it into the ctor
529
+ * because RestateOperations needs the scheduler to construct itself).
530
+ * `Fiber.advance` publishes this to the module-level current-fiber
531
+ * slot read by free-standing API functions. Typed `unknown` here to
532
+ * keep this module independent of `restate-operations.ts`.
533
+ */
534
+ contextSlot = null;
535
+ constructor(lib) {
536
+ this.lib = lib;
537
+ }
538
+ /**
539
+ * The scheduler's current AbortSignal. Aborts when invocation
540
+ * cancellation is observed (the SDK rejects the main race promise
541
+ * with TerminalError). After cancellation has been delivered to
542
+ * fibers and the scheduler has resumed, this getter returns a
543
+ * *fresh* signal — one that is not aborted, even though the previous
544
+ * cancel was just delivered.
545
+ *
546
+ * Pass `signal` to AbortSignal-aware APIs in `ops.run` closures
547
+ * (e.g. `fetch(url, {signal})`) so they cancel promptly when the
548
+ * surrounding work is cancelled. Cleanup closures yielded after a
549
+ * caught CancelledError get a fresh, unaborted signal — so they can
550
+ * do real work and only abort if a *new* cancellation arrives.
551
+ */
552
+ get abortSignal() {
553
+ return this.abortController.signal;
554
+ }
555
+ markReady(f) {
556
+ this.ready.push(f);
557
+ }
558
+ markDone(f) {
559
+ this.fibers.delete(f);
560
+ }
561
+ spawnFuture(op) {
562
+ return makeFuture({
563
+ kind: "local",
564
+ target: this.createFiber(op)
565
+ });
566
+ }
567
+ createFiber(op) {
568
+ const f = new Fiber(op, this);
569
+ this.fibers.add(f);
570
+ this.ready.push(f);
571
+ return f;
572
+ }
573
+ makeJournalFuture(promise) {
574
+ return makeFuture({
575
+ kind: "journal",
576
+ promise
577
+ });
578
+ }
579
+ /**
580
+ * Spawn an operation as a fresh fiber and return a Future that
581
+ * resolves with its eventual value. Same as the SchedulerOps method;
582
+ * exposed publicly for external callers (combinator helpers, the
583
+ * main run() entry point).
584
+ */
585
+ spawnDetached(op) {
586
+ return this.spawnFuture(op);
587
+ }
588
+ /**
589
+ * Construct a single-shot in-memory channel. Send must be called from
590
+ * a fiber currently advancing under this scheduler. See `channel.ts`
591
+ * for full semantics.
592
+ */
593
+ makeChannel() {
594
+ return makeChannel();
595
+ }
596
+ /**
597
+ * Combinator over Futures. Fast path when every input is journal-
598
+ * backed: use the lib's all/race for a single combinator entry.
599
+ * Otherwise, fall back to a synthesized fiber that yields each in
600
+ * turn.
601
+ *
602
+ * Tuple-aware typing (mirrors `Promise.all` in the standard lib):
603
+ * `all([fA, fB])` where `fA: Future<A>` and `fB: Future<B>`
604
+ * yields `Future<[A, B]>`, not `Future<(A | B)[]>`. The `const T`
605
+ * lets TS infer a tuple from a literal array.
606
+ */
607
+ all(futures) {
608
+ const fs = futures;
609
+ if (fs.every(isJournalBacked)) {
610
+ const promises = fs.map((f) => f[futureBacking].promise);
611
+ return this.makeJournalFuture(this.lib.all(promises));
612
+ }
613
+ return this.spawnDetached(gen(function* () {
614
+ const out = new Array(fs.length);
615
+ for (let i = 0; i < fs.length; i++) out[i] = yield* fs[i];
616
+ return out;
617
+ }));
618
+ }
619
+ race(futures) {
620
+ const fs = futures;
621
+ return this.spawnDetached(gen(function* () {
622
+ const result = yield* awaitRace(fs);
623
+ if (result.settled.ok) return result.settled.v;
624
+ throw result.settled.e;
625
+ }));
626
+ }
627
+ /**
628
+ * First-success combinator. Mirrors `Promise.any` /
629
+ * `RestatePromise.any`: settles with the first input that succeeds
630
+ * (non-rejected); rejects with `AggregateError(errors)` when every
631
+ * input rejects (including the empty-array case).
632
+ *
633
+ * Fast path collapses to a single `lib.any` over journal awaitables.
634
+ * Fallback synthesizes a fiber that loops `awaitAnyOf` over the
635
+ * still-pending subset, accumulating rejections in input order until
636
+ * one input fulfills or all have rejected.
637
+ *
638
+ * Tuple-aware: `any([fA, fB])` where `fA: Future<A>` and `fB:
639
+ * Future<B>` yields `Future<A | B>` (the union of slot types), same
640
+ * shape as `Promise.any`.
641
+ */
642
+ any(futures) {
643
+ const fs = futures;
644
+ if (fs.every(isJournalBacked)) {
645
+ const promises = fs.map((f) => f[futureBacking].promise);
646
+ return this.makeJournalFuture(this.lib.any(promises));
647
+ }
648
+ return this.spawnDetached(gen(function* () {
649
+ const errors = new Array(fs.length);
650
+ const remaining = /* @__PURE__ */ new Set();
651
+ for (let i = 0; i < fs.length; i++) remaining.add(i);
652
+ while (remaining.size > 0) {
653
+ const liveIdx = Array.from(remaining);
654
+ const result = yield* awaitRace(liveIdx.map((i) => fs[i]));
655
+ const original = liveIdx[result.index];
656
+ if (result.settled.ok) return result.settled.v;
657
+ errors[original] = result.settled.e;
658
+ remaining.delete(original);
659
+ }
660
+ throw new AggregateError(errors, "All promises were rejected");
661
+ }));
662
+ }
663
+ /**
664
+ * Settle-all combinator. Mirrors `Promise.allSettled` /
665
+ * `RestatePromise.allSettled`: resolves with an array of
666
+ * `FutureSettledResult` in input order, never rejects.
667
+ *
668
+ * Fast path collapses to a single `lib.allSettled`. Fallback yields
669
+ * each Future in turn — safe because Futures are eager (already in
670
+ * flight); sequential harvesting just reads them as they complete
671
+ * without blocking concurrency.
672
+ *
673
+ * Tuple-aware: `allSettled([fA, fB])` yields
674
+ * `Future<[FutureSettledResult<A>, FutureSettledResult<B>]>`.
675
+ */
676
+ allSettled(futures) {
677
+ const fs = futures;
678
+ if (fs.every(isJournalBacked)) {
679
+ const promises = fs.map((f) => f[futureBacking].promise);
680
+ return this.makeJournalFuture(this.lib.allSettled(promises));
681
+ }
682
+ return this.spawnDetached(gen(function* () {
683
+ const out = new Array(fs.length);
684
+ for (let i = 0; i < fs.length; i++) try {
685
+ out[i] = {
686
+ status: "fulfilled",
687
+ value: yield* fs[i]
688
+ };
689
+ } catch (reason) {
690
+ out[i] = {
691
+ status: "rejected",
692
+ reason
693
+ };
694
+ }
695
+ return out;
696
+ }));
697
+ }
698
+ drainReady() {
699
+ while (this.ready.length > 0) this.ready.shift().advance();
700
+ }
701
+ /**
702
+ * Run an operation to completion. Drain the ready queue, then loop:
703
+ * collect every PromiseSource from every parked fiber, race them,
704
+ * dispatch the winner via its fire callback, drain. Stop when no
705
+ * fiber is alive.
706
+ */
707
+ async run(op) {
708
+ const main = this.createFiber(op);
709
+ this.drainReady();
710
+ while (this.fibers.size > 0) {
711
+ const items = [];
712
+ for (const f of this.fibers) for (const src of f.parkedSources()) items.push(src);
713
+ if (items.length === 0) throw new Error("scheduler stuck: live fibers but nothing pending on a journal promise");
714
+ const tagged = items.map(({ promise }, i$1) => promise.map((v, e) => e !== void 0 ? {
715
+ i: i$1,
716
+ ok: false,
717
+ e
718
+ } : {
719
+ i: i$1,
720
+ ok: true,
721
+ v
722
+ }));
723
+ let raceWinner;
724
+ try {
725
+ raceWinner = await this.lib.race(tagged);
726
+ } catch (e) {
727
+ if (this.lib.isCancellation(e)) {
728
+ this.abortController.abort(e);
729
+ this.abortController = new AbortController();
730
+ }
731
+ const errSettled = {
732
+ ok: false,
733
+ e
734
+ };
735
+ for (const it of items) it.fire(errSettled);
736
+ this.drainReady();
737
+ continue;
738
+ }
739
+ const { i,...settledFields } = raceWinner;
740
+ const settled = settledFields.ok ? {
741
+ ok: true,
742
+ v: settledFields.v
743
+ } : {
744
+ ok: false,
745
+ e: settledFields.e
746
+ };
747
+ items[i].fire(settled);
748
+ this.drainReady();
749
+ }
750
+ if (!main.isDone()) throw new Error("scheduler exited but main fiber never completed");
751
+ const final = main.settledValue();
752
+ if (final.ok) return final.v;
753
+ throw final.e;
754
+ }
755
+ };
756
+
757
+ //#endregion
758
+ //#region src/restate-operations.ts
759
+ function adapt(p) {
760
+ return p;
761
+ }
762
+ /**
763
+ * Wrap a user-supplied `run` closure to surface the abort reason
764
+ * (typically a TerminalError(CANCELLED)) on throw paths if the signal
765
+ * aborted during execution. This converts AbortError (and any other
766
+ * abort-caused failure) into the canonical cancellation TerminalError
767
+ * for journal recording.
768
+ *
769
+ * Defensive coercion: if `signal.reason` is itself not a TerminalError
770
+ * (which shouldn't happen in production but might during testing or
771
+ * with non-cancellation race rejections), we wrap it in one. The
772
+ * journal must record a *terminal* outcome to avoid retries against
773
+ * a cancelled invocation.
774
+ *
775
+ * Exposed for testing — the wrapper's behavior is the part that has
776
+ * semantic bite, separate from the ctx.run plumbing.
777
+ */
778
+ function wrapActionForCancellation(signal$1, action) {
779
+ return async () => {
780
+ try {
781
+ return await action({ signal: signal$1 });
782
+ } catch (e) {
783
+ if (signal$1.aborted) throw asTerminalError(signal$1.reason);
784
+ throw e;
785
+ }
786
+ };
787
+ }
788
+ /**
789
+ * Resolve the journal-entry name; throw `TerminalError` if neither
790
+ * source provides one.
791
+ *
792
+ * `TerminalError` (not a plain `Error`) because a missing name is a
793
+ * programming bug — retrying the invocation will hit the same code
794
+ * path and fail the same way. The SDK treats terminal errors as
795
+ * non-retryable; the invocation fails fast instead of looping.
796
+ */
797
+ function resolveRunName(action, opts) {
798
+ const fromOpts = opts?.name?.trim();
799
+ if (fromOpts) return fromOpts;
800
+ const fromFn = action.name;
801
+ if (fromFn) return fromFn;
802
+ throw new restate.TerminalError("@restatedev/restate-sdk-gen: run() requires a journal-entry name. Either pass a named function (`run(myFn)`) or supply `{ name: '...' }` in the second argument.");
803
+ }
804
+ /** Translate our `RetryOptions` into the SDK's flat `RunOptions` shape. */
805
+ function toSdkRunOptions(opts) {
806
+ const out = {};
807
+ if (opts?.serde !== void 0) out.serde = opts.serde;
808
+ const r = opts?.retry;
809
+ if (r) {
810
+ if (r.maxAttempts !== void 0) out.maxRetryAttempts = r.maxAttempts;
811
+ if (r.maxDuration !== void 0) out.maxRetryDuration = r.maxDuration;
812
+ if (r.initialInterval !== void 0) out.initialRetryInterval = r.initialInterval;
813
+ if (r.maxInterval !== void 0) out.maxRetryInterval = r.maxInterval;
814
+ if (r.intervalFactor !== void 0) out.retryIntervalFactor = r.intervalFactor;
815
+ }
816
+ return out;
817
+ }
818
+ function asTerminalError(reason) {
819
+ if (reason instanceof restate.TerminalError) return reason;
820
+ return new restate.CancelledError();
821
+ }
822
+ var RestateOperations = class {
823
+ ctx;
824
+ sched;
825
+ constructor(context, sched) {
826
+ this.ctx = context;
827
+ this.sched = sched;
828
+ }
829
+ toFuture(p) {
830
+ return this.sched.makeJournalFuture(adapt(p));
831
+ }
832
+ /**
833
+ * Run a side-effecting closure as a journal entry.
834
+ *
835
+ * The closure receives `{ signal }` — an AbortSignal that fires when
836
+ * invocation cancellation arrives. Pass it into AbortSignal-aware
837
+ * APIs (e.g. `fetch(url, { signal })`) to abort in-flight syscalls.
838
+ *
839
+ * `name` is the journal entry's stable identifier (must be
840
+ * deterministic across replay). It can come from either:
841
+ *
842
+ * - `opts.name` — explicit override
843
+ * - `action.name` — the function's own name (works for `function`
844
+ * declarations and arrow functions assigned to a `const`,
845
+ * since JS infers names from the binding site)
846
+ *
847
+ * If neither resolves, `run` throws.
848
+ *
849
+ * @example Named function — name derived
850
+ * async function fetchUser({ signal }: RunActionOpts): Promise<User> {
851
+ * const r = await fetch(`/users/${id}`, { signal });
852
+ * return r.json();
853
+ * }
854
+ * yield* run(fetchUser);
855
+ *
856
+ * @example Named arrow — name derived from binding
857
+ * const fetchUser = async ({ signal }: RunActionOpts) => { ... };
858
+ * yield* run(fetchUser);
859
+ *
860
+ * @example Inline arrow — name explicit
861
+ * yield* run(async ({ signal }) => fetch(url, { signal }), { name: "fetch" });
862
+ *
863
+ * @example With retry policy
864
+ * yield* run(fetchUser, { retry: { maxAttempts: 3 } });
865
+ *
866
+ * Cancellation hygiene: if the closure throws while the signal is
867
+ * aborted, we rethrow `signal.reason` (the original TerminalError)
868
+ * instead of whatever the closure threw. This ensures the journal
869
+ * entry records `TerminalError(CANCELLED)` rather than `AbortError`.
870
+ */
871
+ run(action, opts) {
872
+ const name = resolveRunName(action, opts);
873
+ const wrapped = wrapActionForCancellation(this.sched.abortSignal, action);
874
+ return this.sched.makeJournalFuture(adapt(this.ctx.run(name, wrapped, toSdkRunOptions(opts))));
875
+ }
876
+ sleep(duration, name) {
877
+ return this.sched.makeJournalFuture(adapt(this.ctx.sleep(duration, name)));
878
+ }
879
+ awakeable(serde) {
880
+ const { id, promise } = this.ctx.awakeable(serde);
881
+ return {
882
+ id,
883
+ promise: this.sched.makeJournalFuture(adapt(promise))
884
+ };
885
+ }
886
+ resolveAwakeable(id, payload, serde) {
887
+ this.ctx.resolveAwakeable(id, payload, serde);
888
+ }
889
+ rejectAwakeable(id, reason) {
890
+ this.ctx.rejectAwakeable(id, reason);
891
+ }
892
+ signal(name, serde) {
893
+ return this.sched.makeJournalFuture(adapt(this.ctx.signal(name, serde)));
894
+ }
895
+ attach(invocationId, serde) {
896
+ return this.sched.makeJournalFuture(adapt(this.ctx.attach(invocationId, serde)));
897
+ }
898
+ /**
899
+ * Typed RPC client for a service: `ops.serviceClient(api).foo(arg)`
900
+ * yields a `Future<T>` whose value is the handler's return value.
901
+ *
902
+ * Same shape as `ctx.serviceClient(api)` from the SDK, but each
903
+ * handler-method returns `Future<T>` rather than `InvocationPromise<T>`.
904
+ */
905
+ serviceClient(api) {
906
+ return wrapClient(this.ctx.serviceClient(api), (p) => this.toFuture(p));
907
+ }
908
+ /** Typed RPC client for a virtual object. See {@link serviceClient}. */
909
+ objectClient(api, key) {
910
+ return wrapClient(this.ctx.objectClient(api, key), (p) => this.toFuture(p));
911
+ }
912
+ /** Typed RPC client for a workflow. See {@link serviceClient}. */
913
+ workflowClient(api, key) {
914
+ return wrapClient(this.ctx.workflowClient(api, key), (p) => this.toFuture(p));
915
+ }
916
+ serviceSendClient(api) {
917
+ return this.ctx.serviceSendClient(api);
918
+ }
919
+ objectSendClient(api, key) {
920
+ return this.ctx.objectSendClient(api, key);
921
+ }
922
+ workflowSendClient(api, key) {
923
+ return this.ctx.workflowSendClient(api, key);
924
+ }
925
+ genericCall(call) {
926
+ return this.toFuture(this.ctx.genericCall(call));
927
+ }
928
+ genericSend(call) {
929
+ return this.ctx.genericSend(call);
930
+ }
931
+ /**
932
+ * Cancel another invocation by its id. To observe cancellation
933
+ * arriving at *this* invocation, catch the `TerminalError` thrown by
934
+ * the next `yield*` boundary or use the `signal` exposed inside
935
+ * `ops.run` closures.
936
+ */
937
+ cancel(invocationId) {
938
+ this.ctx.cancel(invocationId);
939
+ }
940
+ /**
941
+ * Workflow-bound durable promise. Use only inside a workflow handler
942
+ * (the underlying context must be `WorkflowContext` or
943
+ * `WorkflowSharedContext`). Returns a wrapper whose `peek`/`get`/
944
+ * `resolve`/`reject` methods return Futures.
945
+ */
946
+ workflowPromise(name, serde) {
947
+ const wfCtx = this.ctx;
948
+ return wrapDurablePromise(wfCtx.promise(name, serde), (p) => this.toFuture(p));
949
+ }
950
+ spawn(op) {
951
+ return spawn(op);
952
+ }
953
+ /**
954
+ * Create a single-shot in-memory channel. Returns a Channel<T> with
955
+ * `send(v)` (fire-and-forget, idempotent — first call settles, rest
956
+ * are dropped) and `receive: Future<T>` (a stable settle-once Future,
957
+ * the same handle on every access).
958
+ *
959
+ * Canonical use: cooperative cancellation. Spawn a routine that
960
+ * selects over its work and `stop.receive`; the canceller calls
961
+ * `stop.send()` to request termination. The receiver decides what
962
+ * to do — return a partial result, do cleanup yields, ignore.
963
+ *
964
+ * Because `receive` is a stable, settle-once Future, multiple readers
965
+ * all observe the same value (one-time broadcast) and the worker can
966
+ * use it in every iteration of a select-loop without leaking orphan
967
+ * receivers.
968
+ *
969
+ * Multi-event streams (producer-consumer, progress events) are NOT
970
+ * supported — Channel is intentionally single-shot. A separate
971
+ * primitive for that use case is yet to be designed.
972
+ */
973
+ channel() {
974
+ return this.sched.makeChannel();
975
+ }
976
+ /**
977
+ * Per-invocation read-write key-value store. Use from a handler whose
978
+ * underlying context is ObjectContext or WorkflowContext.
979
+ *
980
+ * The optional `TState` generic gives keyof-checked names and per-key
981
+ * value types:
982
+ *
983
+ * ops.state<{count: number; user: User}>()
984
+ * // state.get("count") → Future<number | null>
985
+ *
986
+ * Without it, names are `string` and values are inferred per call:
987
+ *
988
+ * ops.state()
989
+ * // state.get<number>("count") → Future<number | null>
990
+ *
991
+ * Calling write methods from a shared (read-only) context throws at
992
+ * runtime — for shared handlers, use `sharedState()` below to get a
993
+ * narrower type that drops the write methods.
994
+ */
995
+ state() {
996
+ return makeState(this.ctx, this.sched, adapt);
997
+ }
998
+ /**
999
+ * Per-invocation read-only key-value store. Use from a handler whose
1000
+ * underlying context is ObjectSharedContext or WorkflowSharedContext.
1001
+ *
1002
+ * Same `TState` generic as `state()`. Returns the read-only subset
1003
+ * (`get`, `keys`); attempting to call writes is a type error.
1004
+ */
1005
+ sharedState() {
1006
+ return makeState(this.ctx, this.sched, adapt);
1007
+ }
1008
+ /**
1009
+ * Wait for every future to settle; return their values in input
1010
+ * order. Heterogeneous-tuple typing — `all([fA, fB])` where
1011
+ * `fA: Future<A>` and `fB: Future<B>` yields `Future<[A, B]>`.
1012
+ * Mirrors `Promise.all` from the standard lib.
1013
+ */
1014
+ all(futures) {
1015
+ return this.sched.all(futures);
1016
+ }
1017
+ /**
1018
+ * Return the first future to settle; losers continue running but
1019
+ * their results are discarded. Heterogeneous-tuple typing —
1020
+ * `race([fA, fB])` yields `Future<A | B>`. Mirrors `Promise.race`.
1021
+ */
1022
+ race(futures) {
1023
+ return this.sched.race(futures);
1024
+ }
1025
+ /**
1026
+ * First-success combinator. Resolves with the first input that
1027
+ * succeeds (non-rejected); rejects with `AggregateError(errors)` when
1028
+ * every input rejects (including an empty input array). See `Promise.any`.
1029
+ *
1030
+ * Tuple-aware typing — `any([fA, fB])` where `fA: Future<A>` and
1031
+ * `fB: Future<B>` yields `Future<A | B>`.
1032
+ */
1033
+ any(futures) {
1034
+ return this.sched.any(futures);
1035
+ }
1036
+ /**
1037
+ * Settle-all combinator. Resolves with an array of
1038
+ * `FutureSettledResult` in input order; never rejects. See
1039
+ * `Promise.allSettled`.
1040
+ *
1041
+ * Tuple-aware typing — `allSettled([fA, fB])` yields
1042
+ * `Future<[FutureSettledResult<A>, FutureSettledResult<B>]>`.
1043
+ */
1044
+ allSettled(futures) {
1045
+ return this.sched.allSettled(futures);
1046
+ }
1047
+ *select(branches) {
1048
+ return yield* select(branches);
1049
+ }
1050
+ };
1051
+ /**
1052
+ * Run a generator-based workflow against a Restate context.
1053
+ *
1054
+ * `op` is an `Operation<T>` — typically the result of
1055
+ * `gen(function*() { ... })`. Inside the generator body, reach for the
1056
+ * free-standing API (`run`, `sleep`, `all`, `state`, …) imported
1057
+ * from `@restatedev/restate-sdk-gen`. They read the active scheduler from a
1058
+ * synchronous current-fiber slot installed by `Fiber.advance`.
1059
+ *
1060
+ * `gen()` already takes a factory, so the same `Operation` is re-
1061
+ * iterable across multiple `execute()` calls — no need for a builder
1062
+ * lambda at this boundary.
1063
+ *
1064
+ * @example
1065
+ * execute(ctx, gen(function* () {
1066
+ * const greeting = yield* run(async () => "hi", { name: "compose" });
1067
+ * return greeting;
1068
+ * }));
1069
+ */
1070
+ async function execute(context, op) {
1071
+ const sched = new Scheduler(defaultLib);
1072
+ sched.contextSlot = new RestateOperations(context, sched);
1073
+ return sched.run(op);
1074
+ }
1075
+
1076
+ //#endregion
1077
+ export { all, allSettled, any, attach, awakeable, cancel, channel, execute, gen, genericCall, genericSend, objectClient, objectSendClient, race, rejectAwakeable, resolveAwakeable, run, select, serviceClient, serviceSendClient, sharedState, signal, sleep, spawn, state, workflowClient, workflowPromise, workflowSendClient, wrapActionForCancellation };
1078
+ //# sourceMappingURL=index.js.map