@yieldstar/core 0.4.6 → 0.5.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.
@@ -0,0 +1,833 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { WorkflowEvent } from "./event";
3
+
4
+ export type Draft<T> = T extends object
5
+ ? { -readonly [K in keyof T]: Draft<T[K]> }
6
+ : T;
7
+
8
+ export type StoreVersion = number;
9
+ export type StorePath = readonly (string | number)[];
10
+
11
+ export type StoreDefinition<Schema extends StandardSchemaV1 = StandardSchemaV1> =
12
+ {
13
+ name: string;
14
+ schema: Schema;
15
+ };
16
+
17
+ export type StoreState<Schema extends StandardSchemaV1> =
18
+ StandardSchemaV1.InferOutput<Schema>;
19
+
20
+ export type StoreKey = {
21
+ storeName: string;
22
+ storeId: string;
23
+ };
24
+
25
+ /**
26
+ * Identifies the durable workflow step performing a store operation.
27
+ * When provided to `updateStore`/`takeFromStore`, the store client records
28
+ * the committed result in an applied-steps ledger keyed by
29
+ * (storeName, storeId, executionId, stepKey), written atomically with the
30
+ * state change. A retried call with the same StoreStepId returns the recorded
31
+ * result without re-running the updater/selector/claim, making the operation
32
+ * exactly-once even if the caller crashes before persisting its own record
33
+ * of the result (e.g. the workflow heap write).
34
+ */
35
+ export type StoreStepId = {
36
+ executionId: string;
37
+ stepKey: string;
38
+ };
39
+
40
+ export type StoreSnapshot<T> = {
41
+ state: T;
42
+ instanceId: string;
43
+ version: StoreVersion;
44
+ };
45
+
46
+ export type StoreUpdateResult<T> = {
47
+ state: T;
48
+ previousVersion: StoreVersion;
49
+ version: StoreVersion;
50
+ };
51
+
52
+ export type StoreUpdateFromResult<T> =
53
+ | ({ updated: true } & StoreUpdateResult<T>)
54
+ | {
55
+ updated: false;
56
+ expectedInstanceId: string;
57
+ actualInstanceId: string;
58
+ expectedVersion: StoreVersion;
59
+ actualVersion: StoreVersion;
60
+ };
61
+
62
+ export type StoreDeleteFromResult =
63
+ | { deleted: true }
64
+ | {
65
+ deleted: false;
66
+ reason: "conflict";
67
+ expectedInstanceId: string;
68
+ actualInstanceId: string;
69
+ expectedVersion: StoreVersion;
70
+ actualVersion: StoreVersion;
71
+ }
72
+ | {
73
+ deleted: false;
74
+ reason: "not-found";
75
+ expectedInstanceId: string;
76
+ expectedVersion: StoreVersion;
77
+ };
78
+
79
+ export type StoreSelector<T, R> = (state: Readonly<T>) => R;
80
+
81
+ export type StoreTakeResult<R> =
82
+ | {
83
+ matched: true;
84
+ selected: NonNullable<R>;
85
+ instanceId: string;
86
+ version: StoreVersion;
87
+ }
88
+ | {
89
+ matched: false;
90
+ instanceId: string;
91
+ version: StoreVersion;
92
+ readPaths: StorePath[];
93
+ };
94
+
95
+ export type StoreWaiter = {
96
+ workflowId: string;
97
+ executionId: string;
98
+ stepKey: string;
99
+ event: WorkflowEvent;
100
+ storeName: string;
101
+ storeId: string;
102
+ instanceId: string;
103
+ sinceVersion: StoreVersion;
104
+ readPaths: StorePath[];
105
+ };
106
+
107
+ export type StoreMutationCommitResult =
108
+ | { status: "committed" }
109
+ | { status: "already-applied"; result: unknown }
110
+ | { status: "conflict"; snapshot: StoreSnapshot<unknown> };
111
+
112
+ export type StoreMutation = {
113
+ definition: StoreDefinition;
114
+ id: string;
115
+ expected: StoreSnapshot<unknown>;
116
+ nextState: unknown;
117
+ changedPaths: StorePath[];
118
+ stepId?: StoreStepId;
119
+ result: unknown;
120
+ };
121
+
122
+ export type RuntimeStore<T> = {
123
+ get(): Promise<StoreSnapshot<T>>;
124
+ update(updater: (draft: Draft<T>) => void | T): Promise<StoreUpdateResult<T>>;
125
+ updateFrom(
126
+ snapshot: StoreSnapshot<T>,
127
+ updater: (draft: Draft<T>) => void | T
128
+ ): Promise<StoreUpdateFromResult<T>>;
129
+ deleteFrom(snapshot: StoreSnapshot<T>): Promise<StoreDeleteFromResult>;
130
+ };
131
+
132
+ export function defineStore<Schema extends StandardSchemaV1>(
133
+ name: string,
134
+ schema: Schema
135
+ ): StoreDefinition<Schema> {
136
+ return { name, schema };
137
+ }
138
+
139
+ export abstract class StoreClient {
140
+ store<Schema extends StandardSchemaV1>(
141
+ definition: StoreDefinition<Schema>,
142
+ id: string
143
+ ): RuntimeStore<StoreState<Schema>> {
144
+ return {
145
+ get: () =>
146
+ this.getStore({
147
+ definition,
148
+ id,
149
+ }),
150
+ update: (updater) =>
151
+ this.updateStore({
152
+ definition,
153
+ id,
154
+ updater,
155
+ }),
156
+ updateFrom: (snapshot, updater) =>
157
+ this.updateStoreFrom({
158
+ definition,
159
+ id,
160
+ snapshot,
161
+ updater,
162
+ }),
163
+ deleteFrom: (snapshot) =>
164
+ this.deleteStoreFrom({
165
+ definition,
166
+ id,
167
+ snapshot,
168
+ }),
169
+ };
170
+ }
171
+
172
+ abstract getOrCreateStore<Schema extends StandardSchemaV1>(params: {
173
+ definition: StoreDefinition<Schema>;
174
+ id: string;
175
+ initial?:
176
+ | StoreState<Schema>
177
+ | (() => StoreState<Schema> | Promise<StoreState<Schema>>);
178
+ }): Promise<StoreSnapshot<StoreState<Schema>>>;
179
+
180
+ abstract getStore<Schema extends StandardSchemaV1>(params: {
181
+ definition: StoreDefinition<Schema>;
182
+ id: string;
183
+ }): Promise<StoreSnapshot<StoreState<Schema>>>;
184
+
185
+ /**
186
+ * Updates a store's state atomically.
187
+ * Updaters must be synchronous, deterministic, and side-effect-free. CAS-backed
188
+ * clients may run an updater again when another writer wins the version race.
189
+ * A rejected promise does not prove that the mutation was rolled back: a
190
+ * connector may commit state and then fail while delivering its durable wake
191
+ * intents. Retrying is exactly-once only when the same `stepId` is supplied.
192
+ * Callers without a `stepId` must read and reconcile instead of blindly retrying.
193
+ *
194
+ * When `stepId` is provided the update is exactly-once per
195
+ * (executionId, stepKey): the committed StoreUpdateResult is recorded in
196
+ * the applied-steps ledger inside the same transaction as the state change,
197
+ * and a repeated call with the same stepId returns the recorded result
198
+ * verbatim without running the updater or bumping the version.
199
+ */
200
+ abstract updateStore<Schema extends StandardSchemaV1>(params: {
201
+ definition: StoreDefinition<Schema>;
202
+ id: string;
203
+ updater: (draft: Draft<StoreState<Schema>>) => void | StoreState<Schema>;
204
+ stepId?: StoreStepId;
205
+ }): Promise<StoreUpdateResult<StoreState<Schema>>>;
206
+
207
+ /**
208
+ * Updates a store only if it has not changed since `snapshot` was read.
209
+ * A conflict does not change the store, though a racing writer may cause a
210
+ * pure updater to have been evaluated before the conflict is observed. When `stepId`
211
+ * identifies an update that already committed, its recorded result wins
212
+ * over the version check so replay remains exactly-once.
213
+ */
214
+ abstract updateStoreFrom<Schema extends StandardSchemaV1>(params: {
215
+ definition: StoreDefinition<Schema>;
216
+ id: string;
217
+ snapshot: StoreSnapshot<StoreState<Schema>>;
218
+ updater: (draft: Draft<StoreState<Schema>>) => void | StoreState<Schema>;
219
+ stepId?: StoreStepId;
220
+ }): Promise<StoreUpdateFromResult<StoreState<Schema>>>;
221
+
222
+ /**
223
+ * Atomically selects and claims from a store. The selector and claim run
224
+ * locally against a snapshot, then commit with a single conditional version
225
+ * bump. A conflict re-runs both functions against the new snapshot. If the selector does not match, nothing is
226
+ * committed and the store's current version plus the selector's tracked
227
+ * read paths are returned so the caller can register a waiter with the
228
+ * correct sinceVersion (closing the lost-wakeup gap by construction).
229
+ *
230
+ * `claim` must be synchronous – implementations must reject (throw) if it
231
+ * returns a Promise.
232
+ *
233
+ * When `stepId` is provided, a MATCHED (committed) take is recorded in the
234
+ * applied-steps ledger inside the same transaction as the claim commit, and
235
+ * a repeated call with the same stepId returns the recorded outcome without
236
+ * re-running the selector or claim. Unmatched outcomes are NOT recorded:
237
+ * an unmatched take commits nothing and registers a waiter, so it must
238
+ * remain free to re-evaluate the selector on every wake.
239
+ */
240
+ abstract takeFromStore<Schema extends StandardSchemaV1, R>(params: {
241
+ definition: StoreDefinition<Schema>;
242
+ id: string;
243
+ selector: StoreSelector<StoreState<Schema>, R>;
244
+ claim: (
245
+ draft: Draft<StoreState<Schema>>,
246
+ selected: NonNullable<R>
247
+ ) => void;
248
+ stepId?: StoreStepId;
249
+ }): Promise<StoreTakeResult<R>>;
250
+
251
+ abstract registerWaiter(waiter: StoreWaiter): Promise<void>;
252
+
253
+ /**
254
+ * Enumerates the ids of every store created under a given definition name.
255
+ * Needed by external consumers (e.g. Notation's state backend) that treat a
256
+ * store name as a collection of instances and must list them. Order is
257
+ * ascending by id so callers get a deterministic sequence.
258
+ */
259
+ abstract listStores(definition: StoreDefinition): Promise<string[]>;
260
+
261
+ /**
262
+ * Removes a store instance and all of its associated rows (state, waiters,
263
+ * applied-steps ledger). A no-op if the store does not exist.
264
+ */
265
+ abstract deleteStore(params: {
266
+ definition: StoreDefinition;
267
+ id: string;
268
+ }): Promise<void>;
269
+
270
+ /** Deletes a store only if its instance ID and version still match the snapshot. */
271
+ abstract deleteStoreFrom(params: {
272
+ definition: StoreDefinition;
273
+ id: string;
274
+ snapshot: StoreSnapshot<unknown>;
275
+ stepId?: StoreStepId;
276
+ }): Promise<StoreDeleteFromResult>;
277
+ }
278
+
279
+ /**
280
+ * Implements store transformations as read/compute/compare-and-swap loops.
281
+ * Storage connectors only implement the atomic mutation protocol and never
282
+ * execute application callbacks while holding a storage transaction.
283
+ */
284
+ export abstract class CasStoreClient extends StoreClient {
285
+ protected abstract getAppliedStoreStep(params: {
286
+ definition: StoreDefinition;
287
+ id: string;
288
+ stepId: StoreStepId;
289
+ }): Promise<{ result: unknown } | undefined>;
290
+
291
+ /**
292
+ * Atomically compares `expected`, writes the next state, records the step
293
+ * result, and persists the changed paths for durable wake delivery.
294
+ */
295
+ protected abstract commitStoreMutation(
296
+ mutation: StoreMutation
297
+ ): Promise<StoreMutationCommitResult>;
298
+
299
+ async updateStore<Schema extends StandardSchemaV1>(params: {
300
+ definition: StoreDefinition<Schema>;
301
+ id: string;
302
+ updater: (draft: Draft<StoreState<Schema>>) => void | StoreState<Schema>;
303
+ stepId?: StoreStepId;
304
+ }): Promise<StoreUpdateResult<StoreState<Schema>>> {
305
+ const applied = await this.getAppliedResult(params);
306
+ if (applied) {
307
+ return applied.result as StoreUpdateResult<StoreState<Schema>>;
308
+ }
309
+
310
+ let snapshot = await this.getStore({
311
+ definition: params.definition,
312
+ id: params.id,
313
+ });
314
+ while (true) {
315
+ const prepared = await prepareStoreUpdate(
316
+ params.definition,
317
+ snapshot,
318
+ params.updater
319
+ );
320
+ const result: StoreUpdateResult<StoreState<Schema>> = {
321
+ state: cloneStoreState(prepared.nextState),
322
+ previousVersion: snapshot.version,
323
+ version: snapshot.version + 1,
324
+ };
325
+ const committed = await this.commitStoreMutation({
326
+ definition: params.definition,
327
+ id: params.id,
328
+ expected: snapshot,
329
+ nextState: prepared.nextState,
330
+ changedPaths: prepared.changedPaths,
331
+ stepId: params.stepId,
332
+ result,
333
+ });
334
+
335
+ if (committed.status === "committed") return result;
336
+ if (committed.status === "already-applied") {
337
+ return committed.result as StoreUpdateResult<StoreState<Schema>>;
338
+ }
339
+ snapshot = committed.snapshot as StoreSnapshot<StoreState<Schema>>;
340
+ // TODO: add a configurable retry cap/backoff policy before remote CAS
341
+ // connectors are introduced; SQLite serializes commits locally.
342
+ }
343
+ }
344
+
345
+ async updateStoreFrom<Schema extends StandardSchemaV1>(params: {
346
+ definition: StoreDefinition<Schema>;
347
+ id: string;
348
+ snapshot: StoreSnapshot<StoreState<Schema>>;
349
+ updater: (draft: Draft<StoreState<Schema>>) => void | StoreState<Schema>;
350
+ stepId?: StoreStepId;
351
+ }): Promise<StoreUpdateFromResult<StoreState<Schema>>> {
352
+ const applied = await this.getAppliedResult(params);
353
+ if (applied) {
354
+ return applied.result as StoreUpdateFromResult<StoreState<Schema>>;
355
+ }
356
+
357
+ assertStoreSnapshotInstanceId(params.snapshot);
358
+
359
+ const current = await this.getStore({
360
+ definition: params.definition,
361
+ id: params.id,
362
+ });
363
+ if (!sameStoreVersion(current, params.snapshot)) {
364
+ return storeUpdateConflict(params.snapshot, current);
365
+ }
366
+
367
+ const prepared = await prepareStoreUpdate(
368
+ params.definition,
369
+ params.snapshot,
370
+ params.updater
371
+ );
372
+ const result: StoreUpdateFromResult<StoreState<Schema>> = {
373
+ updated: true,
374
+ state: cloneStoreState(prepared.nextState),
375
+ previousVersion: params.snapshot.version,
376
+ version: params.snapshot.version + 1,
377
+ };
378
+ const committed = await this.commitStoreMutation({
379
+ definition: params.definition,
380
+ id: params.id,
381
+ expected: params.snapshot,
382
+ nextState: prepared.nextState,
383
+ changedPaths: prepared.changedPaths,
384
+ stepId: params.stepId,
385
+ result,
386
+ });
387
+
388
+ if (committed.status === "committed") return result;
389
+ if (committed.status === "already-applied") {
390
+ return committed.result as StoreUpdateFromResult<StoreState<Schema>>;
391
+ }
392
+ return storeUpdateConflict(params.snapshot, committed.snapshot);
393
+ }
394
+
395
+ async takeFromStore<Schema extends StandardSchemaV1, R>(params: {
396
+ definition: StoreDefinition<Schema>;
397
+ id: string;
398
+ selector: StoreSelector<StoreState<Schema>, R>;
399
+ claim: (
400
+ draft: Draft<StoreState<Schema>>,
401
+ selected: NonNullable<R>
402
+ ) => void;
403
+ stepId?: StoreStepId;
404
+ }): Promise<StoreTakeResult<R>> {
405
+ const applied = await this.getAppliedResult(params);
406
+ if (applied) return applied.result as StoreTakeResult<R>;
407
+
408
+ let snapshot = await this.getStore({
409
+ definition: params.definition,
410
+ id: params.id,
411
+ });
412
+ while (true) {
413
+ const previousState = cloneStoreState(snapshot.state);
414
+ const draft = cloneStoreState(previousState) as Draft<StoreState<Schema>>;
415
+ const tracked = trackStoreUpdater(draft);
416
+ const { result: selectedResult, readPaths } = trackStoreSelector(
417
+ tracked.draft as StoreState<Schema>,
418
+ params.selector
419
+ );
420
+
421
+ if (!isStoreSelectorMatch(selectedResult)) {
422
+ return {
423
+ matched: false,
424
+ instanceId: snapshot.instanceId,
425
+ version: snapshot.version,
426
+ readPaths,
427
+ };
428
+ }
429
+
430
+ const selected = unwrapTrackedValue(selectedResult) as NonNullable<R>;
431
+ assertSynchronousClaim(params.claim(tracked.draft, selected));
432
+ const prepared = await finalizeStoreMutation({
433
+ definition: params.definition,
434
+ previousState,
435
+ draft,
436
+ tracked,
437
+ });
438
+ const selectedSnapshot = cloneStoreState(selected);
439
+ const result: StoreTakeResult<R> = {
440
+ matched: true,
441
+ selected: selectedSnapshot,
442
+ instanceId: snapshot.instanceId,
443
+ version: snapshot.version + 1,
444
+ };
445
+ const committed = await this.commitStoreMutation({
446
+ definition: params.definition,
447
+ id: params.id,
448
+ expected: snapshot,
449
+ nextState: prepared.nextState,
450
+ changedPaths: prepared.changedPaths,
451
+ stepId: params.stepId,
452
+ result,
453
+ });
454
+
455
+ if (committed.status === "committed") return result;
456
+ if (committed.status === "already-applied") {
457
+ return committed.result as StoreTakeResult<R>;
458
+ }
459
+ snapshot = committed.snapshot as StoreSnapshot<StoreState<Schema>>;
460
+ // TODO: share the configurable retry cap/backoff policy with updateStore.
461
+ }
462
+ }
463
+
464
+ private getAppliedResult(params: {
465
+ definition: StoreDefinition;
466
+ id: string;
467
+ stepId?: StoreStepId;
468
+ }) {
469
+ return params.stepId
470
+ ? this.getAppliedStoreStep({
471
+ definition: params.definition,
472
+ id: params.id,
473
+ stepId: params.stepId,
474
+ })
475
+ : Promise.resolve(undefined);
476
+ }
477
+ }
478
+
479
+ async function prepareStoreUpdate<Schema extends StandardSchemaV1>(
480
+ definition: StoreDefinition<Schema>,
481
+ snapshot: StoreSnapshot<StoreState<Schema>>,
482
+ updater: (draft: Draft<StoreState<Schema>>) => void | StoreState<Schema>
483
+ ) {
484
+ const previousState = cloneStoreState(snapshot.state);
485
+ const draft = cloneStoreState(previousState) as Draft<StoreState<Schema>>;
486
+ const tracked = trackStoreUpdater(draft);
487
+ const updated = updater(tracked.draft);
488
+ assertSynchronousUpdater(updated);
489
+ const returned = updated === undefined ? undefined : unwrapTrackedValue(updated);
490
+ return finalizeStoreMutation({
491
+ definition,
492
+ previousState,
493
+ draft,
494
+ tracked,
495
+ replacement: returned,
496
+ });
497
+ }
498
+
499
+ async function finalizeStoreMutation<Schema extends StandardSchemaV1>(params: {
500
+ definition: StoreDefinition<Schema>;
501
+ previousState: StoreState<Schema>;
502
+ draft: Draft<StoreState<Schema>>;
503
+ tracked: TrackedStoreUpdater<Draft<StoreState<Schema>>>;
504
+ replacement?: unknown;
505
+ }) {
506
+ const isReplacement =
507
+ params.replacement !== undefined && params.replacement !== params.draft;
508
+ const nextState = await validateStoreState(
509
+ params.definition,
510
+ isReplacement ? params.replacement : params.draft
511
+ );
512
+ const changedPaths =
513
+ !isReplacement && (nextState as unknown) === params.draft
514
+ ? params.tracked.writePaths()
515
+ : diffStorePaths(params.previousState, nextState);
516
+ return { nextState, changedPaths };
517
+ }
518
+
519
+ function sameStoreVersion(
520
+ left: StoreSnapshot<unknown>,
521
+ right: StoreSnapshot<unknown>
522
+ ) {
523
+ return (
524
+ left.instanceId === right.instanceId && left.version === right.version
525
+ );
526
+ }
527
+
528
+ function assertStoreSnapshotInstanceId(snapshot: { instanceId?: string }) {
529
+ if (!snapshot.instanceId) {
530
+ throw new Error(
531
+ "Store snapshot is missing instanceId; read a fresh snapshot"
532
+ );
533
+ }
534
+ }
535
+
536
+ function storeUpdateConflict(
537
+ expected: StoreSnapshot<unknown>,
538
+ actual: StoreSnapshot<unknown>
539
+ ): Extract<StoreUpdateFromResult<never>, { updated: false }> {
540
+ return {
541
+ updated: false,
542
+ expectedInstanceId: expected.instanceId,
543
+ actualInstanceId: actual.instanceId,
544
+ expectedVersion: expected.version,
545
+ actualVersion: actual.version,
546
+ };
547
+ }
548
+
549
+ export function isStoreSelectorMatch<R>(
550
+ result: R
551
+ ): result is Exclude<R, undefined | null | false> {
552
+ return result !== undefined && result !== null && result !== false;
553
+ }
554
+
555
+ export function assertSynchronousClaim(claimResult: unknown): void {
556
+ if (
557
+ claimResult &&
558
+ typeof (claimResult as PromiseLike<unknown>).then === "function"
559
+ ) {
560
+ throw new Error("Store take claims must be synchronous");
561
+ }
562
+ }
563
+
564
+ export function assertSynchronousUpdater(updaterResult: unknown): void {
565
+ if (
566
+ updaterResult &&
567
+ typeof (updaterResult as PromiseLike<unknown>).then === "function"
568
+ ) {
569
+ throw new Error("Store updaters must be synchronous");
570
+ }
571
+ }
572
+
573
+ export async function validateStoreState<Schema extends StandardSchemaV1>(
574
+ definition: StoreDefinition<Schema>,
575
+ state: unknown
576
+ ): Promise<StoreState<Schema>> {
577
+ const result = await definition.schema["~standard"].validate(state);
578
+
579
+ if ("issues" in result && result.issues) {
580
+ const messages = result.issues.map((issue) => issue.message).join("; ");
581
+ throw new Error(`Invalid store state for "${definition.name}": ${messages}`);
582
+ }
583
+
584
+ return result.value as StoreState<Schema>;
585
+ }
586
+
587
+ export function cloneStoreState<T>(state: T): T {
588
+ if (typeof structuredClone === "function") {
589
+ try {
590
+ return structuredClone(state);
591
+ } catch {
592
+ // Fallback if structuredClone fails (e.g. for Proxy objects in JavaScriptCore)
593
+ }
594
+ }
595
+
596
+ return JSON.parse(JSON.stringify(state));
597
+ }
598
+
599
+ /**
600
+ * Diffs two store states and returns the set of changed paths.
601
+ *
602
+ * This is O(total state size). `trackStoreUpdater` records ordinary mutation
603
+ * paths in O(changes); the diff handles cases a recording proxy cannot observe:
604
+ * - the updater RETURNED a replacement state instead of mutating the draft
605
+ * - schema validation returned a transformed copy of the draft
606
+ *
607
+ * NOTE: array splices (insert/remove in the middle) report all shifted
608
+ * indices as changed, which can over-wake waiters. This is safe – wakes are
609
+ * spurious at worst, since replay re-evaluates the selector.
610
+ */
611
+ export function diffStorePaths(previous: unknown, next: unknown): StorePath[] {
612
+ const paths: StorePath[] = [];
613
+
614
+ function visit(left: unknown, right: unknown, path: StorePath) {
615
+ if (Object.is(left, right)) return;
616
+
617
+ if (!isDiffableObject(left) || !isDiffableObject(right)) {
618
+ paths.push(path);
619
+ return;
620
+ }
621
+
622
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
623
+
624
+ for (const key of keys) {
625
+ visit(
626
+ (left as Record<string, unknown>)[key],
627
+ (right as Record<string, unknown>)[key],
628
+ [...path, arrayKeyToPathSegment(key)]
629
+ );
630
+ }
631
+ }
632
+
633
+ visit(previous, next, []);
634
+ return collapseStorePaths(paths);
635
+ }
636
+
637
+ const TRACKING_TARGET = Symbol("yieldstar.trackingTarget");
638
+
639
+ /**
640
+ * Unwraps a tracking proxy (`trackStoreSelector` or `trackStoreUpdater`)
641
+ * one level, back to the object it wraps. When a selector runs over a
642
+ * write-recording draft, the selected value unwraps to the RECORDING proxy,
643
+ * so claim mutations applied through it land on the draft AND are recorded
644
+ * as write paths. Derived values (fresh arrays/objects built inside the
645
+ * selector) are returned as-is.
646
+ */
647
+ export function unwrapTrackedValue<V>(value: V): V {
648
+ if (isDiffableObject(value)) {
649
+ const target = (value as Record<PropertyKey, unknown>)[
650
+ TRACKING_TARGET as unknown as string
651
+ ];
652
+ if (target !== undefined) return target as V;
653
+ }
654
+ return value;
655
+ }
656
+
657
+ export function trackStoreSelector<T, R>(
658
+ state: T,
659
+ selector: StoreSelector<T, R>
660
+ ): { result: R; readPaths: StorePath[] } {
661
+ const paths: StorePath[] = [];
662
+ const proxies = new WeakMap<object, unknown>();
663
+
664
+ function track(value: unknown, path: StorePath): unknown {
665
+ if (!isDiffableObject(value)) return value;
666
+
667
+ const cached = proxies.get(value);
668
+ if (cached) return cached;
669
+
670
+ const proxy = new Proxy(value, {
671
+ get(target, property, receiver) {
672
+ if (typeof property === "symbol") {
673
+ if (property === TRACKING_TARGET) return target;
674
+ return Reflect.get(target, property, receiver);
675
+ }
676
+
677
+ const nextPath = [...path, arrayKeyToPathSegment(property)];
678
+ if (nextPath.length > 0) {
679
+ paths.push(nextPath);
680
+ }
681
+
682
+ const child = Reflect.get(target, property, receiver);
683
+ return track(child, nextPath);
684
+ },
685
+ set() {
686
+ throw new Error("Store selectors must not mutate state");
687
+ },
688
+ deleteProperty() {
689
+ throw new Error("Store selectors must not mutate state");
690
+ },
691
+ });
692
+
693
+ proxies.set(value, proxy);
694
+ return proxy;
695
+ }
696
+
697
+ const result = selector(track(state, []) as Readonly<T>);
698
+
699
+ return {
700
+ result,
701
+ readPaths: collapseStorePaths(paths),
702
+ };
703
+ }
704
+
705
+ export type TrackedStoreUpdater<T> = {
706
+ /** Write-recording proxy over the raw draft. Hand this to the updater. */
707
+ draft: T;
708
+ /** The collapsed set of paths written so far (O(changes), not O(state)). */
709
+ writePaths(): StorePath[];
710
+ };
711
+
712
+ /**
713
+ * Wraps a draft in a write-recording Proxy so changed paths can be derived
714
+ * from the updater's own mutations in O(changes) instead of deep-diffing the
715
+ * whole previous/next state (O(state size) – see `diffStorePaths`).
716
+ *
717
+ * - Every `set` and `deleteProperty` through the proxy records its full
718
+ * path. Mutating array methods are trapped naturally via the index/length
719
+ * sets they perform: a push onto `messages` records ["messages", 3] (and
720
+ * ["messages", "length"]), preserving prefix-match wake semantics – a
721
+ * waiter on ["messages"] still wakes via prefix intersection.
722
+ * - Reads return proxied children so nested mutations are captured, but the
723
+ * mutation itself lands on the underlying raw draft (Reflect.set on the
724
+ * target), because the mutated draft becomes the next state.
725
+ * - Values assigned through the proxy are unwrapped (top-level) so the raw
726
+ * draft never stores a proxy wrapper for the common `draft.a = draft.b`
727
+ * case. Deeper wrappers (a proxy nested inside a fresh object) are
728
+ * laundered at commit time: `cloneStoreState` always produces fresh plain
729
+ * objects (structuredClone rejects proxies and falls back to JSON), and
730
+ * the SQLite client serializes state through JSON.stringify.
731
+ * - Ambiguous traps (`defineProperty`) record conservatively. Changed paths
732
+ * only affect wake precision, never state correctness: an extra path is a
733
+ * spurious wake (safe – replay re-evaluates the selector), while a missed
734
+ * path would lose a wakeup. When in doubt, over-report.
735
+ *
736
+ * IMPORTANT: this only observes MUTATIONS of the draft. If the updater
737
+ * RETURNS a replacement state instead of mutating (the
738
+ * `updated === undefined ? draft : updated` contract), no writes go through
739
+ * the proxy – callers must detect that case and fall back to
740
+ * `diffStorePaths(previousState, replacement)`.
741
+ */
742
+ export function trackStoreUpdater<T>(target: T): TrackedStoreUpdater<T> {
743
+ const paths: StorePath[] = [];
744
+ const proxies = new WeakMap<object, unknown>();
745
+
746
+ function record(path: StorePath, property: PropertyKey) {
747
+ if (typeof property === "symbol") {
748
+ // Symbol-keyed writes are invisible to JSON state and read paths;
749
+ // record the parent path so any waiter on it still wakes.
750
+ paths.push(path);
751
+ return;
752
+ }
753
+ paths.push([...path, arrayKeyToPathSegment(String(property))]);
754
+ }
755
+
756
+ function track(value: unknown, path: StorePath): unknown {
757
+ if (!isDiffableObject(value)) return value;
758
+
759
+ const cached = proxies.get(value);
760
+ if (cached) return cached;
761
+
762
+ const proxy = new Proxy(value, {
763
+ get(target, property, receiver) {
764
+ if (typeof property === "symbol") {
765
+ if (property === TRACKING_TARGET) return target;
766
+ return Reflect.get(target, property, receiver);
767
+ }
768
+
769
+ // Read without the proxy receiver so any getters run against the
770
+ // raw draft, then wrap the child so nested mutations are captured.
771
+ const child = Reflect.get(target, property);
772
+ return track(child, [...path, arrayKeyToPathSegment(property)]);
773
+ },
774
+ set(target, property, value) {
775
+ record(path, property);
776
+ // Unwrap so the raw draft never stores a proxy wrapper, and set on
777
+ // the raw target (no proxy receiver) so the draft receives the
778
+ // mutation directly.
779
+ return Reflect.set(target, property, unwrapTrackedValue(value));
780
+ },
781
+ deleteProperty(target, property) {
782
+ record(path, property);
783
+ return Reflect.deleteProperty(target, property);
784
+ },
785
+ defineProperty(target, property, descriptor) {
786
+ record(path, property);
787
+ if ("value" in descriptor) {
788
+ descriptor = { ...descriptor, value: unwrapTrackedValue(descriptor.value) };
789
+ }
790
+ return Reflect.defineProperty(target, property, descriptor);
791
+ },
792
+ });
793
+
794
+ proxies.set(value, proxy);
795
+ return proxy;
796
+ }
797
+
798
+ return {
799
+ draft: track(target, []) as T,
800
+ writePaths: () => collapseStorePaths(paths),
801
+ };
802
+ }
803
+
804
+ export function storePathsIntersect(
805
+ readPaths: StorePath[],
806
+ writePaths: StorePath[]
807
+ ): boolean {
808
+ return readPaths.some((readPath) =>
809
+ writePaths.some(
810
+ (writePath) =>
811
+ isPathPrefix(readPath, writePath) || isPathPrefix(writePath, readPath)
812
+ )
813
+ );
814
+ }
815
+
816
+ function collapseStorePaths(paths: StorePath[]): StorePath[] {
817
+ const unique = new Map(paths.map((path) => [path.join("\u0000"), path]));
818
+ return [...unique.values()];
819
+ }
820
+
821
+ function isPathPrefix(prefix: StorePath, path: StorePath): boolean {
822
+ if (prefix.length > path.length) return false;
823
+ return prefix.every((segment, index) => segment === path[index]);
824
+ }
825
+
826
+ function isDiffableObject(value: unknown): value is Record<string, unknown> {
827
+ return typeof value === "object" && value !== null;
828
+ }
829
+
830
+ function arrayKeyToPathSegment(key: string): string | number {
831
+ if (/^(0|[1-9]\d*)$/.test(key)) return Number(key);
832
+ return key;
833
+ }