@rohal12/spindle 0.60.3 → 0.61.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.
Files changed (55) hide show
  1. package/README.md +1 -1
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +18671 -18510
  4. package/dist/pkg/play-worker.js +181 -0
  5. package/dist/pkg/play.js +398 -0
  6. package/dist/pkg/story-variables.js +11016 -153
  7. package/package.json +19 -1
  8. package/src/action-registry.ts +43 -3
  9. package/src/components/PassageDialog.tsx +29 -27
  10. package/src/components/dialog-close-context.ts +5 -1
  11. package/src/components/macros/Button.tsx +3 -3
  12. package/src/components/macros/Checkbox.tsx +3 -2
  13. package/src/components/macros/Cycle.tsx +3 -4
  14. package/src/components/macros/Dialog.tsx +3 -3
  15. package/src/components/macros/Listbox.tsx +3 -4
  16. package/src/components/macros/MacroLink.tsx +3 -3
  17. package/src/components/macros/MenubarButtons.tsx +3 -3
  18. package/src/components/macros/PassageDisplay.tsx +14 -9
  19. package/src/components/macros/Radiobutton.tsx +3 -2
  20. package/src/components/macros/detached-body.tsx +1 -4
  21. package/src/components/macros/input-macro.ts +10 -8
  22. package/src/define-macro.ts +0 -4
  23. package/src/execute-mutation.ts +10 -6
  24. package/src/format/fenced-code.ts +59 -0
  25. package/src/format/format-passage.ts +100 -11
  26. package/src/headless.ts +25 -1
  27. package/src/hooks/use-action.ts +44 -4
  28. package/src/hooks/use-modal-focus.ts +1 -30
  29. package/src/markup/ast.ts +4 -3
  30. package/src/markup/pair.ts +22 -9
  31. package/src/markup/parse.ts +2 -0
  32. package/src/markup/validate.ts +5 -3
  33. package/src/observe/observable-text.ts +6 -24
  34. package/src/observe/observe.ts +4 -1
  35. package/src/play/index.ts +15 -0
  36. package/src/play/optional.ts +41 -0
  37. package/src/play/protocol.ts +35 -0
  38. package/src/play/resolve-story.ts +265 -0
  39. package/src/play/session.ts +253 -0
  40. package/src/play/worker.ts +169 -0
  41. package/src/registry.ts +36 -1
  42. package/src/runtime-errors.ts +5 -0
  43. package/src/saves/save-manager.ts +48 -7
  44. package/src/saves/storage.ts +3 -1
  45. package/src/saves/types.ts +1 -0
  46. package/src/store.ts +13 -6
  47. package/src/story-init.ts +6 -1
  48. package/src/structural.ts +126 -66
  49. package/src/tooling.ts +2 -0
  50. package/src/types-drift-check.ts +55 -0
  51. package/src/utils/element-visibility.ts +61 -0
  52. package/types/headless.d.ts +14 -0
  53. package/types/index.d.ts +2 -0
  54. package/types/play.d.ts +83 -0
  55. package/types/tooling.d.ts +2 -0
package/src/registry.ts CHANGED
@@ -65,7 +65,7 @@ export function registerSubMacro(name: string): void {
65
65
  }
66
66
 
67
67
  export function isSubMacro(name: string): boolean {
68
- return subMacros.has(name);
68
+ return subMacros.has(name) || companionParents.has(name);
69
69
  }
70
70
 
71
71
  /**
@@ -227,12 +227,46 @@ export interface MacroMetadata {
227
227
  }
228
228
 
229
229
  const metadataRegistry = new NameMap<MacroMetadata>();
230
+ /** Indexed at registration, so parsing each tag does not scan every macro. */
231
+ const companionParents = new NameMap<Set<string>>();
230
232
 
231
233
  export function registerMacroMetadata(
232
234
  name: string,
233
235
  metadata: MacroMetadata,
234
236
  ): void {
237
+ const previous = metadataRegistry.get(name);
238
+ if (previous) {
239
+ for (const sub of previous.subMacros) {
240
+ const parents = companionParents.get(sub);
241
+ parents?.delete(previous.name.toLowerCase());
242
+ if (parents?.size === 0) companionParents.delete(sub);
243
+ }
244
+ }
235
245
  metadataRegistry.set(name, metadata);
246
+ for (const sub of metadata.subMacros) {
247
+ const parents = companionParents.get(sub) ?? new Set<string>();
248
+ parents.add(metadata.name.toLowerCase());
249
+ companionParents.set(sub, parents);
250
+ }
251
+ }
252
+
253
+ /** The parents declaring a branching companion (listbox options are values). */
254
+ export function branchParents(
255
+ name: string,
256
+ macros?: readonly Pick<MacroMetadata, 'name' | 'subMacros'>[],
257
+ ): string[] {
258
+ if (!macros) {
259
+ return [...(companionParents.get(name) ?? [])].filter(
260
+ (parent) => parent !== 'listbox',
261
+ );
262
+ }
263
+ return macros
264
+ .filter(
265
+ (macro) =>
266
+ macro.name.toLowerCase() !== 'listbox' &&
267
+ macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase()),
268
+ )
269
+ .map((macro) => macro.name.toLowerCase());
236
270
  }
237
271
 
238
272
  /** The declared parameters of the macro `name`, if it declares any. */
@@ -248,4 +282,5 @@ export function getMacroRegistry(): MacroMetadata[] {
248
282
 
249
283
  export function clearMetadataRegistry(): void {
250
284
  metadataRegistry.clear();
285
+ companionParents.clear();
251
286
  }
@@ -42,6 +42,11 @@ export function showRuntimeError(context: string, error: unknown): void {
42
42
  );
43
43
  }
44
44
 
45
+ /** The error for navigating to `name`, a special passage (StoryInit, ...). */
46
+ export function specialPassageError(name: string): Error {
47
+ return new Error(`Cannot navigate to special passage "${name}".`);
48
+ }
49
+
45
50
  /**
46
51
  * The error for `name`, a passage name that names no passage, used in the
47
52
  * passage `from`.
@@ -148,6 +148,7 @@ async function startNewPlaythroughNow(
148
148
  id: string = randomUUID(),
149
149
  ): Promise<string> {
150
150
  const backend = await getBackend();
151
+ await checkPlaythroughOwner(ifid, id);
151
152
  // Taking the next number is a read-modify-write other tabs do too
152
153
  await withTabLock(`spindle-playthrough-count:${ifid}`, async () => {
153
154
  const num = await nextPlaythroughNumber(ifid);
@@ -230,17 +231,44 @@ async function ensurePlaythrough(
230
231
  id: string,
231
232
  createdAt: string,
232
233
  ): Promise<void> {
233
- if (!(await hasPlaythroughNow(ifid, id))) {
234
+ if (!(await checkPlaythroughOwner(ifid, id))) {
234
235
  await (
235
236
  await getBackend()
236
237
  ).putPlaythrough({ id, ifid, createdAt, label: 'Imported' });
237
238
  }
238
239
  }
239
240
 
241
+ /** Globally keyed playthroughs must not be overwritten by another story. */
242
+ async function checkPlaythroughOwner(
243
+ ifid: string,
244
+ id: string,
245
+ ): Promise<PlaythroughRecord | undefined> {
246
+ const record = await (await getBackend()).getPlaythrough(id);
247
+ if (record && record.ifid !== ifid) {
248
+ throw new Error('Playthrough belongs to a different story');
249
+ }
250
+ return record;
251
+ }
252
+
253
+ /** Keep imports of the same source playthrough together within this story. */
254
+ async function importedPlaythrough(ifid: string, id: string): Promise<string> {
255
+ const backend = await getBackend();
256
+ const key = `${META_PREFIXES.importedPlaythroughs}${ifid}`;
257
+ const mappings = (await backend.getMeta<Record<string, string>>(key)) ?? {};
258
+ const mapped = Object.prototype.hasOwnProperty.call(mappings, id)
259
+ ? mappings[id]!
260
+ : id;
261
+ const owner = await backend.getPlaythrough(mapped);
262
+ if (!owner || owner.ifid === ifid) return mapped;
263
+ const fresh = randomUUID();
264
+ await backend.setMeta(key, { ...mappings, [id]: fresh });
265
+ return fresh;
266
+ }
267
+
240
268
  /** Whether the story has a record of the playthrough `id`. */
241
269
  async function hasPlaythroughNow(ifid: string, id: string): Promise<boolean> {
242
270
  const backend = await getBackend();
243
- return (await backend.getPlaythroughsByIfid(ifid)).some((p) => p.id === id);
271
+ return (await backend.getPlaythrough(id))?.ifid === ifid;
244
272
  }
245
273
 
246
274
  /**
@@ -277,10 +305,12 @@ export function establishPlaythrough(
277
305
  // and may belong to what another tab has done since (#356).
278
306
  const own = loadSessionPlaythrough(ifid);
279
307
  const ownExists = own !== undefined && (await hasPlaythroughNow(ifid, own));
308
+ const current = await backend.getMeta<string>(currentPlaythroughKey(ifid));
280
309
  const id = ownExists
281
310
  ? own
282
- : ((await backend.getMeta<string>(currentPlaythroughKey(ifid))) ??
283
- (await startNewPlaythroughNow(ifid)));
311
+ : current && (await hasPlaythroughNow(ifid, current))
312
+ ? current
313
+ : await startNewPlaythroughNow(ifid);
284
314
  saveSessionPlaythrough(ifid, id);
285
315
  return { id, knownSaves: await populateKnownSavesNow(ifid) };
286
316
  });
@@ -999,6 +1029,10 @@ async function prepareImport(data: unknown, ifid: string): Promise<SaveRecord> {
999
1029
  // with it, whatever its own metadata says
1000
1030
  record.meta.ifid = ifid;
1001
1031
 
1032
+ record.meta.playthroughId = await importedPlaythrough(
1033
+ ifid,
1034
+ record.meta.playthroughId,
1035
+ );
1002
1036
  await ensurePlaythrough(
1003
1037
  ifid,
1004
1038
  record.meta.playthroughId,
@@ -1131,9 +1165,16 @@ export function deletePlaythroughData(
1131
1165
  ): Promise<boolean> {
1132
1166
  return inOrder(async () => {
1133
1167
  const backend = await getBackend();
1134
- const deletedSaveIds =
1135
- await backend.deleteSavesByPlaythrough(playthroughId);
1136
- await backend.deletePlaythroughById(playthroughId);
1168
+ // Older saves may share a playthrough ID with another story. Only this
1169
+ // story's saves, slots and playthrough record belong to this deletion.
1170
+ const saves = (await backend.getSavesByIfid(ifid)).filter(
1171
+ (record) => record.meta.playthroughId === playthroughId,
1172
+ );
1173
+ const deletedSaveIds = saves.map((record) => record.meta.id);
1174
+ for (const id of deletedSaveIds) await backend.deleteSave(id);
1175
+ if (await hasPlaythroughNow(ifid, playthroughId)) {
1176
+ await backend.deletePlaythroughById(playthroughId);
1177
+ }
1137
1178
 
1138
1179
  // Clear the slots that held deleted saves (pointer and slot index)
1139
1180
  const deletedSet = new Set(deletedSaveIds);
@@ -55,6 +55,7 @@ export const META_PREFIXES = {
55
55
  autosave: 'autosave.',
56
56
  slot: 'slot.',
57
57
  slotIndex: 'slotIndex.',
58
+ importedPlaythroughs: 'importedPlaythroughs.',
58
59
  playthroughCount: 'playthroughCount.',
59
60
  currentPlaythrough: 'currentPlaythroughId.',
60
61
  } as const;
@@ -97,7 +98,7 @@ function createBackend(
97
98
  return {
98
99
  type,
99
100
  putSave: (record) => saves.put(record.meta.id, record),
100
- getSave: (id) => saves.get(id),
101
+ getSave: saves.get,
101
102
  deleteSave: (id) => saves.delete(id),
102
103
  getSavesByIfid: (ifid) => saves.find('ifid', ifid),
103
104
  deleteSavesByIfid: async (ifid) => {
@@ -107,6 +108,7 @@ function createBackend(
107
108
  deleteFound(saves, saveId, 'playthroughId', id),
108
109
 
109
110
  putPlaythrough: (record) => playthroughs.put(record.id, record),
111
+ getPlaythrough: playthroughs.get,
110
112
  getPlaythroughsByIfid: (ifid) => playthroughs.find('ifid', ifid),
111
113
  deletePlaythroughsByIfid: async (ifid) => {
112
114
  await deleteFound(playthroughs, playthroughId, 'ifid', ifid);
@@ -183,6 +183,7 @@ export interface StorageBackend {
183
183
  deleteSavesByPlaythrough(playthroughId: string): Promise<string[]>;
184
184
 
185
185
  putPlaythrough(record: PlaythroughRecord): Promise<void>;
186
+ getPlaythrough(id: string): Promise<PlaythroughRecord | undefined>;
186
187
  getPlaythroughsByIfid(ifid: string): Promise<PlaythroughRecord[]>;
187
188
  deletePlaythroughsByIfid(ifid: string): Promise<void>;
188
189
  deletePlaythroughById(id: string): Promise<void>;
package/src/store.ts CHANGED
@@ -63,7 +63,11 @@ import {
63
63
  } from './structural';
64
64
  import { getByPath } from './utils/object-path';
65
65
  import { isIndexKey } from './utils/value-kinds';
66
- import { noPassageError, showRuntimeError } from './runtime-errors';
66
+ import {
67
+ noPassageError,
68
+ showRuntimeError,
69
+ specialPassageError,
70
+ } from './runtime-errors';
67
71
  import {
68
72
  snapshotPRNG,
69
73
  restorePRNG,
@@ -108,6 +112,11 @@ const SPECIAL_PASSAGES = new Set([
108
112
  'StoryContext',
109
113
  ]);
110
114
 
115
+ /** Whether `name` is a special passage, which navigation never goes to. */
116
+ export function isSpecialPassage(name: string): boolean {
117
+ return SPECIAL_PASSAGES.has(name);
118
+ }
119
+
111
120
  // ---------------------------------------------------------------------------
112
121
  // Patch-based variable history (module-level, outside Zustand)
113
122
  // ---------------------------------------------------------------------------
@@ -844,7 +853,7 @@ function keepHookWrites(
844
853
  ): void {
845
854
  const moment = payload.history[payload.historyIndex];
846
855
  if (!moment) return;
847
- const changes = changesBetween(before, after, true);
856
+ const changes = changesBetween(before, after, true, moment.variables);
848
857
  const keys = new Set(changes.map((c) => pathKey(c.path)));
849
858
  // A write of the live value is no change to the live store, but the
850
859
  // snapshot can still hold another one: an earlier save's hooks wrote the
@@ -1394,10 +1403,8 @@ export const useStoryStore = create<StoryState>()(
1394
1403
  const { storyData } = get();
1395
1404
  if (!storyData) return;
1396
1405
 
1397
- if (SPECIAL_PASSAGES.has(passageName)) {
1398
- console.error(
1399
- `spindle: Cannot navigate to special passage "${passageName}".`,
1400
- );
1406
+ if (isSpecialPassage(passageName)) {
1407
+ console.error(`spindle: ${specialPassageError(passageName).message}`);
1401
1408
  return;
1402
1409
  }
1403
1410
 
package/src/story-init.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ActionsDisabledContext } from './hooks/use-action';
1
2
  import { h, render } from 'preact';
2
3
  import { useStoryStore, recordStoryInitState, missingPassage } from './store';
3
4
  import { parseMarkup } from './markup/parse';
@@ -49,7 +50,11 @@ export function executeStoryInit() {
49
50
  document.body.appendChild(container);
50
51
  storyInitContainer = container;
51
52
  render(
52
- h(() => renderNodes(ast), null),
53
+ h(
54
+ ActionsDisabledContext.Provider,
55
+ { value: true },
56
+ h(() => renderNodes(ast), null),
57
+ ),
53
58
  container,
54
59
  );
55
60
 
package/src/structural.ts CHANGED
@@ -676,9 +676,10 @@ export type PathChange =
676
676
  /** Holes an appended element follows (the array is sparse). */
677
677
  gap?: number;
678
678
  /**
679
- * Set where the value is the same content as before and only which
680
- * object the path refers to changed (see aliasChanges), so a store
681
- * holding equal content there still takes the write.
679
+ * A reference write (see aliasChanges), also used by diffPaths for
680
+ * another edge to an object already changed through its first path.
681
+ * A store holding equal content there still takes the write, and the
682
+ * value is adopted from the target's existing object when available.
682
683
  */
683
684
  alias?: true;
684
685
  /**
@@ -696,42 +697,83 @@ export type PathChange =
696
697
  hole?: true;
697
698
  };
698
699
 
700
+ type DiffOptions = [arrays?: boolean, target?: Record<string, unknown>];
701
+
699
702
  /**
700
703
  * The property paths where `after` differs from `before`, two objects of
701
704
  * one class: objects that merge (see isMergeable) are compared property by
702
705
  * property, any other value as a whole; with `arrays`, arrays are compared
703
- * by index too (see keyChanges).
706
+ * by index too (see keyChanges). Shared changed pairs are entered once;
707
+ * later edges write a reference to their first target object. With `target`,
708
+ * compare each distinct target object separately, keeping its own fields
709
+ * and references when the target shares differently from the live values.
704
710
  */
705
711
  export function diffPaths(
706
712
  before: Record<string, unknown>,
707
713
  after: Record<string, unknown>,
708
- arrays = false,
714
+ ...[arrays = false, target]: DiffOptions
709
715
  ): PathChange[] {
710
716
  const changes: PathChange[] = [];
711
717
  const ancestors = new Set<object>();
712
- // Pairs found equal, so a graph that shares objects is not walked once per
713
- // path to them (exponentially many), and how often a walk met a cycle
714
- const unchanged = new WeakMap<object, Set<object>>();
715
- let cuts = 0;
718
+ // Compare each pair once. A repeated changed edge refers to the object
719
+ // already changed through its first path, rather than repeating every
720
+ // descendant path (exponentially many in a shared graph).
721
+ const compared = new WeakMap<object, Map<object, boolean>>();
722
+ const targets = new WeakMap<object, WeakMap<object, WeakSet<object>>>();
723
+ const missing = new WeakMap<object, Map<object, PathChange[]>>();
716
724
  (function walk(
717
725
  b: Record<string, unknown>,
718
726
  a: Record<string, unknown>,
719
727
  path: string[],
728
+ held?: Record<string, unknown>,
720
729
  ): void {
721
- // Stop at cycles; shared (non-cyclic) references that differ are visited
722
- // per path, as each is a change there.
723
- if (ancestors.has(a)) {
724
- cuts++;
730
+ if (held) {
731
+ const byBefore = targets.get(a) ?? new WeakMap();
732
+ const seen = byBefore.get(b) ?? new WeakSet();
733
+ if (seen.has(held)) return;
734
+ seen.add(held);
735
+ byBefore.set(b, seen);
736
+ targets.set(a, byBefore);
737
+ }
738
+ // Stop at cycles; the first path already changes the object they reach.
739
+ if (!held && ancestors.has(a)) return;
740
+ const pairs = compared.get(a);
741
+ if (!held && pairs?.has(b)) {
742
+ if (pairs.get(b)) {
743
+ changes.push({ path, deleted: false, value: a, alias: true });
744
+ }
725
745
  return;
726
746
  }
727
- if (unchanged.get(a)?.has(b)) return;
728
- ancestors.add(a);
747
+ if (!held) ancestors.add(a);
729
748
  const found = changes.length;
730
- const cutsBefore = cuts;
731
749
  for (const change of keyChanges(b, a, arrays)) {
732
750
  const at = [...path, change.key];
733
751
  if (change.kind === 'nested') {
734
- walk(change.before, change.after, at);
752
+ const child =
753
+ held && hasOwn(held, change.key) ? held[change.key] : undefined;
754
+ if (!held || mergesWith(child, change.after, arrays)) {
755
+ walk(
756
+ change.before,
757
+ change.after,
758
+ at,
759
+ child as Record<string, unknown> | undefined,
760
+ );
761
+ } else {
762
+ // Keep descendant paths when the target lacks their parent, so
763
+ // the writer can copy that parent without changing object lookup.
764
+ const known =
765
+ missing.get(change.after) ?? new Map<object, PathChange[]>();
766
+ if (!known.has(change.before)) {
767
+ known.set(
768
+ change.before,
769
+ diffPaths(change.before, change.after, arrays),
770
+ );
771
+ missing.set(change.after, known);
772
+ }
773
+ for (const nested of known.get(change.before)!) {
774
+ changes.push({ ...nested, path: [...at, ...nested.path] });
775
+ }
776
+ }
735
777
  } else {
736
778
  changes.push(
737
779
  change.kind === 'deleted'
@@ -756,18 +798,17 @@ export function diffPaths(
756
798
  );
757
799
  }
758
800
  }
759
- // A walk that met a cycle depends on the ancestors it was reached by
760
- if (changes.length === found && cuts === cutsBefore) {
761
- const seen = unchanged.get(a) ?? new Set<object>();
762
- seen.add(b);
763
- unchanged.set(a, seen);
801
+ if (!held) {
802
+ const seen = pairs ?? new Map<object, boolean>();
803
+ seen.set(b, changes.length !== found);
804
+ compared.set(a, seen);
805
+ ancestors.delete(a);
764
806
  }
765
- ancestors.delete(a);
766
- })(before, after, []);
807
+ })(before, after, [], target);
767
808
  return changes;
768
809
  }
769
810
 
770
- export const pathKey = (path: readonly string[]): string =>
811
+ export const pathKey = (path: readonly ObjectPathSegment[]): string =>
771
812
  JSON.stringify(path);
772
813
 
773
814
  /** Whether `path`, or one of its ancestors, is one of `keys`. */
@@ -786,21 +827,31 @@ export function underChange(
786
827
  * for the `cause` or `errors` of an Error ('c', 'e'), or for the buffer a
787
828
  * typed array or DataView views ('b').
788
829
  */
789
- const entryKey = (
790
- kind: 'k' | 'v' | 's' | 'c' | 'e' | 'b',
791
- index: number,
792
- ): string => `\0${kind}${index}`;
830
+ interface EntrySegment {
831
+ kind: 'k' | 'v' | 's' | 'c' | 'e' | 'b';
832
+ index: number;
833
+ }
834
+
835
+ /** Internal graph paths distinguish built-in entries from every own key. */
836
+ export type ObjectPathSegment = string | EntrySegment;
837
+ export type ObjectPath = ObjectPathSegment[];
838
+
839
+ const entryKey = (kind: EntrySegment['kind'], index: number): EntrySegment => ({
840
+ kind,
841
+ index,
842
+ });
793
843
 
794
- export const isEntryKey = (segment: string): boolean =>
795
- segment.startsWith('\0');
844
+ export const isEntryKey = (
845
+ segment: ObjectPathSegment,
846
+ ): segment is EntrySegment => typeof segment !== 'string';
796
847
 
797
848
  /**
798
849
  * What a Map, Set, Error or view holds in place of properties (keys and
799
850
  * values, members, `cause` and `errors`, the buffer), each with the segment standing for it in
800
851
  * a path (see entryKey); undefined for any other value.
801
852
  */
802
- function entryChildren(value: object): [string, unknown][] | undefined {
803
- const children: [string, unknown][] = [];
853
+ function entryChildren(value: object): [EntrySegment, unknown][] | undefined {
854
+ const children: [EntrySegment, unknown][] = [];
804
855
  if (value instanceof Map) {
805
856
  let index = 0;
806
857
  for (const [k, v] of mapEntries(value)) {
@@ -834,19 +885,20 @@ function entryChildren(value: object): [string, unknown][] | undefined {
834
885
  * The value at `path` below `root`, where a path may go through the entries
835
886
  * of Maps, Sets and Errors (see objectPaths) as well as properties.
836
887
  */
837
- export function getByEntryPath(root: object, path: readonly string[]): unknown {
888
+ export function getByEntryPath(
889
+ root: object,
890
+ path: readonly ObjectPathSegment[],
891
+ ): unknown {
838
892
  let current: unknown = root;
839
- let start = 0;
840
- for (let i = 0; i < path.length; i++) {
841
- if (!isEntryKey(path[i]!)) continue;
842
- current = getByPath(current as object, path.slice(start, i));
893
+ for (const segment of path) {
843
894
  if (!isObjectValue(current)) return undefined;
844
- current = entryChildren(current)?.find(([at]) => at === path[i])?.[1];
845
- start = i + 1;
895
+ current = isEntryKey(segment)
896
+ ? entryChildren(current)?.find(
897
+ ([at]) => at.kind === segment.kind && at.index === segment.index,
898
+ )?.[1]
899
+ : getByPath(current, [segment]);
846
900
  }
847
- return start === path.length
848
- ? current
849
- : getByPath(current as object, path.slice(start));
901
+ return current;
850
902
  }
851
903
 
852
904
  /**
@@ -856,13 +908,14 @@ export function getByEntryPath(root: object, path: readonly string[]): unknown {
856
908
  */
857
909
  function setEntryValue(
858
910
  root: object,
859
- path: readonly string[],
911
+ path: readonly ObjectPathSegment[],
860
912
  value: unknown,
861
913
  ): boolean {
862
914
  const holder = getByEntryPath(root, path.slice(0, -1));
863
- const match = /^\0v(\d+)$/.exec(path[path.length - 1]!);
864
- if (!(holder instanceof Map) || !match) return false;
865
- const entry = [...mapEntries(holder)][Number(match[1])];
915
+ const segment = path[path.length - 1]!;
916
+ if (!(holder instanceof Map) || !isEntryKey(segment) || segment.kind !== 'v')
917
+ return false;
918
+ const entry = [...mapEntries(holder)][segment.index];
866
919
  if (!entry) return false;
867
920
  mapSet(holder, entry[0], value);
868
921
  return true;
@@ -907,10 +960,10 @@ function objectPaths(
907
960
  root: object,
908
961
  skip: ReadonlySet<string> = new Set(),
909
962
  entries = false,
910
- ): Map<object, string[][]> {
911
- const all = new Map<object, string[][]>();
912
- const collections: [object, string[]][] = [];
913
- function place(value: object, at: string[]): void {
963
+ ): Map<object, ObjectPath[]> {
964
+ const all = new Map<object, ObjectPath[]>();
965
+ const collections: [object, ObjectPath][] = [];
966
+ function place(value: object, at: ObjectPath): void {
914
967
  const known = all.get(value);
915
968
  if (known) {
916
969
  known.push(at);
@@ -926,7 +979,7 @@ function objectPaths(
926
979
  }
927
980
  function walk(
928
981
  node: Record<string, unknown>,
929
- path: string[],
982
+ path: ObjectPath,
930
983
  keys: string[] = Object.keys(node),
931
984
  ): void {
932
985
  for (const key of keys) {
@@ -951,7 +1004,7 @@ function firstPaths(
951
1004
  root: object,
952
1005
  skip?: ReadonlySet<string>,
953
1006
  entries?: boolean,
954
- ): Map<object, string[]> {
1007
+ ): Map<object, ObjectPath> {
955
1008
  return new Map(
956
1009
  [...objectPaths(root, skip, entries)].map(([object, paths]) => [
957
1010
  object,
@@ -965,7 +1018,7 @@ function firstPaths(
965
1018
  * refer to, or one that refers to itself), with every path they are at,
966
1019
  * parents before children.
967
1020
  */
968
- export function sharedPaths(root: object): string[][][] {
1021
+ export function sharedPaths(root: object): ObjectPath[][] {
969
1022
  return [...objectPaths(root, undefined, true).values()].filter(
970
1023
  (paths) => paths.length > 1,
971
1024
  );
@@ -982,11 +1035,11 @@ export function sharedPaths(root: object): string[][][] {
982
1035
  function aliasMoved(
983
1036
  x: object,
984
1037
  y: object,
985
- at: string[],
986
- earlier: ReadonlyMap<object, string[]>,
987
- later: ReadonlyMap<object, string[]>,
1038
+ at: ObjectPath,
1039
+ earlier: ReadonlyMap<object, ObjectPath>,
1040
+ later: ReadonlyMap<object, ObjectPath>,
988
1041
  ): boolean {
989
- const pairs: [string, unknown, unknown][] = [];
1042
+ const pairs: [ObjectPathSegment, unknown, unknown][] = [];
990
1043
  const xs = entryChildren(x);
991
1044
  const ys = entryChildren(y);
992
1045
  if (xs && ys) {
@@ -995,9 +1048,12 @@ function aliasMoved(
995
1048
  const ySize = collectionSize(y as Map<unknown, unknown>);
996
1049
  if (collectionSize(x) !== ySize) return false;
997
1050
  }
998
- const held = new Map(ys);
1051
+ const held = new Map(
1052
+ ys.map(([segment, value]) => [pathKey([segment]), value]),
1053
+ );
999
1054
  for (const [segment, a] of xs) {
1000
- if (held.has(segment)) pairs.push([segment, a, held.get(segment)]);
1055
+ const key = pathKey([segment]);
1056
+ if (held.has(key)) pairs.push([segment, a, held.get(key)]);
1001
1057
  }
1002
1058
  }
1003
1059
  // The properties both hold: of objects that merge, and the fields of a
@@ -1088,8 +1144,9 @@ export function changesBetween(
1088
1144
  before: Record<string, unknown>,
1089
1145
  after: Record<string, unknown>,
1090
1146
  arrays = false,
1147
+ target?: Record<string, unknown>,
1091
1148
  ): PathChange[] {
1092
- const written = diffPaths(before, after, arrays);
1149
+ const written = diffPaths(before, after, arrays, target);
1093
1150
  const keys = new Set(written.map((c) => pathKey(c.path)));
1094
1151
  const aliases: PathChange[] = [];
1095
1152
  for (const change of aliasChanges(before, after)) {
@@ -1108,7 +1165,7 @@ export function changesBetween(
1108
1165
  export function locateObjects(
1109
1166
  source: object,
1110
1167
  changes: readonly PathChange[],
1111
- ): Map<object, string[]> {
1168
+ ): Map<object, ObjectPath> {
1112
1169
  return firstPaths(
1113
1170
  source as Record<string, unknown>,
1114
1171
  new Set(changes.map((c) => pathKey(c.path))),
@@ -1124,7 +1181,7 @@ export function locateObjects(
1124
1181
  * when met, not up front.
1125
1182
  */
1126
1183
  export function existingObjects(
1127
- paths: ReadonlyMap<object, string[]>,
1184
+ paths: ReadonlyMap<object, ObjectPath>,
1128
1185
  target: object,
1129
1186
  ): Map<object, object> {
1130
1187
  return new (class extends Map<object, object> {
@@ -1164,11 +1221,14 @@ export function isApplied(target: object, change: PathChange): boolean {
1164
1221
  */
1165
1222
  export function relinkPath(
1166
1223
  root: Record<string, unknown>,
1167
- path: readonly string[],
1224
+ path: readonly ObjectPathSegment[],
1168
1225
  object: object,
1169
1226
  ): void {
1170
- if (path.some(isEntryKey)) setEntryValue(root, path, object);
1171
- else setByPath(root, path, object);
1227
+ if (path.every((segment): segment is string => !isEntryKey(segment))) {
1228
+ setByPath(root, path, object);
1229
+ } else {
1230
+ setEntryValue(root, path, object);
1231
+ }
1172
1232
  }
1173
1233
 
1174
1234
  export function applyChange(target: object, change: PathChange): void {
package/src/tooling.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { branchParents } from './registry';
1
2
  /**
2
3
  * What the tooling entry point (`@rohal12/spindle/tooling`) bundles as
3
4
  * dist/pkg/story-variables.js: the StoryVariables parser and the markup
@@ -208,6 +209,7 @@ export function validateStoryMarkup(
208
209
  if (macro.block) blocks.add(name);
209
210
  }
210
211
  return validateMarkup(list, {
212
+ branchParents: (name) => branchParents(name, all),
211
213
  isKnownMacro: (name) => known.has(name),
212
214
  macroNames: known,
213
215
  parametersOf,