@restatedev/restate-sdk-gen 0.0.0 → 1.14.3

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,1475 @@
1
+ import { t as __export } from "./chunk-Bp6m_JJh.js";
2
+ import * as restate from "@restatedev/restate-sdk";
3
+ import { Opts, SendOpts } from "@restatedev/restate-sdk";
4
+ import { Opts as Opts$1, SendOpts as SendOpts$1, connect } from "@restatedev/restate-sdk-clients";
5
+ import { serde } from "@restatedev/restate-sdk-core";
6
+
7
+ //#region src/current.ts
8
+ let CURRENT = null;
9
+ /**
10
+ * Save the previous slot, install `value` as the current. Returns the
11
+ * previous value so `clearCurrent` can restore it (supports nested
12
+ * scheduler invocations on the same thread, even though we don't expect
13
+ * any in production).
14
+ */
15
+ function setCurrent(value) {
16
+ const prev = CURRENT;
17
+ CURRENT = value;
18
+ return prev;
19
+ }
20
+ /** Restore a slot previously captured by `setCurrent`. */
21
+ function clearCurrent(prev) {
22
+ CURRENT = prev;
23
+ }
24
+ /**
25
+ * Read the slot, throwing if no fiber is currently advancing. Callers
26
+ * cast the return type — the slot is intentionally `unknown` here so
27
+ * this module stays free of cycles.
28
+ */
29
+ function getCurrent() {
30
+ 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*() { ... }))`.");
31
+ return CURRENT;
32
+ }
33
+
34
+ //#endregion
35
+ //#region src/invocation-reference.ts
36
+ var InvocationReferenceImpl = class {
37
+ constructor(id, _outputSerde) {
38
+ this.id = id;
39
+ this._outputSerde = _outputSerde;
40
+ }
41
+ attach(serde$1) {
42
+ return getCurrent().attach(this.id, serde$1 ?? this._outputSerde);
43
+ }
44
+ signal(name, serde$1) {
45
+ return getCurrent().invocationSignal(this.id, name, serde$1);
46
+ }
47
+ cancel() {
48
+ getCurrent().cancel(this.id);
49
+ }
50
+ };
51
+
52
+ //#endregion
53
+ //#region src/free.ts
54
+ /**
55
+ * Read the active `RestateOperations` from the current-fiber slot.
56
+ * Throws if called outside a fiber's synchronous advance span (e.g.,
57
+ * at module init or inside an `ops.run` async closure that resolved
58
+ * after the fiber returned).
59
+ */
60
+ function currentOps() {
61
+ return getCurrent();
62
+ }
63
+ const rand = () => currentOps().rand;
64
+ const date = () => currentOps().date;
65
+ const logger = () => currentOps().console;
66
+ /**
67
+ * Returns the current invocation's request metadata plus the optional
68
+ * virtual-object / workflow key. The `key` field is only present when
69
+ * the handler belongs to an object or workflow.
70
+ */
71
+ const handlerRequest = () => currentOps().handlerRequest();
72
+ /**
73
+ * Run a side-effecting closure as a journal entry. See
74
+ * `RestateOperations.run` for full semantics.
75
+ *
76
+ * `name` is derived from `action.name` (works for named functions and
77
+ * arrow functions assigned to a `const`) or specified explicitly via
78
+ * `opts.name`. If neither resolves, throws.
79
+ */
80
+ const run = (action, opts) => currentOps().run(action, opts);
81
+ const sleep = (duration, name) => currentOps().sleep(duration, name);
82
+ const awakeable = (serde$1) => currentOps().awakeable(serde$1);
83
+ const resolveAwakeable = (id, payload, serde$1) => currentOps().resolveAwakeable(id, payload, serde$1);
84
+ const rejectAwakeable = (id, reason) => currentOps().rejectAwakeable(id, reason);
85
+ const signal = (name, serde$1) => currentOps().signal(name, serde$1);
86
+ const attach = (invocationId, serde$1) => currentOps().attach(invocationId, serde$1);
87
+ function client(def, key) {
88
+ return currentOps().client(def, key);
89
+ }
90
+ function sendClient(def, key) {
91
+ return currentOps().sendClient(def, key);
92
+ }
93
+ const call = (c) => currentOps().call(c);
94
+ const send = (c, outputSerde) => currentOps().send(c, outputSerde);
95
+ /**
96
+ * Create an InvocationReference from a known invocation ID (e.g. retrieved from state).
97
+ * `attach()` and `cancel()` on the result use the current fiber slot like all free functions.
98
+ */
99
+ function invocation(id, opts) {
100
+ return new InvocationReferenceImpl(id, opts?.outputSerde);
101
+ }
102
+ const cancel = (invocationId) => currentOps().cancel(invocationId);
103
+ const channel = () => currentOps().channel();
104
+ const state = () => currentOps().state();
105
+ const sharedState = () => currentOps().sharedState();
106
+ const workflowPromise = (name, serde$1) => currentOps().workflowPromise(name, serde$1);
107
+ /**
108
+ * Wait for every future to settle; return their values in input order.
109
+ * Heterogeneous-tuple typing — `all([fA, fB])` where `fA: Future<A>`
110
+ * and `fB: Future<B>` yields `Future<[A, B]>`. Mirrors `Promise.all`.
111
+ */
112
+ const all = (futures) => currentOps().all(futures);
113
+ /**
114
+ * Return the first future to settle; losers continue running but their
115
+ * results are discarded. Heterogeneous-tuple typing — `race([fA, fB])`
116
+ * yields `Future<A | B>`. Mirrors `Promise.race`.
117
+ */
118
+ const race = (futures) => currentOps().race(futures);
119
+ /**
120
+ * First-to-succeed wins (non-rejected). Rejects with `AggregateError(errors)`
121
+ * when every input rejects (including the empty input case). Tuple-aware —
122
+ * `any([fA, fB])` yields `Future<A | B>`. Mirrors `Promise.any`.
123
+ */
124
+ const any = (futures) => currentOps().any(futures);
125
+ /**
126
+ * Wait for every future to settle; never rejects. Tuple-aware —
127
+ * `allSettled([fA, fB])` yields
128
+ * `Future<[FutureSettledResult<A>, FutureSettledResult<B>]>`.
129
+ * Mirrors `Promise.allSettled`.
130
+ */
131
+ const allSettled = (futures) => currentOps().allSettled(futures);
132
+ /**
133
+ * Register `op` as a fresh routine and return a `Future<T>` for its
134
+ * eventual outcome. Eager — the child is already in flight by the time
135
+ * `spawn` returns. See `RestateOperations.spawn` for full semantics.
136
+ */
137
+ const spawn = (op) => currentOps().spawn(op);
138
+
139
+ //#endregion
140
+ //#region src/operation.ts
141
+ const opTag = Symbol("restateOperation");
142
+ function makePrimitive(node) {
143
+ const op = {
144
+ [opTag]: node,
145
+ *[Symbol.iterator]() {
146
+ return yield op;
147
+ }
148
+ };
149
+ return op;
150
+ }
151
+ function awaitRace(futures) {
152
+ const op = {
153
+ [opTag]: {
154
+ _tag: "AwaitRace",
155
+ futures
156
+ },
157
+ *[Symbol.iterator]() {
158
+ return yield op;
159
+ }
160
+ };
161
+ return op;
162
+ }
163
+ function gen(body) {
164
+ return { [Symbol.iterator]: body };
165
+ }
166
+ function* select(branches) {
167
+ const tags = Object.keys(branches);
168
+ const tag = tags[(yield* awaitRace(tags.map((t) => branches[t]))).index];
169
+ return {
170
+ tag,
171
+ future: branches[tag]
172
+ };
173
+ }
174
+
175
+ //#endregion
176
+ //#region src/future.ts
177
+ const futureBacking = Symbol("restateFutureBacking");
178
+ /**
179
+ * Internal accessor — read the backing off a Future. Only the scheduler
180
+ * and fiber call this; user code never sees Backing.
181
+ */
182
+ function getBacking(f) {
183
+ return f[futureBacking];
184
+ }
185
+ function makeFuture(backing) {
186
+ const future = {
187
+ [futureBacking]: backing,
188
+ *[Symbol.iterator]() {
189
+ return yield leafOp;
190
+ }
191
+ };
192
+ const leafOp = makePrimitive({
193
+ _tag: "Leaf",
194
+ future
195
+ });
196
+ return future;
197
+ }
198
+ function isJournalBacked(f) {
199
+ return getBacking(f).kind === "journal";
200
+ }
201
+
202
+ //#endregion
203
+ //#region src/fiber.ts
204
+ var Fiber = class {
205
+ it;
206
+ sched;
207
+ state = {
208
+ kind: "ready",
209
+ resume: null
210
+ };
211
+ waiters = [];
212
+ constructor(op, sched) {
213
+ this.it = op[Symbol.iterator]();
214
+ this.sched = sched;
215
+ }
216
+ isDone() {
217
+ return this.state.kind === "done";
218
+ }
219
+ /**
220
+ * For a fiber known to be done, return its settled outcome. Throws
221
+ * if called on a non-done fiber — callers must check `isDone()` first
222
+ * (or use `awaitCompletion` for the polymorphic version).
223
+ */
224
+ settledValue() {
225
+ if (this.state.kind !== "done") throw new Error("Fiber.settledValue called on non-done fiber");
226
+ return this.state.settled;
227
+ }
228
+ /**
229
+ * Returns the parked sources this fiber is currently racing against.
230
+ * Empty if the fiber is parked only on routine waiters (e.g.,
231
+ * waiting on a sibling fiber to finish), or in any non-parked state.
232
+ * The scheduler reads these to assemble its main-loop race.
233
+ */
234
+ parkedSources() {
235
+ return this.state.kind === "parked" ? this.state.promises : [];
236
+ }
237
+ /**
238
+ * "I want to be notified when this fiber is done." If the fiber is
239
+ * already done, returns its settled outcome immediately (caller
240
+ * should NOT also expect the waiter to be invoked). Otherwise
241
+ * returns null and queues the waiter for invocation when the fiber
242
+ * eventually finishes.
243
+ */
244
+ awaitCompletion(waiter) {
245
+ if (this.state.kind === "done") return this.state.settled;
246
+ this.waiters.push(waiter);
247
+ return null;
248
+ }
249
+ /**
250
+ * Wake this fiber with a resume value. Transitions to ready and
251
+ * notifies the scheduler. May be called from any state except done
252
+ * (waking a done fiber is a programming error and is ignored
253
+ * defensively).
254
+ */
255
+ wake(resume) {
256
+ if (this.state.kind === "done") return;
257
+ this.state = {
258
+ kind: "ready",
259
+ resume
260
+ };
261
+ this.sched.markReady(this);
262
+ }
263
+ /**
264
+ * Drive the fiber's iterator until it parks (yields a primitive
265
+ * whose dispatch ends with the fiber waiting on a source) or
266
+ * finishes (returns or throws).
267
+ *
268
+ * No-op if the fiber is not in the ready state — protects against
269
+ * stale entries in the scheduler's ready queue.
270
+ */
271
+ advance() {
272
+ if (this.state.kind !== "ready") return;
273
+ const prevSlot = setCurrent(this.sched.contextSlot);
274
+ try {
275
+ let resume = this.state.resume;
276
+ while (true) {
277
+ let next;
278
+ try {
279
+ next = stepIterator(this.it, resume);
280
+ } catch (e) {
281
+ this.finish({
282
+ ok: false,
283
+ e
284
+ });
285
+ return;
286
+ }
287
+ if (next.done) {
288
+ this.finish({
289
+ ok: true,
290
+ v: next.value
291
+ });
292
+ return;
293
+ }
294
+ const node = next.value[opTag];
295
+ let outcome;
296
+ switch (node._tag) {
297
+ case "Leaf":
298
+ outcome = this.parkOnLeaf(node);
299
+ break;
300
+ case "AwaitRace":
301
+ outcome = this.parkOnAwaitRace(node.futures);
302
+ break;
303
+ }
304
+ if (outcome === null) return;
305
+ resume = outcome;
306
+ }
307
+ } finally {
308
+ clearCurrent(prevSlot);
309
+ }
310
+ }
311
+ /**
312
+ * Park on a single Future, or short-circuit if the Future is already
313
+ * settled. Returns the Settled value to feed back into the iterator
314
+ * if a short-circuit is possible (routine-backed future whose target
315
+ * already finished); returns null if the fiber is parked and the
316
+ * caller should suspend.
317
+ */
318
+ parkOnLeaf(leaf) {
319
+ const backing = getBacking(leaf.future);
320
+ if (backing.kind === "journal") {
321
+ this.state = {
322
+ kind: "parked",
323
+ promises: [{
324
+ promise: backing.promise,
325
+ fire: (s) => this.wake(s)
326
+ }]
327
+ };
328
+ return null;
329
+ }
330
+ const settled = backing.target.awaitCompletion((s) => this.wake(s));
331
+ if (settled !== null) return settled;
332
+ this.state = {
333
+ kind: "parked",
334
+ promises: []
335
+ };
336
+ return null;
337
+ }
338
+ /**
339
+ * Park on the first-to-settle of a list of Futures, or short-circuit
340
+ * if any source is already settled. Returns `{index, settled}`
341
+ * (wrapped as Settled) on short-circuit, or null if parked.
342
+ *
343
+ * On the parked path, every source registers a one-shot fire
344
+ * callback that wakes the fiber with `{index, settled}`. The `won`
345
+ * flag guards against duplicate wakes when multiple sources settle
346
+ * in the same tick. Local sources (fibers, channels) park on the
347
+ * target's waiter list; journal sources race in the main loop's
348
+ * race promise.
349
+ */
350
+ parkOnAwaitRace(futures) {
351
+ for (let i = 0; i < futures.length; i++) {
352
+ const b = getBacking(futures[i]);
353
+ if (b.kind === "local" && b.target.isDone()) return {
354
+ ok: true,
355
+ v: {
356
+ index: i,
357
+ settled: b.target.settledValue()
358
+ }
359
+ };
360
+ }
361
+ let won = false;
362
+ const promises = [];
363
+ for (let i = 0; i < futures.length; i++) {
364
+ const idx = i;
365
+ const b = getBacking(futures[i]);
366
+ const fireOnce = (settled) => {
367
+ if (won) return;
368
+ won = true;
369
+ this.wake({
370
+ ok: true,
371
+ v: {
372
+ index: idx,
373
+ settled
374
+ }
375
+ });
376
+ };
377
+ if (b.kind === "local") b.target.awaitCompletion(fireOnce);
378
+ else promises.push({
379
+ promise: b.promise,
380
+ fire: fireOnce
381
+ });
382
+ }
383
+ this.state = {
384
+ kind: "parked",
385
+ promises
386
+ };
387
+ return null;
388
+ }
389
+ /**
390
+ * Iterator finished or threw. Transition to done, fire all waiters
391
+ * with the settled outcome, notify scheduler.
392
+ */
393
+ finish(settled) {
394
+ this.state = {
395
+ kind: "done",
396
+ settled
397
+ };
398
+ const waiters = this.waiters;
399
+ this.waiters = [];
400
+ for (const w of waiters) w(settled);
401
+ this.sched.markDone(this);
402
+ }
403
+ };
404
+ /**
405
+ * Drive a generator iterator one step, feeding it whatever value or
406
+ * exception the caller is resuming with. `resume === null` is the
407
+ * very first step; `{ok: true, v}` resumes with a value; `{ok: false,
408
+ * e}` throws into the iterator (or, if the iterator has no `throw`
409
+ * method, rethrows so the fiber fails).
410
+ */
411
+ function stepIterator(it, resume) {
412
+ if (resume === null) return it.next(void 0);
413
+ if (resume.ok) return it.next(resume.v);
414
+ if (it.throw) return it.throw(resume.e);
415
+ throw resume.e;
416
+ }
417
+
418
+ //#endregion
419
+ //#region src/channel.ts
420
+ var ChannelImpl = class {
421
+ state = { kind: "pending" };
422
+ waiters = [];
423
+ fire(value) {
424
+ if (this.state.kind === "settled") return;
425
+ this.state = {
426
+ kind: "settled",
427
+ value
428
+ };
429
+ const ws = this.waiters;
430
+ this.waiters = [];
431
+ const settled = {
432
+ ok: true,
433
+ v: value
434
+ };
435
+ for (const w of ws) w(settled);
436
+ }
437
+ isDone() {
438
+ return this.state.kind === "settled";
439
+ }
440
+ settledValue() {
441
+ if (this.state.kind !== "settled") throw new Error("ChannelImpl.settledValue called on a pending channel");
442
+ return {
443
+ ok: true,
444
+ v: this.state.value
445
+ };
446
+ }
447
+ awaitCompletion(waiter) {
448
+ if (this.state.kind === "settled") return {
449
+ ok: true,
450
+ v: this.state.value
451
+ };
452
+ this.waiters.push(waiter);
453
+ return null;
454
+ }
455
+ };
456
+ function makeChannel() {
457
+ const impl = new ChannelImpl();
458
+ return {
459
+ send: (v) => gen(function* () {
460
+ impl.fire(v);
461
+ }),
462
+ receive: makeFuture({
463
+ kind: "local",
464
+ target: impl
465
+ })
466
+ };
467
+ }
468
+
469
+ //#endregion
470
+ //#region src/scheduler.ts
471
+ var Scheduler = class {
472
+ fibers = /* @__PURE__ */ new Set();
473
+ ready = [];
474
+ lib;
475
+ abortController = new AbortController();
476
+ /**
477
+ * Slot for the operations object bound to this scheduler. Defaults
478
+ * to the scheduler itself so tests (which don't construct a
479
+ * `RestateOperations`) still get a slot exposing `.spawn`. Production
480
+ * `execute()` overrides this with a `RestateOperations` instance
481
+ * after construction (we can't pass it into the ctor because
482
+ * `RestateOperations` needs the scheduler to construct itself).
483
+ * `Fiber.advance` publishes this to the module-level current-fiber
484
+ * slot read by free-standing API functions. Typed `unknown` here to
485
+ * keep this module independent of `restate-operations.ts`.
486
+ */
487
+ contextSlot;
488
+ constructor(lib) {
489
+ this.lib = lib;
490
+ this.contextSlot = this;
491
+ }
492
+ /**
493
+ * The scheduler's current AbortSignal. Aborts when invocation
494
+ * cancellation is observed (the SDK rejects the main race promise
495
+ * with TerminalError). After cancellation has been delivered to
496
+ * fibers and the scheduler has resumed, this getter returns a
497
+ * *fresh* signal — one that is not aborted, even though the previous
498
+ * cancel was just delivered.
499
+ *
500
+ * Pass `signal` to AbortSignal-aware APIs in `ops.run` closures
501
+ * (e.g. `fetch(url, {signal})`) so they cancel promptly when the
502
+ * surrounding work is cancelled. Cleanup closures yielded after a
503
+ * caught CancelledError get a fresh, unaborted signal — so they can
504
+ * do real work and only abort if a *new* cancellation arrives.
505
+ */
506
+ get abortSignal() {
507
+ return this.abortController.signal;
508
+ }
509
+ markReady(f) {
510
+ this.ready.push(f);
511
+ }
512
+ markDone(f) {
513
+ this.fibers.delete(f);
514
+ }
515
+ createFiber(op) {
516
+ const f = new Fiber(op, this);
517
+ this.fibers.add(f);
518
+ this.ready.push(f);
519
+ return f;
520
+ }
521
+ makeJournalFuture(promise) {
522
+ return makeFuture({
523
+ kind: "journal",
524
+ promise
525
+ });
526
+ }
527
+ /**
528
+ * Register an Operation as a fresh fiber and return a Future that
529
+ * resolves with its eventual value. Eager: by the time this returns,
530
+ * the fiber is queued ready and will be advanced on the next drain.
531
+ *
532
+ * Used by combinator fallbacks (race, allSettled, …), by
533
+ * `RestateOperations.spawn`, and via the slot interface by the free
534
+ * `spawn` function.
535
+ */
536
+ spawn(op) {
537
+ return makeFuture({
538
+ kind: "local",
539
+ target: this.createFiber(op)
540
+ });
541
+ }
542
+ /**
543
+ * Construct a single-shot in-memory channel. Send must be called from
544
+ * a fiber currently advancing under this scheduler. See `channel.ts`
545
+ * for full semantics.
546
+ */
547
+ makeChannel() {
548
+ return makeChannel();
549
+ }
550
+ /**
551
+ * Combinator over Futures. Fast path when every input is journal-
552
+ * backed: use the lib's all/race for a single combinator entry.
553
+ * Otherwise, fall back to a synthesized fiber that yields each in
554
+ * turn.
555
+ *
556
+ * Tuple-aware typing (mirrors `Promise.all` in the standard lib):
557
+ * `all([fA, fB])` where `fA: Future<A>` and `fB: Future<B>`
558
+ * yields `Future<[A, B]>`, not `Future<(A | B)[]>`. The `const T`
559
+ * lets TS infer a tuple from a literal array.
560
+ */
561
+ all(futures) {
562
+ const fs = futures;
563
+ if (fs.every(isJournalBacked)) {
564
+ const promises = fs.map((f) => f[futureBacking].promise);
565
+ return this.makeJournalFuture(this.lib.all(promises));
566
+ }
567
+ return this.spawn(gen(function* () {
568
+ const out = new Array(fs.length);
569
+ for (let i = 0; i < fs.length; i++) out[i] = yield* fs[i];
570
+ return out;
571
+ }));
572
+ }
573
+ race(futures) {
574
+ const fs = futures;
575
+ return this.spawn(gen(function* () {
576
+ const result = yield* awaitRace(fs);
577
+ if (result.settled.ok) return result.settled.v;
578
+ throw result.settled.e;
579
+ }));
580
+ }
581
+ /**
582
+ * First-success combinator. Mirrors `Promise.any` /
583
+ * `RestatePromise.any`: settles with the first input that succeeds
584
+ * (non-rejected); rejects with `AggregateError(errors)` when every
585
+ * input rejects (including the empty-array case).
586
+ *
587
+ * Fast path collapses to a single `lib.any` over journal awaitables.
588
+ * Fallback synthesizes a fiber that loops `awaitAnyOf` over the
589
+ * still-pending subset, accumulating rejections in input order until
590
+ * one input fulfills or all have rejected.
591
+ *
592
+ * Tuple-aware: `any([fA, fB])` where `fA: Future<A>` and `fB:
593
+ * Future<B>` yields `Future<A | B>` (the union of slot types), same
594
+ * shape as `Promise.any`.
595
+ */
596
+ any(futures) {
597
+ const fs = futures;
598
+ if (fs.every(isJournalBacked)) {
599
+ const promises = fs.map((f) => f[futureBacking].promise);
600
+ return this.makeJournalFuture(this.lib.any(promises));
601
+ }
602
+ return this.spawn(gen(function* () {
603
+ const errors = new Array(fs.length);
604
+ const remaining = /* @__PURE__ */ new Set();
605
+ for (let i = 0; i < fs.length; i++) remaining.add(i);
606
+ while (remaining.size > 0) {
607
+ const liveIdx = Array.from(remaining);
608
+ const result = yield* awaitRace(liveIdx.map((i) => fs[i]));
609
+ const original = liveIdx[result.index];
610
+ if (result.settled.ok) return result.settled.v;
611
+ errors[original] = result.settled.e;
612
+ remaining.delete(original);
613
+ }
614
+ throw new AggregateError(errors, "All promises were rejected");
615
+ }));
616
+ }
617
+ /**
618
+ * Settle-all combinator. Mirrors `Promise.allSettled` /
619
+ * `RestatePromise.allSettled`: resolves with an array of
620
+ * `FutureSettledResult` in input order, never rejects.
621
+ *
622
+ * Fast path collapses to a single `lib.allSettled`. Fallback yields
623
+ * each Future in turn — safe because Futures are eager (already in
624
+ * flight); sequential harvesting just reads them as they complete
625
+ * without blocking concurrency.
626
+ *
627
+ * Tuple-aware: `allSettled([fA, fB])` yields
628
+ * `Future<[FutureSettledResult<A>, FutureSettledResult<B>]>`.
629
+ */
630
+ allSettled(futures) {
631
+ const fs = futures;
632
+ if (fs.every(isJournalBacked)) {
633
+ const promises = fs.map((f) => f[futureBacking].promise);
634
+ return this.makeJournalFuture(this.lib.allSettled(promises));
635
+ }
636
+ return this.spawn(gen(function* () {
637
+ const out = new Array(fs.length);
638
+ for (let i = 0; i < fs.length; i++) try {
639
+ out[i] = {
640
+ status: "fulfilled",
641
+ value: yield* fs[i]
642
+ };
643
+ } catch (reason) {
644
+ out[i] = {
645
+ status: "rejected",
646
+ reason
647
+ };
648
+ }
649
+ return out;
650
+ }));
651
+ }
652
+ drainReady() {
653
+ while (this.ready.length > 0) this.ready.shift().advance();
654
+ }
655
+ /**
656
+ * Run an operation to completion. Drain the ready queue, then loop:
657
+ * collect every PromiseSource from every parked fiber, race them,
658
+ * dispatch the winner via its fire callback, drain. Stop when no
659
+ * fiber is alive.
660
+ */
661
+ async run(op) {
662
+ const main = this.createFiber(op);
663
+ this.drainReady();
664
+ while (this.fibers.size > 0) {
665
+ const items = [];
666
+ for (const f of this.fibers) for (const src of f.parkedSources()) items.push(src);
667
+ if (items.length === 0) throw new Error("scheduler stuck: live fibers but nothing pending on a journal promise");
668
+ const tagged = items.map(({ promise }, i$1) => promise.map((v, e) => e !== void 0 ? {
669
+ i: i$1,
670
+ ok: false,
671
+ e
672
+ } : {
673
+ i: i$1,
674
+ ok: true,
675
+ v
676
+ }));
677
+ let raceWinner;
678
+ try {
679
+ raceWinner = await this.lib.race(tagged);
680
+ } catch (e) {
681
+ if (this.lib.isCancellation(e)) {
682
+ this.abortController.abort(e);
683
+ this.abortController = new AbortController();
684
+ }
685
+ const errSettled = {
686
+ ok: false,
687
+ e
688
+ };
689
+ for (const it of items) it.fire(errSettled);
690
+ this.drainReady();
691
+ continue;
692
+ }
693
+ const { i,...settledFields } = raceWinner;
694
+ const settled = settledFields.ok ? {
695
+ ok: true,
696
+ v: settledFields.v
697
+ } : {
698
+ ok: false,
699
+ e: settledFields.e
700
+ };
701
+ items[i].fire(settled);
702
+ this.drainReady();
703
+ }
704
+ if (!main.isDone()) throw new Error("scheduler exited but main fiber never completed");
705
+ const final = main.settledValue();
706
+ if (final.ok) return final.v;
707
+ throw final.e;
708
+ }
709
+ };
710
+
711
+ //#endregion
712
+ //#region src/state.ts
713
+ /**
714
+ * Build a `State<TState>` over the given context. The runtime delegates
715
+ * straight to `ctx.get` / `ctx.set` / etc.; the TState generic is purely
716
+ * a TS-level convenience and gets erased at runtime.
717
+ *
718
+ * For shared (read-only) contexts, the returned State has the same
719
+ * runtime shape but the caller should use the `SharedState<TState>`
720
+ * type to drop the write methods. The convenience method
721
+ * `RestateOperations.sharedState()` does this cast.
722
+ */
723
+ function makeState(ctx, sched, adapt$1) {
724
+ const writeCtx = ctx;
725
+ return {
726
+ get(name, serde$1) {
727
+ return sched.makeJournalFuture(adapt$1(ctx.get(name, serde$1)));
728
+ },
729
+ keys() {
730
+ return sched.makeJournalFuture(adapt$1(ctx.stateKeys()));
731
+ },
732
+ set(name, value, serde$1) {
733
+ writeCtx.set(name, value, serde$1);
734
+ },
735
+ clear(name) {
736
+ writeCtx.clear(name);
737
+ },
738
+ clearAll() {
739
+ writeCtx.clearAll();
740
+ }
741
+ };
742
+ }
743
+
744
+ //#endregion
745
+ //#region src/clients.ts
746
+ function makeClient(def, key, call$1) {
747
+ return new Proxy({}, { get(_target, methodName) {
748
+ return (...args) => {
749
+ const { parameter, opts } = optsFromArgs$1(args);
750
+ const callOpts = opts;
751
+ const desc = def._handlers[methodName];
752
+ const outputSerde = callOpts?.output ?? desc?._outputSerde;
753
+ return call$1({
754
+ service: def.name,
755
+ key,
756
+ method: String(methodName),
757
+ parameter,
758
+ inputSerde: callOpts?.input ?? desc?._inputSerde ?? restate.serde.json,
759
+ outputSerde: outputSerde ?? restate.serde.json,
760
+ idempotencyKey: callOpts?.idempotencyKey,
761
+ headers: callOpts?.headers,
762
+ name: callOpts?.name
763
+ });
764
+ };
765
+ } });
766
+ }
767
+ function makeSendClient(def, key, send$1) {
768
+ return new Proxy({}, { get(_target, methodName) {
769
+ return (...args) => {
770
+ const { parameter, opts } = optsFromArgs$1(args);
771
+ const sendOpts = opts;
772
+ const desc = def._handlers[methodName];
773
+ return send$1({
774
+ service: def.name,
775
+ key,
776
+ method: String(methodName),
777
+ parameter,
778
+ inputSerde: sendOpts?.input ?? desc?._inputSerde ?? restate.serde.json,
779
+ delay: sendOpts?.delay,
780
+ idempotencyKey: sendOpts?.idempotencyKey,
781
+ headers: sendOpts?.headers,
782
+ name: sendOpts?.name
783
+ }, desc?._outputSerde);
784
+ };
785
+ } });
786
+ }
787
+ function optsFromArgs$1(args) {
788
+ let parameter;
789
+ let opts;
790
+ switch (args.length) {
791
+ case 0: break;
792
+ case 1:
793
+ if (args[0] instanceof Opts) opts = args[0].getOpts();
794
+ else if (args[0] instanceof SendOpts) opts = args[0].getOpts();
795
+ else parameter = args[0];
796
+ break;
797
+ case 2:
798
+ parameter = args[0];
799
+ if (args[1] instanceof Opts) opts = args[1].getOpts();
800
+ else if (args[1] instanceof SendOpts) opts = args[1].getOpts();
801
+ else throw new TypeError("The second argument must be either Opts or SendOpts");
802
+ break;
803
+ default: throw new TypeError("unexpected number of arguments");
804
+ }
805
+ return {
806
+ parameter,
807
+ opts
808
+ };
809
+ }
810
+
811
+ //#endregion
812
+ //#region src/durable-promise.ts
813
+ function wrapDurablePromise(dp, toFuture) {
814
+ return {
815
+ peek: () => toFuture(dp.peek()),
816
+ resolve: (value) => toFuture(dp.resolve(value)),
817
+ reject: (errorMsg) => toFuture(dp.reject(errorMsg)),
818
+ get: () => toFuture(dp.get())
819
+ };
820
+ }
821
+
822
+ //#endregion
823
+ //#region src/default-lib.ts
824
+ const defaultLib = {
825
+ all(items) {
826
+ return restate.RestatePromise.all(items);
827
+ },
828
+ race(items) {
829
+ return restate.RestatePromise.race(items);
830
+ },
831
+ any(items) {
832
+ return restate.RestatePromise.any(items);
833
+ },
834
+ allSettled(items) {
835
+ return restate.RestatePromise.allSettled(items);
836
+ },
837
+ isCancellation(e) {
838
+ return e instanceof restate.CancelledError;
839
+ }
840
+ };
841
+
842
+ //#endregion
843
+ //#region src/restate-operations.ts
844
+ function adapt(p) {
845
+ return p;
846
+ }
847
+ /**
848
+ * Wrap a user-supplied `run` closure to surface the abort reason
849
+ * (typically a TerminalError(CANCELLED)) on throw paths if the signal
850
+ * aborted during execution. This converts AbortError (and any other
851
+ * abort-caused failure) into the canonical cancellation TerminalError
852
+ * for journal recording.
853
+ *
854
+ * Defensive coercion: if `signal.reason` is itself not a TerminalError
855
+ * (which shouldn't happen in production but might during testing or
856
+ * with non-cancellation race rejections), we wrap it in one. The
857
+ * journal must record a *terminal* outcome to avoid retries against
858
+ * a cancelled invocation.
859
+ *
860
+ * Exposed for testing — the wrapper's behavior is the part that has
861
+ * semantic bite, separate from the ctx.run plumbing.
862
+ */
863
+ function wrapActionForCancellation(signal$1, action) {
864
+ return async () => {
865
+ try {
866
+ return await action({ signal: signal$1 });
867
+ } catch (e) {
868
+ if (signal$1.aborted) throw asTerminalError(signal$1.reason);
869
+ throw e;
870
+ }
871
+ };
872
+ }
873
+ /**
874
+ * Resolve the journal-entry name; throw `TerminalError` if neither
875
+ * source provides one.
876
+ *
877
+ * `TerminalError` (not a plain `Error`) because a missing name is a
878
+ * programming bug — retrying the invocation will hit the same code
879
+ * path and fail the same way. The SDK treats terminal errors as
880
+ * non-retryable; the invocation fails fast instead of looping.
881
+ */
882
+ function resolveRunName(action, opts) {
883
+ const fromOpts = opts?.name?.trim();
884
+ if (fromOpts) return fromOpts;
885
+ const fromFn = action.name;
886
+ if (fromFn) return fromFn;
887
+ 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.");
888
+ }
889
+ /** Translate our `RetryOptions` into the SDK's flat `RunOptions` shape. */
890
+ function toSdkRunOptions(opts) {
891
+ const out = {};
892
+ if (opts?.serde !== void 0) out.serde = opts.serde;
893
+ const r = opts?.retry;
894
+ if (r) {
895
+ if (r.maxAttempts !== void 0) out.maxRetryAttempts = r.maxAttempts;
896
+ if (r.maxDuration !== void 0) out.maxRetryDuration = r.maxDuration;
897
+ if (r.initialInterval !== void 0) out.initialRetryInterval = r.initialInterval;
898
+ if (r.maxInterval !== void 0) out.maxRetryInterval = r.maxInterval;
899
+ if (r.intervalFactor !== void 0) out.retryIntervalFactor = r.intervalFactor;
900
+ }
901
+ return out;
902
+ }
903
+ function asTerminalError(reason) {
904
+ if (reason instanceof restate.TerminalError) return reason;
905
+ return new restate.CancelledError();
906
+ }
907
+ var RestateOperations = class {
908
+ ctx;
909
+ sched;
910
+ constructor(context, sched) {
911
+ this.ctx = context;
912
+ this.sched = sched;
913
+ }
914
+ toFuture(p) {
915
+ return this.sched.makeJournalFuture(adapt(p));
916
+ }
917
+ get rand() {
918
+ return this.ctx.rand;
919
+ }
920
+ get date() {
921
+ return {
922
+ now: () => this.toFuture(this.ctx.date.now()),
923
+ toJSON: () => this.toFuture(this.ctx.date.toJSON())
924
+ };
925
+ }
926
+ get console() {
927
+ return this.ctx.console;
928
+ }
929
+ /**
930
+ * Run a side-effecting closure as a journal entry.
931
+ *
932
+ * The closure receives `{ signal }` — an AbortSignal that fires when
933
+ * invocation cancellation arrives. Pass it into AbortSignal-aware
934
+ * APIs (e.g. `fetch(url, { signal })`) to abort in-flight syscalls.
935
+ *
936
+ * `name` is the journal entry's stable identifier (must be
937
+ * deterministic across replay). It can come from either:
938
+ *
939
+ * - `opts.name` — explicit override
940
+ * - `action.name` — the function's own name (works for `function`
941
+ * declarations and arrow functions assigned to a `const`,
942
+ * since JS infers names from the binding site)
943
+ *
944
+ * If neither resolves, `run` throws.
945
+ *
946
+ * @example Named function — name derived
947
+ * async function fetchUser({ signal }: RunActionOpts): Promise<User> {
948
+ * const r = await fetch(`/users/${id}`, { signal });
949
+ * return r.json();
950
+ * }
951
+ * yield* run(fetchUser);
952
+ *
953
+ * @example Named arrow — name derived from binding
954
+ * const fetchUser = async ({ signal }: RunActionOpts) => { ... };
955
+ * yield* run(fetchUser);
956
+ *
957
+ * @example Inline arrow — name explicit
958
+ * yield* run(async ({ signal }) => fetch(url, { signal }), { name: "fetch" });
959
+ *
960
+ * @example With retry policy
961
+ * yield* run(fetchUser, { retry: { maxAttempts: 3 } });
962
+ *
963
+ * Cancellation hygiene: if the closure throws while the signal is
964
+ * aborted, we rethrow `signal.reason` (the original TerminalError)
965
+ * instead of whatever the closure threw. This ensures the journal
966
+ * entry records `TerminalError(CANCELLED)` rather than `AbortError`.
967
+ */
968
+ run(action, opts) {
969
+ const name = resolveRunName(action, opts);
970
+ const wrapped = wrapActionForCancellation(this.sched.abortSignal, action);
971
+ return this.sched.makeJournalFuture(adapt(this.ctx.run(name, wrapped, toSdkRunOptions(opts))));
972
+ }
973
+ sleep(duration, name) {
974
+ return this.sched.makeJournalFuture(adapt(this.ctx.sleep(duration, name)));
975
+ }
976
+ awakeable(serde$1) {
977
+ const { id, promise } = this.ctx.awakeable(serde$1);
978
+ return {
979
+ id,
980
+ promise: this.sched.makeJournalFuture(adapt(promise))
981
+ };
982
+ }
983
+ resolveAwakeable(id, payload, serde$1) {
984
+ this.ctx.resolveAwakeable(id, payload, serde$1);
985
+ }
986
+ rejectAwakeable(id, reason) {
987
+ this.ctx.rejectAwakeable(id, reason);
988
+ }
989
+ signal(name, serde$1) {
990
+ return this.sched.makeJournalFuture(adapt(this.ctx.signal(name, serde$1)));
991
+ }
992
+ attach(invocationId, serde$1) {
993
+ return this.sched.makeJournalFuture(adapt(this.ctx.attach(invocationId, serde$1)));
994
+ }
995
+ /**
996
+ * Returns the current invocation's request metadata plus the optional
997
+ * virtual-object / workflow key. The `key` field is only present when
998
+ * the handler belongs to an object or workflow.
999
+ */
1000
+ handlerRequest() {
1001
+ const req = this.ctx.request();
1002
+ const ctx = this.ctx;
1003
+ return {
1004
+ attemptHeaders: req.attemptHeaders,
1005
+ body: req.body,
1006
+ extraArgs: req.extraArgs,
1007
+ headers: req.headers,
1008
+ id: req.id,
1009
+ target: req.target,
1010
+ get key() {
1011
+ return ctx.key;
1012
+ }
1013
+ };
1014
+ }
1015
+ client(def, key) {
1016
+ return makeClient(def, key, (o) => this.call(o));
1017
+ }
1018
+ sendClient(def, key) {
1019
+ return makeSendClient(def, key, (o, serde$1) => this.send(o, serde$1));
1020
+ }
1021
+ call(opts) {
1022
+ const restatePromise = this.ctx.genericCall(opts);
1023
+ const resultFuture = this.toFuture(restatePromise);
1024
+ const invocation$1 = this.invocationReferenceFromHandle(restatePromise, opts.outputSerde);
1025
+ return Object.assign(resultFuture, { invocation: invocation$1 });
1026
+ }
1027
+ send(opts, outputSerde) {
1028
+ const handle = this.ctx.genericSend(opts);
1029
+ return this.invocationReferenceFromHandle(handle, outputSerde);
1030
+ }
1031
+ invocationReferenceFromHandle(handle, outputSerde) {
1032
+ const idFuture = this.toFuture(handle.invocationId);
1033
+ return this.sched.spawn(gen(function* () {
1034
+ return new InvocationReferenceImpl(yield* idFuture, outputSerde);
1035
+ }));
1036
+ }
1037
+ invocationSignal(invocationId, name, serde$1) {
1038
+ return this.ctx.invocation(invocationId).signal(name, serde$1);
1039
+ }
1040
+ /**
1041
+ * Cancel another invocation by its id. To observe cancellation
1042
+ * arriving at *this* invocation, catch the `TerminalError` thrown by
1043
+ * the next `yield*` boundary or use the `signal` exposed inside
1044
+ * `ops.run` closures.
1045
+ */
1046
+ cancel(invocationId) {
1047
+ this.ctx.cancel(invocationId);
1048
+ }
1049
+ /**
1050
+ * Workflow-bound durable promise. Use only inside a workflow handler
1051
+ * (the underlying context must be `WorkflowContext` or
1052
+ * `WorkflowSharedContext`). Returns a wrapper whose `peek`/`get`/
1053
+ * `resolve`/`reject` methods return Futures.
1054
+ */
1055
+ workflowPromise(name, serde$1) {
1056
+ const wfCtx = this.ctx;
1057
+ return wrapDurablePromise(wfCtx.promise(name, serde$1), (p) => this.toFuture(p));
1058
+ }
1059
+ /**
1060
+ * Register `op` as a fresh routine and return a `Future<T>` for its
1061
+ * eventual outcome. Eager: by the time `spawn` returns, the child is
1062
+ * already queued and will advance on the next scheduler tick — same
1063
+ * model as `run`/`sleep`/`awakeable`. The returned Future can be
1064
+ * yielded on, handed to combinators, or stored.
1065
+ */
1066
+ spawn(op) {
1067
+ return this.sched.spawn(op);
1068
+ }
1069
+ /**
1070
+ * Create a single-shot in-memory channel. Returns a Channel<T> with
1071
+ * `send(v)` (fire-and-forget, idempotent — first call settles, rest
1072
+ * are dropped) and `receive: Future<T>` (a stable settle-once Future,
1073
+ * the same handle on every access).
1074
+ *
1075
+ * Canonical use: cooperative cancellation. Spawn a routine that
1076
+ * selects over its work and `stop.receive`; the canceller calls
1077
+ * `stop.send()` to request termination. The receiver decides what
1078
+ * to do — return a partial result, do cleanup yields, ignore.
1079
+ *
1080
+ * Because `receive` is a stable, settle-once Future, multiple readers
1081
+ * all observe the same value (one-time broadcast) and the worker can
1082
+ * use it in every iteration of a select-loop without leaking orphan
1083
+ * receivers.
1084
+ *
1085
+ * Multi-event streams (producer-consumer, progress events) are NOT
1086
+ * supported — Channel is intentionally single-shot. A separate
1087
+ * primitive for that use case is yet to be designed.
1088
+ */
1089
+ channel() {
1090
+ return this.sched.makeChannel();
1091
+ }
1092
+ /**
1093
+ * Per-invocation read-write key-value store. Use from a handler whose
1094
+ * underlying context is ObjectContext or WorkflowContext.
1095
+ *
1096
+ * The optional `TState` generic gives keyof-checked names and per-key
1097
+ * value types:
1098
+ *
1099
+ * ops.state<{count: number; user: User}>()
1100
+ * // state.get("count") → Future<number | null>
1101
+ *
1102
+ * Without it, names are `string` and values are inferred per call:
1103
+ *
1104
+ * ops.state()
1105
+ * // state.get<number>("count") → Future<number | null>
1106
+ *
1107
+ * Calling write methods from a shared (read-only) context throws at
1108
+ * runtime — for shared handlers, use `sharedState()` below to get a
1109
+ * narrower type that drops the write methods.
1110
+ */
1111
+ state() {
1112
+ return makeState(this.ctx, this.sched, adapt);
1113
+ }
1114
+ /**
1115
+ * Per-invocation read-only key-value store. Use from a handler whose
1116
+ * underlying context is ObjectSharedContext or WorkflowSharedContext.
1117
+ *
1118
+ * Same `TState` generic as `state()`. Returns the read-only subset
1119
+ * (`get`, `keys`); attempting to call writes is a type error.
1120
+ */
1121
+ sharedState() {
1122
+ return makeState(this.ctx, this.sched, adapt);
1123
+ }
1124
+ /**
1125
+ * Wait for every future to settle; return their values in input
1126
+ * order. Heterogeneous-tuple typing — `all([fA, fB])` where
1127
+ * `fA: Future<A>` and `fB: Future<B>` yields `Future<[A, B]>`.
1128
+ * Mirrors `Promise.all` from the standard lib.
1129
+ */
1130
+ all(futures) {
1131
+ return this.sched.all(futures);
1132
+ }
1133
+ /**
1134
+ * Return the first future to settle; losers continue running but
1135
+ * their results are discarded. Heterogeneous-tuple typing —
1136
+ * `race([fA, fB])` yields `Future<A | B>`. Mirrors `Promise.race`.
1137
+ */
1138
+ race(futures) {
1139
+ return this.sched.race(futures);
1140
+ }
1141
+ /**
1142
+ * First-success combinator. Resolves with the first input that
1143
+ * succeeds (non-rejected); rejects with `AggregateError(errors)` when
1144
+ * every input rejects (including an empty input array). See `Promise.any`.
1145
+ *
1146
+ * Tuple-aware typing — `any([fA, fB])` where `fA: Future<A>` and
1147
+ * `fB: Future<B>` yields `Future<A | B>`.
1148
+ */
1149
+ any(futures) {
1150
+ return this.sched.any(futures);
1151
+ }
1152
+ /**
1153
+ * Settle-all combinator. Resolves with an array of
1154
+ * `FutureSettledResult` in input order; never rejects. See
1155
+ * `Promise.allSettled`.
1156
+ *
1157
+ * Tuple-aware typing — `allSettled([fA, fB])` yields
1158
+ * `Future<[FutureSettledResult<A>, FutureSettledResult<B>]>`.
1159
+ */
1160
+ allSettled(futures) {
1161
+ return this.sched.allSettled(futures);
1162
+ }
1163
+ *select(branches) {
1164
+ return yield* select(branches);
1165
+ }
1166
+ };
1167
+ /**
1168
+ * Run a generator-based workflow against a Restate context.
1169
+ *
1170
+ * `op` is an `Operation<T>` — typically the result of
1171
+ * `gen(function*() { ... })`. Inside the generator body, reach for the
1172
+ * free-standing API (`run`, `sleep`, `all`, `state`, …) imported
1173
+ * from `@restatedev/restate-sdk-gen`. They read the active scheduler from a
1174
+ * synchronous current-fiber slot installed by `Fiber.advance`.
1175
+ *
1176
+ * `gen()` already takes a factory, so the same `Operation` is re-
1177
+ * iterable across multiple `execute()` calls — no need for a builder
1178
+ * lambda at this boundary.
1179
+ *
1180
+ * @example
1181
+ * execute(ctx, gen(function* () {
1182
+ * const greeting = yield* run(async () => "hi", { name: "compose" });
1183
+ * return greeting;
1184
+ * }));
1185
+ */
1186
+ async function execute(context, op) {
1187
+ const sched = new Scheduler(defaultLib);
1188
+ sched.contextSlot = new RestateOperations(context, sched);
1189
+ return sched.run(op);
1190
+ }
1191
+
1192
+ //#endregion
1193
+ //#region src/define.ts
1194
+ function makeDescriptor(inputSerde, outputSerde) {
1195
+ return {
1196
+ _inputSerde: inputSerde,
1197
+ _outputSerde: outputSerde
1198
+ };
1199
+ }
1200
+ /** HandlerDef has _genFn as an object property; bare gen fns are plain functions */
1201
+ function isHandlerDef(entry) {
1202
+ return typeof entry === "object" && entry !== null && typeof entry._genFn === "function";
1203
+ }
1204
+ /** Convert a Standard Schema to a Serde via restate.serde.schema() */
1205
+ function toSerde(schema) {
1206
+ return restate.serde.schema(schema);
1207
+ }
1208
+ function extractEntry(entry) {
1209
+ if (isHandlerDef(entry)) return {
1210
+ genFn: entry._genFn,
1211
+ inputSerde: entry._inputSerde,
1212
+ outputSerde: entry._outputSerde
1213
+ };
1214
+ return {
1215
+ genFn: entry,
1216
+ inputSerde: void 0,
1217
+ outputSerde: void 0
1218
+ };
1219
+ }
1220
+ /** serdes(opts, fn) — explicit Serde per field */
1221
+ function serdes(opts, fn) {
1222
+ return {
1223
+ _genFn: fn,
1224
+ _inputSerde: opts.input,
1225
+ _outputSerde: opts.output
1226
+ };
1227
+ }
1228
+ /** schemas(opts, fn) — Standard Schema (Zod, TypeBox, Valibot, …) per field */
1229
+ function schemas(opts, fn) {
1230
+ return {
1231
+ _genFn: fn,
1232
+ _inputSerde: toSerde(opts.input),
1233
+ _outputSerde: toSerde(opts.output)
1234
+ };
1235
+ }
1236
+ function service(config) {
1237
+ const { name, description, metadata, handlers, options } = config;
1238
+ const { handlers: perHandlerOpts,...serviceOpts } = options ?? {};
1239
+ const coreHandlers = {};
1240
+ const descriptors = {};
1241
+ for (const [handlerName, entry] of Object.entries(handlers)) {
1242
+ const { genFn, inputSerde, outputSerde } = extractEntry(entry);
1243
+ const handlerOpts = perHandlerOpts?.[handlerName] ?? {};
1244
+ coreHandlers[handlerName] = restate.handlers.handler({
1245
+ input: inputSerde,
1246
+ output: outputSerde,
1247
+ ...handlerOpts
1248
+ }, async (ctx, input) => execute(ctx, genFn(input)));
1249
+ descriptors[handlerName] = makeDescriptor(inputSerde, outputSerde);
1250
+ }
1251
+ const coreDef = restate.service({
1252
+ name,
1253
+ handlers: coreHandlers,
1254
+ description,
1255
+ metadata,
1256
+ options: serviceOpts
1257
+ });
1258
+ return Object.assign(coreDef, {
1259
+ _kind: "service",
1260
+ _handlers: descriptors
1261
+ });
1262
+ }
1263
+ function object(config) {
1264
+ const { name, description, metadata, handlers, options } = config;
1265
+ const { handlers: perHandlerOpts,...objectOpts } = options ?? {};
1266
+ const coreHandlers = {};
1267
+ const descriptors = {};
1268
+ for (const [handlerName, entry] of Object.entries(handlers)) {
1269
+ const { genFn, inputSerde, outputSerde } = extractEntry(entry);
1270
+ const { shared,...restOpts } = perHandlerOpts?.[handlerName] ?? {};
1271
+ const sdkOpts = {
1272
+ input: inputSerde,
1273
+ output: outputSerde,
1274
+ ...restOpts
1275
+ };
1276
+ const fn = async (ctx, input) => execute(ctx, genFn(input));
1277
+ coreHandlers[handlerName] = shared ? restate.handlers.object.shared(sdkOpts, fn) : restate.handlers.object.exclusive(sdkOpts, fn);
1278
+ descriptors[handlerName] = makeDescriptor(inputSerde, outputSerde);
1279
+ }
1280
+ const coreDef = restate.object({
1281
+ name,
1282
+ handlers: coreHandlers,
1283
+ description,
1284
+ metadata,
1285
+ options: objectOpts
1286
+ });
1287
+ return Object.assign(coreDef, {
1288
+ _kind: "object",
1289
+ _handlers: descriptors
1290
+ });
1291
+ }
1292
+ function workflow(config) {
1293
+ const { name, description, metadata, handlers, options } = config;
1294
+ const { handlers: perHandlerOpts,...workflowOpts } = options ?? {};
1295
+ const coreHandlers = {};
1296
+ const descriptors = {};
1297
+ for (const [handlerName, entry] of Object.entries(handlers)) {
1298
+ const { genFn, inputSerde, outputSerde } = extractEntry(entry);
1299
+ const sdkOpts = {
1300
+ input: inputSerde,
1301
+ output: outputSerde,
1302
+ ...perHandlerOpts?.[handlerName] ?? {}
1303
+ };
1304
+ const fn = async (ctx, input) => execute(ctx, genFn(input));
1305
+ coreHandlers[handlerName] = handlerName === "run" ? restate.handlers.workflow.workflow(sdkOpts, fn) : restate.handlers.workflow.shared(sdkOpts, fn);
1306
+ descriptors[handlerName] = makeDescriptor(inputSerde, outputSerde);
1307
+ }
1308
+ const coreDef = restate.workflow({
1309
+ name,
1310
+ handlers: coreHandlers,
1311
+ description,
1312
+ metadata,
1313
+ options: workflowOpts
1314
+ });
1315
+ return Object.assign(coreDef, {
1316
+ _kind: "workflow",
1317
+ _handlers: descriptors
1318
+ });
1319
+ }
1320
+
1321
+ //#endregion
1322
+ //#region src/interface.ts
1323
+ var interface_exports = /* @__PURE__ */ __export({
1324
+ implement: () => implement,
1325
+ json: () => json,
1326
+ object: () => object$1,
1327
+ schemas: () => schemas$1,
1328
+ serdes: () => serdes$1,
1329
+ service: () => service$1,
1330
+ workflow: () => workflow$1
1331
+ });
1332
+ /** json<I, O>() — type params, default JSON serde */
1333
+ function json() {
1334
+ return makeDescriptor(void 0, void 0);
1335
+ }
1336
+ /** serdes(opts) — explicit Serde per field */
1337
+ function serdes$1(opts) {
1338
+ return makeDescriptor(opts.input, opts.output);
1339
+ }
1340
+ /** schemas(opts) — Standard Schema (Zod, TypeBox, Valibot, …) per field */
1341
+ function schemas$1(opts) {
1342
+ return makeDescriptor(opts.input ? toSerde(opts.input) : void 0, opts.output ? toSerde(opts.output) : void 0);
1343
+ }
1344
+ function service$1(name, handlers) {
1345
+ return {
1346
+ name,
1347
+ _kind: "service",
1348
+ _handlers: handlers
1349
+ };
1350
+ }
1351
+ function object$1(name, handlers) {
1352
+ return {
1353
+ name,
1354
+ _kind: "object",
1355
+ _handlers: handlers
1356
+ };
1357
+ }
1358
+ function workflow$1(name, handlers) {
1359
+ return {
1360
+ name,
1361
+ _kind: "workflow",
1362
+ _handlers: handlers
1363
+ };
1364
+ }
1365
+ function implement(iface, config) {
1366
+ const handlerEntries = {};
1367
+ for (const [name, desc] of Object.entries(iface._handlers)) {
1368
+ const genFn = config.handlers[name];
1369
+ if (!genFn) throw new Error(`implement(): missing handler "${name}"`);
1370
+ handlerEntries[name] = {
1371
+ _genFn: genFn,
1372
+ _inputSerde: desc._inputSerde,
1373
+ _outputSerde: desc._outputSerde
1374
+ };
1375
+ }
1376
+ if (iface._kind === "service") return service({
1377
+ name: iface.name,
1378
+ handlers: handlerEntries,
1379
+ options: config.options
1380
+ });
1381
+ else if (iface._kind === "object") return object({
1382
+ name: iface.name,
1383
+ handlers: handlerEntries,
1384
+ options: config.options
1385
+ });
1386
+ else return workflow({
1387
+ name: iface.name,
1388
+ handlers: handlerEntries,
1389
+ options: config.options
1390
+ });
1391
+ }
1392
+
1393
+ //#endregion
1394
+ //#region src/ingress.ts
1395
+ var ingress_exports = /* @__PURE__ */ __export({
1396
+ SendOpts: () => SendOpts$1,
1397
+ client: () => client$1,
1398
+ connect: () => connect$1,
1399
+ sendClient: () => sendClient$1
1400
+ });
1401
+ /**
1402
+ * Connect to the Restate Ingress.
1403
+ *
1404
+ * @param opts connection options
1405
+ * @returns a connection the the restate ingress
1406
+ */
1407
+ function connect$1(opts) {
1408
+ return connect(opts);
1409
+ }
1410
+ function client$1(ingress, def, key) {
1411
+ return new Proxy({}, { get(_target, methodName) {
1412
+ return (...args) => {
1413
+ const { parameter, opts } = optsFromArgs(args);
1414
+ const desc = def._handlers[methodName];
1415
+ const mergedOpts = Opts$1.from({
1416
+ ...opts?.opts,
1417
+ input: opts?.opts?.input ?? desc?._inputSerde,
1418
+ output: opts?.opts?.output ?? desc?._outputSerde
1419
+ });
1420
+ return ingress.call({
1421
+ service: def.name,
1422
+ handler: methodName,
1423
+ parameter,
1424
+ key,
1425
+ opts: mergedOpts
1426
+ });
1427
+ };
1428
+ } });
1429
+ }
1430
+ function sendClient$1(ingress, def, key) {
1431
+ return new Proxy({}, { get(_target, methodName) {
1432
+ return (...args) => {
1433
+ const { parameter, opts } = optsFromArgs(args);
1434
+ const desc = def._handlers[methodName];
1435
+ const mergedOpts = SendOpts$1.from({
1436
+ ...opts?.opts,
1437
+ input: opts?.opts?.input ?? desc?._inputSerde
1438
+ });
1439
+ return ingress.send({
1440
+ service: def.name,
1441
+ handler: methodName,
1442
+ parameter,
1443
+ key,
1444
+ opts: mergedOpts
1445
+ });
1446
+ };
1447
+ } });
1448
+ }
1449
+ function optsFromArgs(args) {
1450
+ let parameter;
1451
+ let opts;
1452
+ switch (args.length) {
1453
+ case 0: break;
1454
+ case 1:
1455
+ if (args[0] instanceof Opts$1) opts = args[0];
1456
+ else if (args[0] instanceof SendOpts$1) opts = args[0];
1457
+ else parameter = args[0];
1458
+ break;
1459
+ case 2:
1460
+ parameter = args[0];
1461
+ if (args[1] instanceof Opts$1) opts = args[1];
1462
+ else if (args[1] instanceof SendOpts$1) opts = args[1];
1463
+ else throw new TypeError("The second argument must be either Opts or SendOpts");
1464
+ break;
1465
+ default: throw new TypeError("unexpected number of arguments");
1466
+ }
1467
+ return {
1468
+ parameter,
1469
+ opts
1470
+ };
1471
+ }
1472
+
1473
+ //#endregion
1474
+ export { all, allSettled, any, attach, awakeable, call, cancel, channel, client, ingress_exports as clients, date, gen, handlerRequest, interface_exports as iface, implement, invocation, logger, object, race, rand, rejectAwakeable, resolveAwakeable, run, schemas, select, send, sendClient, serde, serdes, service, sharedState, signal, sleep, spawn, state, workflow, workflowPromise, wrapActionForCancellation };
1475
+ //# sourceMappingURL=index.js.map