@rohal12/spindle 0.61.4 → 0.61.6

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.
@@ -11259,8 +11259,7 @@ function startsLikeValue(token) {
11259
11259
  const first = token[0];
11260
11260
  if (first === "\"" || first === "'" || first === "`") return true;
11261
11261
  if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
11262
- if (/\d/.test(first)) return true;
11263
- if ((first === "-" || first === "+") && token.length > 1 && /\d/.test(token[1])) return true;
11262
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
11264
11263
  if (first === "(" || first === "[" || first === "{") return true;
11265
11264
  if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
11266
11265
  if (first === "!" && token.length > 1 && token[1] !== "=") return true;
@@ -11423,7 +11422,7 @@ function readOptions(params, src, { at, spans }) {
11423
11422
  return options;
11424
11423
  }
11425
11424
  /** `inline %name` reads a transient variable; `inline % 2` is modulo. */
11426
- var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
11425
+ var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,]|\.(?!\d)|%(?![A-Za-z_]))/;
11427
11426
  /**
11428
11427
  * Where the rest of `src` is without the flag `word` as its last or first
11429
11428
  * term, or `null` if it has no such flag. Next to a binary operator the
@@ -11753,8 +11752,14 @@ function stringHolds(param) {
11753
11752
  * `parametersOf` gives the declared parameters of a macro, if it has any.
11754
11753
  */
11755
11754
  function* codeAndText(src, tokens, parametersOf) {
11756
- /** The index of the closing tag of the `name` macro opened at `t`. */
11757
- const closeOf = (t, name) => tokens.findIndex((c, k) => k > t && c.type === "macro" && c.isClose && c.name.toLowerCase() === name);
11755
+ const closeOfTextBody = (t, name) => {
11756
+ for (let k = t + 1; k < tokens.length; k++) {
11757
+ const c = tokens[k];
11758
+ if (c.type === "text") continue;
11759
+ return c.type === "macro" && c.isClose && c.name.toLowerCase() === name ? k : -1;
11760
+ }
11761
+ return -1;
11762
+ };
11758
11763
  for (let t = 0; t < tokens.length; t++) {
11759
11764
  const token = tokens[t];
11760
11765
  if (token.type === "link") {
@@ -11790,7 +11795,7 @@ function* codeAndText(src, tokens, parametersOf) {
11790
11795
  else if (token.type === "macro" && !token.isClose) {
11791
11796
  const name = token.name.toLowerCase();
11792
11797
  if (name === "do") {
11793
- const close = closeOf(t, name);
11798
+ const close = closeOfTextBody(t, name);
11794
11799
  if (close < 0) continue;
11795
11800
  yield {
11796
11801
  kind: "code",
@@ -11804,9 +11809,8 @@ function* codeAndText(src, tokens, parametersOf) {
11804
11809
  }
11805
11810
  const args = token.rawArgs;
11806
11811
  if (PASSAGE_BODIES.has(name)) {
11807
- const close = closeOf(t, name);
11808
- const body = tokens.slice(t + 1, close);
11809
- if (close > t + 1 && body.every((b) => b.type === "text")) {
11812
+ const close = closeOfTextBody(t, name);
11813
+ if (close > t + 1) {
11810
11814
  const text = src.slice(token.end, tokens[close].start);
11811
11815
  const written = text.trim();
11812
11816
  yield {
@@ -12390,6 +12394,12 @@ function registerWidgetDefinitions(nodes, passageName) {
12390
12394
  */
12391
12395
  var FrozenStateContext = createContext(null);
12392
12396
  /**
12397
+ * Whether a loop has yet to reconcile its rows with newer namespaces.
12398
+ * Queued row effects wait for that reconciliation. This differs from a
12399
+ * detached click body's permanent freeze: its initial effects still run.
12400
+ */
12401
+ var PendingIterationContext = createContext(null);
12402
+ /**
12393
12403
  * Tells a timer ({repeat}, {timed}) whether the passage it belongs to has
12394
12404
  * been left: it must not run a new body then, for that would write into the
12395
12405
  * destination's state until the outgoing tree unmounts (#410). Null outside
@@ -13254,7 +13264,8 @@ function VarDisplay({ node }) {
13254
13264
  const localsValues = useLiveLocals();
13255
13265
  const parts = name.split(".");
13256
13266
  const root = parts[0];
13257
- const storeValue = useStoryStore((s) => scope === "local" ? void 0 : ownValue(s[STORE_NAMESPACES[scope]], root));
13267
+ const state = useStoryFields("variables", "temporary", "transient");
13268
+ const storeValue = scope === "local" ? void 0 : ownValue(state[STORE_NAMESPACES[scope]], root);
13258
13269
  const sigil = SCOPE_SIGILS[scope];
13259
13270
  const nameError = variableNameError(root, sigil + root);
13260
13271
  if (nameError) return /* @__PURE__ */ jsx("span", {
@@ -15182,6 +15193,8 @@ var ERROR_HIDDEN_KEYS$1 = [
15182
15193
  ];
15183
15194
  /** Whether `key` is an index of an array element. */
15184
15195
  var isIndexKey = (key) => key !== "4294967295" && String(Number(key) >>> 0) === key;
15196
+ /** Populated own array indices, in order, without visiting holes. */
15197
+ var arrayIndices = (value) => Object.getOwnPropertyNames(value).filter(isIndexKey);
15185
15198
  /**
15186
15199
  * The own enumerable string keys of a collection (an Array, Map or Set) that
15187
15200
  * are not its elements: what an instance of a subclass may hold besides
@@ -15355,7 +15368,7 @@ function classData(value) {
15355
15368
  const extra = () => ownData(value, extraKeys(value));
15356
15369
  if (Array.isArray(value)) {
15357
15370
  const items = new Array(value.length);
15358
- for (let i = 0; i < value.length; i++) if (i in value) items[i] = value[i];
15371
+ for (const key of arrayIndices(value)) items[Number(key)] = value[Number(key)];
15359
15372
  return [
15360
15373
  "Array",
15361
15374
  items,
@@ -15480,9 +15493,9 @@ function reviveBuiltin(name, ctor, list) {
15480
15493
  /** Set the elements of a revived collection, with the built-in methods. */
15481
15494
  function fillCollection(made, contents) {
15482
15495
  if (Array.isArray(made)) {
15496
+ for (const key of arrayIndices(made)) delete made[Number(key)];
15483
15497
  made.length = contents.length;
15484
- for (let i = 0; i < contents.length; i++) if (hasOwn(contents, i)) made[i] = contents[i];
15485
- else delete made[i];
15498
+ for (const key of arrayIndices(contents)) made[Number(key)] = contents[Number(key)];
15486
15499
  } else if (made instanceof Map) {
15487
15500
  Map.prototype.clear.call(made);
15488
15501
  for (const entry of contents) {
@@ -15491,7 +15504,15 @@ function fillCollection(made, contents) {
15491
15504
  }
15492
15505
  } else {
15493
15506
  Set.prototype.clear.call(made);
15494
- for (const member of contents) Set.prototype.add.call(made, member);
15507
+ const indices = arrayIndices(contents);
15508
+ let next = 0;
15509
+ for (const key of indices) {
15510
+ const i = Number(key);
15511
+ if (i > next) Set.prototype.add.call(made, void 0);
15512
+ Set.prototype.add.call(made, contents[i]);
15513
+ next = i + 1;
15514
+ }
15515
+ if (next < contents.length) Set.prototype.add.call(made, void 0);
15495
15516
  }
15496
15517
  }
15497
15518
  /** The object of a `[KEYS_TAG, ...entries]` list (see savedData); other data as is. */
@@ -15831,7 +15852,7 @@ function deepClone(value, options = {}) {
15831
15852
  if (seen.has(obj)) return seen.get(obj);
15832
15853
  if (Array.isArray(val)) {
15833
15854
  const arr = builtin(obj, new Array(val.length));
15834
- for (let i = 0; i < val.length; i++) if (i in val) arr[i] = clone(val[i]);
15855
+ for (const key of arrayIndices(val)) arr[Number(key)] = clone(val[Number(key)]);
15835
15856
  return arr;
15836
15857
  }
15837
15858
  if (val instanceof Map) {
@@ -15957,7 +15978,7 @@ function shareEqual(prev, curr) {
15957
15978
  }
15958
15979
  if (Array.isArray(c) && Array.isArray(p)) {
15959
15980
  const out = collection(new Array(c.length));
15960
- for (let i = 0; i < c.length; i++) if (i in c) out[i] = share(p[i], c[i]);
15981
+ for (const key of arrayIndices(c)) out[Number(key)] = shareKey(key);
15961
15982
  return out;
15962
15983
  }
15963
15984
  if (mergesWith(p, c, false)) {
@@ -16042,8 +16063,7 @@ function equal(a, b, assumed) {
16042
16063
  if (Array.isArray(a)) {
16043
16064
  const bc = b;
16044
16065
  if (a.length !== bc.length) return false;
16045
- for (let i = 0; i < a.length; i++) if (i in a !== i in bc || !equal(a[i], bc[i], assumed)) return false;
16046
- return equalExtraKeys(a, b, assumed);
16066
+ return equalKeys(a, b, assumed, (v) => arrayIndices(v)) && equalExtraKeys(a, b, assumed);
16047
16067
  }
16048
16068
  return equalKeys(a, b, assumed);
16049
16069
  }
@@ -16096,8 +16116,10 @@ function keyChanges(before, after, arrays) {
16096
16116
  if (Array.isArray(after)) {
16097
16117
  const b = before;
16098
16118
  const a = after;
16099
- for (let i = 0; i < Math.min(b.length, a.length); i++) {
16100
- const key = String(i);
16119
+ const indices = [.../* @__PURE__ */ new Set([...arrayIndices(b), ...arrayIndices(a)])].sort((x, y) => Number(x) - Number(y));
16120
+ for (const key of indices) {
16121
+ const i = Number(key);
16122
+ if (i >= Math.min(b.length, a.length)) continue;
16101
16123
  if (i in b && i in a) compare(key, b[i], a[i]);
16102
16124
  else if (i in b) changes.push({
16103
16125
  key,
@@ -16111,8 +16133,9 @@ function keyChanges(before, after, arrays) {
16111
16133
  });
16112
16134
  }
16113
16135
  let next = b.length;
16114
- for (let i = b.length; i < a.length; i++) {
16115
- if (!(i in a)) continue;
16136
+ for (const key of arrayIndices(a)) {
16137
+ const i = Number(key);
16138
+ if (i < b.length) continue;
16116
16139
  const gap = i - next;
16117
16140
  changes.push({
16118
16141
  key: String(i),
@@ -16122,8 +16145,8 @@ function keyChanges(before, after, arrays) {
16122
16145
  });
16123
16146
  next = i + 1;
16124
16147
  }
16125
- for (let i = a.length; i < b.length; i++) changes.push({
16126
- key: String(i),
16148
+ if (a.length < b.length) changes.push({
16149
+ key: String(a.length),
16127
16150
  kind: "deleted"
16128
16151
  });
16129
16152
  if (a.length > next) changes.push({
@@ -16234,8 +16257,9 @@ var entryKey = (kind, index) => ({
16234
16257
  var isEntryKey = (segment) => typeof segment !== "string";
16235
16258
  /**
16236
16259
  * What a Map, Set, Error or view holds in place of properties (keys and
16237
- * values, members, `cause` and `errors`, the buffer), each with the segment standing for it in
16238
- * a path (see entryKey); undefined for any other value.
16260
+ * values, members, `message`, `cause` and `errors`, the buffer), each with
16261
+ * the segment standing for it in a path (see entryKey); undefined for any
16262
+ * other value.
16239
16263
  */
16240
16264
  function entryChildren(value) {
16241
16265
  const children = [];
@@ -16249,7 +16273,7 @@ function entryChildren(value) {
16249
16273
  let index = 0;
16250
16274
  for (const member of setMembers(value)) children.push([entryKey("s", index++), member]);
16251
16275
  } else if (value instanceof Error) {
16252
- for (const key of ["cause", "errors"]) if (hasOwn(value, key)) children.push([entryKey(key === "cause" ? "c" : "e", 0), value[key]]);
16276
+ for (const key of ERROR_HIDDEN_KEYS$1) if (hasOwn(value, key)) children.push([entryKey(key === "message" ? "m" : key === "cause" ? "c" : "e", 0), value[key]]);
16253
16277
  } else if (ArrayBuffer.isView(value)) children.push([entryKey("b", 0), value.buffer]);
16254
16278
  else return;
16255
16279
  return children;
@@ -16281,11 +16305,13 @@ function setEntryValue(root, path, value) {
16281
16305
  return true;
16282
16306
  }
16283
16307
  /**
16284
- * The own enumerable fields of a Map, Set, Date or RegExp (an instance of a
16285
- * registered subclass may hold some besides its built-in content, #412);
16308
+ * The own enumerable fields of an Error, Map, Set, Date or RegExp (an
16309
+ * instance of a registered subclass may hold some besides its built-in
16310
+ * content, #412). Hidden Error data is visited through entryChildren;
16286
16311
  * none for any other value.
16287
16312
  */
16288
16313
  function builtinFields(value) {
16314
+ if (value instanceof Error) return Object.keys(value).filter((key) => !ERROR_HIDDEN_KEYS$1.some((hidden) => hidden === key));
16289
16315
  return value instanceof Map || value instanceof Set || value instanceof Date || value instanceof RegExp ? extraKeys(value) : [];
16290
16316
  }
16291
16317
  /** Whether `x` and `y` are built-ins of one class that may hold fields. */
@@ -16294,16 +16320,16 @@ function sameBuiltin(x, y) {
16294
16320
  }
16295
16321
  /**
16296
16322
  * Every path each object (or array, or other value) of `root` is at, the
16297
- * first appearance first, in depth-first order. Plain objects and arrays are
16298
- * entered, where first met only (an object held in an array is one object,
16299
- * however it was reached); other values are leaves. A path at or below one
16300
- * of `skip` is left out.
16323
+ * first appearance first, in depth-first order. Plain objects and arrays
16324
+ * (including non-enumerable indices) are entered, where first met only (an
16325
+ * object held in an array is one object, however it was reached); other
16326
+ * values are leaves. A path at or below one of `skip` is left out.
16301
16327
  *
16302
16328
  * With `entries`, the objects held in a Map or Set (as key, value or member)
16303
16329
  * are placed too, after everything else: one met nowhere else is at the path
16304
16330
  * of its Map or Set and the entry's segment (see entryKey), which is no path
16305
16331
  * a value can be read at (see getByEntryPath), so only to tell where an
16306
- * object is from; so are the `cause` and `errors` of an Error.
16332
+ * object is from; so are the `message`, `cause` and `errors` of an Error.
16307
16333
  */
16308
16334
  function objectPaths(root, skip = /* @__PURE__ */ new Set(), entries = false) {
16309
16335
  const all = /* @__PURE__ */ new Map();
@@ -16321,7 +16347,7 @@ function objectPaths(root, skip = /* @__PURE__ */ new Set(), entries = false) {
16321
16347
  if (entries && entryChildren(value)) collections.push([value, at]);
16322
16348
  }
16323
16349
  }
16324
- function walk(node, path, keys = Object.keys(node)) {
16350
+ function walk(node, path, keys = Array.isArray(node) ? [...arrayIndices(node), ...extraKeys(node)] : Object.keys(node)) {
16325
16351
  for (const key of keys) {
16326
16352
  const value = node[key];
16327
16353
  if (!isObjectValue(value)) continue;
@@ -16339,6 +16365,14 @@ function firstPaths(root, skip, entries) {
16339
16365
  return new Map([...objectPaths(root, skip, entries)].map(([object, paths]) => [object, paths[0]]));
16340
16366
  }
16341
16367
  /**
16368
+ * Refuse arrays whose logical length would make downstream slot scans
16369
+ * (including Immer's array freezing) excessive. Inspect populated keys and
16370
+ * collection entries only, sharing the graph walk used for structural diffs.
16371
+ */
16372
+ function assertArrayLengths(root, maxLength) {
16373
+ for (const value of objectPaths({ root }, void 0, true).keys()) if (Array.isArray(value) && value.length > maxLength) throw new RangeError(`Save arrays cannot exceed ${maxLength} elements`);
16374
+ }
16375
+ /**
16342
16376
  * The objects `root` holds at more than one path (an object two variables
16343
16377
  * refer to, or one that refers to itself), with every path they are at,
16344
16378
  * parents before children.
@@ -17297,6 +17331,7 @@ function closeAllOpenDialogs() {
17297
17331
  function isDialogShowing() {
17298
17332
  return openDialogs.length > 0 || (dialogHostCallbacks?.isOpen() ?? false);
17299
17333
  }
17334
+ var MAX_SAVE_ARRAY_LENGTH = 1e6;
17300
17335
  /** A save, export or session from a version of Spindle this one cannot read. */
17301
17336
  var IncompatibleSaveError = class extends Error {
17302
17337
  constructor() {
@@ -17346,6 +17381,7 @@ function variablePathError(err) {
17346
17381
  */
17347
17382
  function encodePayload(payload) {
17348
17383
  try {
17384
+ assertArrayLengths(payload, MAX_SAVE_ARRAY_LENGTH);
17349
17385
  return {
17350
17386
  formatVersion: 1,
17351
17387
  data: serialize({
@@ -17407,6 +17443,7 @@ function decodePayload(encoded) {
17407
17443
  if (typeof data !== "string") throw invalid();
17408
17444
  const body = deserialize(migrate(formatVersion, data));
17409
17445
  if (!isPayload(body)) throw invalid();
17446
+ assertArrayLengths(body, MAX_SAVE_ARRAY_LENGTH);
17410
17447
  assertTrustedWatchers(body.watchers ?? []);
17411
17448
  const payload = {
17412
17449
  ...body,
@@ -19195,14 +19232,24 @@ function applyReplacement(n) {
19195
19232
  * stop (#401).
19196
19233
  */
19197
19234
  var subscribeStateReplacement = replacementListeners.subscribe;
19198
- var runtimeUnsubs = [];
19235
+ var runtimeUnsubs = /* @__PURE__ */ new Set();
19199
19236
  var inRuntimePhase = false;
19200
19237
  /**
19201
19238
  * Track an unsubscribe function for automatic cleanup on restart.
19202
- * No-op if called during the startup phase (before enterRuntimePhase).
19239
+ * Return its manual cleanup, which also releases the tracked entry.
19240
+ * Startup subscriptions (before enterRuntimePhase) survive restart.
19203
19241
  */
19204
19242
  function trackRuntimeUnsub(unsub) {
19205
- if (inRuntimePhase) runtimeUnsubs.push(unsub);
19243
+ if (!inRuntimePhase) return unsub;
19244
+ let cleanup = unsub;
19245
+ const tracked = () => {
19246
+ const call = cleanup;
19247
+ cleanup = void 0;
19248
+ runtimeUnsubs.delete(tracked);
19249
+ call?.();
19250
+ };
19251
+ runtimeUnsubs.add(tracked);
19252
+ return tracked;
19206
19253
  }
19207
19254
  /** Mark the start of the runtime phase. Called before executeStoryInit(). */
19208
19255
  function enterRuntimePhase() {
@@ -19211,7 +19258,7 @@ function enterRuntimePhase() {
19211
19258
  /** Call all tracked unsubs and reset the runtime phase. */
19212
19259
  function cleanupRuntimeHandlers() {
19213
19260
  for (const unsub of runtimeUnsubs) unsub();
19214
- runtimeUnsubs = [];
19261
+ runtimeUnsubs.clear();
19215
19262
  inRuntimePhase = false;
19216
19263
  }
19217
19264
  /** A hotkey is a `KeyboardEvent.key` value; anything else disables it. */
@@ -19564,7 +19611,8 @@ var useStoryStore = create()(storyStore((set, get) => ({
19564
19611
  return;
19565
19612
  }
19566
19613
  const previousPassage = get().currentPassage;
19567
- if (replacesState(() => emit("beforenavigate", passageName))) return;
19614
+ const navigation = get().navigationId;
19615
+ if (replacesState(() => emit("beforenavigate", passageName)) || get().navigationId !== navigation) return;
19568
19616
  const patchEntry = computeVarPatches(lastNavigationVars, get().variables);
19569
19617
  set((state) => {
19570
19618
  state.temporary = createNamespace();
@@ -20933,7 +20981,7 @@ function defineMacro(config, source = "builtin") {
20933
20981
  const varExpr = segments.join(".");
20934
20982
  if (segments.includes("__proto__")) return h("span", { class: "error" }, `{${config.name}}: "$${varExpr}" cannot be bound: ${RESERVED_NAME} is reserved`);
20935
20983
  ctx.varName = varExpr;
20936
- ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
20984
+ ctx.value = getByPath(useStoryFields("variables").variables, segments);
20937
20985
  ctx.getValue = () => getByPath(readState().variables, segments);
20938
20986
  ctx.setValue = displayOnly ? refuse : (value) => {
20939
20987
  noteControlEdit(segments);
@@ -21215,8 +21263,6 @@ function stableKey(value) {
21215
21263
  return "<unkeyable>";
21216
21264
  }
21217
21265
  }
21218
- /** The key of an array slot that holds no element. */
21219
- var HOLE = "<hole>";
21220
21266
  /**
21221
21267
  * The key of `val`. `seen` numbers the objects keyed so far, in the order
21222
21268
  * they were first met.
@@ -21250,7 +21296,14 @@ function keyOf(val, seen) {
21250
21296
  seen.set(obj, seen.size);
21251
21297
  if (Array.isArray(val)) {
21252
21298
  const items = [];
21253
- for (let i = 0; i < val.length; i++) items.push(i in val ? keyOf(val[i], seen) : HOLE);
21299
+ let next = 0;
21300
+ for (const index of arrayIndices(val)) {
21301
+ const i = Number(index);
21302
+ if (i > next) items.push(`<holes ${i - next}>`);
21303
+ items.push(keyOf(val[i], seen));
21304
+ next = i + 1;
21305
+ }
21306
+ if (val.length > next) items.push(`<holes ${val.length - next}>`);
21254
21307
  return withFields(`[${items.join(",")}]`);
21255
21308
  }
21256
21309
  const atomic = atomicKey(obj, seen);
@@ -21560,9 +21613,7 @@ function createStoryAPI() {
21560
21613
  },
21561
21614
  on(event, callback) {
21562
21615
  if (event === "variableChanged") ensureVariableChangedSubscription();
21563
- const unsub = on(event, callback);
21564
- trackRuntimeUnsub(unsub);
21565
- return unsub;
21616
+ return trackRuntimeUnsub(on(event, callback));
21566
21617
  },
21567
21618
  async waitForActions() {
21568
21619
  await settleRunningActions();
@@ -23484,6 +23535,7 @@ defineMacro({
23484
23535
  const isTemp = target.startsWith("_");
23485
23536
  const name = target.slice(1);
23486
23537
  const localsUpdate = isLocal ? ctx.update : null;
23538
+ const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
23487
23539
  const prevOutput = ctx.hooks.useRef(UNSET);
23488
23540
  const lastNavigation = ctx.hooks.useRef(-1);
23489
23541
  const compute = () => computeAndApply(expr, name, isTemp, isLocal, ctx.getValues, rawArgs, prevOutput, lastNavigation, localsUpdate);
@@ -23492,7 +23544,9 @@ defineMacro({
23492
23544
  ran.current = true;
23493
23545
  compute();
23494
23546
  }
23495
- ctx.hooks.useLayoutEffect(compute, [ctx.merged]);
23547
+ ctx.hooks.useLayoutEffect(() => {
23548
+ if (!pendingIteration?.(useStoryStore.getState())) compute();
23549
+ }, [ctx.merged, pendingIteration]);
23496
23550
  return null;
23497
23551
  }
23498
23552
  });
@@ -23674,6 +23728,17 @@ defineMacro({
23674
23728
  }
23675
23729
  ],
23676
23730
  render({ rawArgs, children = [] }, ctx) {
23731
+ const enclosingFreeze = useContext(FrozenStateContext);
23732
+ const enclosingPending = useContext(PendingIterationContext);
23733
+ const [variables, temporary, , transient] = ctx.merged;
23734
+ const pending = useMemo(() => (state) => !!enclosingPending?.(state) || (state.variables !== variables || state.temporary !== temporary || state.transient !== transient) && !enclosingFreeze?.(state), [
23735
+ enclosingPending,
23736
+ enclosingFreeze,
23737
+ variables,
23738
+ temporary,
23739
+ transient
23740
+ ]);
23741
+ const freeze = useMemo(() => (state) => !!enclosingFreeze?.(state) || pending(state), [enclosingFreeze, pending]);
23677
23742
  const keys = ctx.hooks.useRef({
23678
23743
  contents: [],
23679
23744
  generations: [],
@@ -23713,9 +23778,15 @@ defineMacro({
23713
23778
  indexValue: i,
23714
23779
  children
23715
23780
  }, `${i}-${generations[i]}`));
23716
- return ctx.wrap(/* @__PURE__ */ jsx(ItemEditContext.Provider, {
23717
- value: true,
23718
- children: content
23781
+ return ctx.wrap(/* @__PURE__ */ jsx(FrozenStateContext.Provider, {
23782
+ value: freeze,
23783
+ children: /* @__PURE__ */ jsx(PendingIterationContext.Provider, {
23784
+ value: pending,
23785
+ children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
23786
+ value: true,
23787
+ children: content
23788
+ })
23789
+ })
23719
23790
  }));
23720
23791
  },
23721
23792
  text({ rawArgs, children = [] }, ctx) {
@@ -10591,8 +10591,7 @@ function startsLikeValue(token) {
10591
10591
  const first = token[0];
10592
10592
  if (first === "\"" || first === "'" || first === "`") return true;
10593
10593
  if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
10594
- if (/\d/.test(first)) return true;
10595
- if ((first === "-" || first === "+") && token.length > 1 && /\d/.test(token[1])) return true;
10594
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
10596
10595
  if (first === "(" || first === "[" || first === "{") return true;
10597
10596
  if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
10598
10597
  if (first === "!" && token.length > 1 && token[1] !== "=") return true;
@@ -10755,7 +10754,7 @@ function readOptions(params, src, { at, spans }) {
10755
10754
  return options;
10756
10755
  }
10757
10756
  /** `inline %name` reads a transient variable; `inline % 2` is modulo. */
10758
- var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
10757
+ var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,]|\.(?!\d)|%(?![A-Za-z_]))/;
10759
10758
  /**
10760
10759
  * Where the rest of `src` is without the flag `word` as its last or first
10761
10760
  * term, or `null` if it has no such flag. Next to a binary operator the
@@ -11074,8 +11073,14 @@ function stringHolds(param) {
11074
11073
  * `parametersOf` gives the declared parameters of a macro, if it has any.
11075
11074
  */
11076
11075
  function* codeAndText(src, tokens, parametersOf) {
11077
- /** The index of the closing tag of the `name` macro opened at `t`. */
11078
- const closeOf = (t, name) => tokens.findIndex((c, k) => k > t && c.type === "macro" && c.isClose && c.name.toLowerCase() === name);
11076
+ const closeOfTextBody = (t, name) => {
11077
+ for (let k = t + 1; k < tokens.length; k++) {
11078
+ const c = tokens[k];
11079
+ if (c.type === "text") continue;
11080
+ return c.type === "macro" && c.isClose && c.name.toLowerCase() === name ? k : -1;
11081
+ }
11082
+ return -1;
11083
+ };
11079
11084
  for (let t = 0; t < tokens.length; t++) {
11080
11085
  const token = tokens[t];
11081
11086
  if (token.type === "link") {
@@ -11111,7 +11116,7 @@ function* codeAndText(src, tokens, parametersOf) {
11111
11116
  else if (token.type === "macro" && !token.isClose) {
11112
11117
  const name = token.name.toLowerCase();
11113
11118
  if (name === "do") {
11114
- const close = closeOf(t, name);
11119
+ const close = closeOfTextBody(t, name);
11115
11120
  if (close < 0) continue;
11116
11121
  yield {
11117
11122
  kind: "code",
@@ -11125,9 +11130,8 @@ function* codeAndText(src, tokens, parametersOf) {
11125
11130
  }
11126
11131
  const args = token.rawArgs;
11127
11132
  if (PASSAGE_BODIES.has(name)) {
11128
- const close = closeOf(t, name);
11129
- const body = tokens.slice(t + 1, close);
11130
- if (close > t + 1 && body.every((b) => b.type === "text")) {
11133
+ const close = closeOfTextBody(t, name);
11134
+ if (close > t + 1) {
11131
11135
  const text = src.slice(token.end, tokens[close].start);
11132
11136
  const written = text.trim();
11133
11137
  yield {
@@ -24600,21 +24604,23 @@ function sameSpindleTokens(before, after) {
24600
24604
  return expected.length === found.length && expected.every((t, i) => t === found[i]);
24601
24605
  }
24602
24606
  /**
24603
- * Put each of `tokens` back in place of its placeholders (those that
24604
- * `placeholdersOf` gives for its index): the first of each.
24607
+ * Restore the first occurrence of each marker in the unchanged document.
24608
+ * Never search inserted source: literals may spell any other marker.
24605
24609
  */
24606
- function restorePlaceholders(text, tokens, placeholdersOf) {
24607
- let result = text;
24608
- tokens.forEach((token, index) => {
24609
- for (const placeholder of placeholdersOf(index)) result = result.replace(placeholder, () => token);
24610
+ function restorePlaceholders(text, groups) {
24611
+ const replacements = /* @__PURE__ */ new Map();
24612
+ for (const [tokens, placeholdersOf] of groups) tokens.forEach((token, index) => {
24613
+ for (const marker of placeholdersOf(index)) replacements.set(marker, token);
24614
+ });
24615
+ return text.replace(/<!--(?:SP|SVG):\d+-->|__SP\d+__/g, (marker) => {
24616
+ const token = replacements.get(marker);
24617
+ replacements.delete(marker);
24618
+ return token ?? marker;
24610
24619
  });
24611
- return result;
24612
24620
  }
24613
- /**
24614
- * Restore SVG blocks from placeholders.
24615
- */
24616
- function restoreSvgBlocks(text, tokens) {
24617
- return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
24621
+ /** Restore both families together, so neither can consume the other's source. */
24622
+ function restoreHtmlTokens(text, spindle, svg) {
24623
+ return restorePlaceholders(text, [[spindle, SPINDLE_PLACEHOLDERS], [svg, SVG_PLACEHOLDERS]]);
24618
24624
  }
24619
24625
  /**
24620
24626
  * Replace Spindle tokens with placeholders.
@@ -24692,12 +24698,6 @@ function replaceSpindleTokens(html) {
24692
24698
  tokens
24693
24699
  };
24694
24700
  }
24695
- /**
24696
- * Restore original Spindle tokens from placeholders.
24697
- */
24698
- function restoreSpindleTokens(text, tokens) {
24699
- return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
24700
- }
24701
24701
  //#endregion
24702
24702
  //#region src/format/format-passage.ts
24703
24703
  /** Default dedenting sub-macros. */
@@ -24859,13 +24859,17 @@ async function formatLf(text, options) {
24859
24859
  continue;
24860
24860
  }
24861
24861
  const { text: svgPlaceholdered, tokens: svgTokens } = replaceSvgBlocks(htmlText);
24862
+ if (!placeholdersIntact(svgPlaceholdered, svgTokens, SVG_PLACEHOLDERS)) {
24863
+ lines.push(...region.lines);
24864
+ continue;
24865
+ }
24862
24866
  const { text: placeholdered, tokens } = replaceSpindleTokens(svgPlaceholdered);
24863
24867
  const formatted = await formatHTML(placeholdered, prettier, prettierOptions);
24864
24868
  if (formatted === void 0 || !placeholdersIntact(formatted, tokens, SPINDLE_PLACEHOLDERS) || !placeholdersIntact(formatted, svgTokens, SVG_PLACEHOLDERS)) {
24865
24869
  lines.push(...region.lines);
24866
24870
  continue;
24867
24871
  }
24868
- const restored = restoreSvgBlocks(restoreSpindleTokens(formatted.trim(), tokens.map((t) => replaceAll(t, "\n", sentinel))), svgTokens);
24872
+ const restored = restoreHtmlTokens(formatted.trim(), tokens.map((t) => replaceAll(t, "\n", sentinel)), svgTokens);
24869
24873
  for (const fLine of restored.split("\n")) lines.push(fLine);
24870
24874
  continue;
24871
24875
  }
@@ -25051,12 +25055,14 @@ var NO_WRAP = /* @__PURE__ */ new Set([
25051
25055
  "atxHeading",
25052
25056
  "setextHeading",
25053
25057
  "table",
25054
- "listItem",
25058
+ "listOrdered",
25059
+ "listUnordered",
25055
25060
  "blockQuote",
25056
25061
  "definition",
25057
25062
  "thematicBreak",
25058
25063
  "htmlFlow",
25059
25064
  "codeText",
25065
+ "codeFenced",
25060
25066
  "link",
25061
25067
  "image"
25062
25068
  ]);
@@ -25080,6 +25086,10 @@ function wrapLines(lines, maxLen, literalLines, isBlock) {
25080
25086
  continue;
25081
25087
  }
25082
25088
  const wrapped = wordWrap(trimmed, maxLen, line.match(/^(\s*)/)?.[1] ?? "");
25089
+ if (wrapped.length > 1 && markdownLines(wrapped.join("\n"), isBlock, NO_WRAP).size) {
25090
+ result.push(line);
25091
+ continue;
25092
+ }
25083
25093
  if (line.endsWith(" ")) wrapped[wrapped.length - 1] += " ";
25084
25094
  result.push(...wrapped);
25085
25095
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.61.4",
3
+ "version": "0.61.6",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -3,6 +3,7 @@
3
3
  import { parse, stringify } from 'devalue';
4
4
  import { hasOwn } from './utils/namespace';
5
5
  import {
6
+ arrayIndices,
6
7
  extraKeys,
7
8
  mapEntries,
8
9
  regExpParts,
@@ -219,9 +220,8 @@ function classData(value: object): unknown {
219
220
  if (Array.isArray(value)) {
220
221
  // Holes stay holes
221
222
  const items = new Array(value.length) as unknown[];
222
- for (let i = 0; i < value.length; i++) {
223
- if (i in value) items[i] = value[i] as unknown;
224
- }
223
+ for (const key of arrayIndices(value))
224
+ items[Number(key)] = value[Number(key)] as unknown;
225
225
  return ['Array', items, extra()];
226
226
  }
227
227
  if (value instanceof Map) {
@@ -391,11 +391,10 @@ function reviveBuiltin(name: string, ctor: Constructor, list: unknown[]) {
391
391
  /** Set the elements of a revived collection, with the built-in methods. */
392
392
  function fillCollection(made: object, contents: unknown[]): void {
393
393
  if (Array.isArray(made)) {
394
+ for (const key of arrayIndices(made)) delete made[Number(key)];
394
395
  made.length = contents.length;
395
- for (let i = 0; i < contents.length; i++) {
396
- if (hasOwn(contents, i)) made[i] = contents[i];
397
- else delete made[i];
398
- }
396
+ for (const key of arrayIndices(contents))
397
+ made[Number(key)] = contents[Number(key)];
399
398
  } else if (made instanceof Map) {
400
399
  Map.prototype.clear.call(made);
401
400
  for (const entry of contents) {
@@ -406,7 +405,16 @@ function fillCollection(made: object, contents: unknown[]): void {
406
405
  }
407
406
  } else {
408
407
  Set.prototype.clear.call(made);
409
- for (const member of contents) Set.prototype.add.call(made, member);
408
+ // Holes contribute only undefined to a Set; do not expand a sparse list.
409
+ const indices = arrayIndices(contents);
410
+ let next = 0;
411
+ for (const key of indices) {
412
+ const i = Number(key);
413
+ if (i > next) Set.prototype.add.call(made, undefined);
414
+ Set.prototype.add.call(made, contents[i]);
415
+ next = i + 1;
416
+ }
417
+ if (next < contents.length) Set.prototype.add.call(made, undefined);
410
418
  }
411
419
  }
412
420