@rohal12/spindle 0.61.3 → 0.61.5

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.
@@ -10023,6 +10023,15 @@ function parseReferencePath(src) {
10023
10023
  nested
10024
10024
  };
10025
10025
  }
10026
+ /** Decode one dot-member identifier, including keywords and Unicode names. */
10027
+ function parseMemberIdentifier(src) {
10028
+ const { ast } = parseWithAst(`x.${src}`, "expression");
10029
+ if (ast.type !== "MemberExpression" || ast.computed) return null;
10030
+ const object = ast.object;
10031
+ const property = ast.property;
10032
+ if (object.type !== "Identifier" || object.start !== 0 || object.end !== 1 || property.type !== "Identifier" || property.start !== 2 || property.end !== src.length + 2) return null;
10033
+ return property.name;
10034
+ }
10026
10035
  /**
10027
10036
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
10028
10037
  * noting where it read a transient in `transientsRead`.
@@ -11250,8 +11259,7 @@ function startsLikeValue(token) {
11250
11259
  const first = token[0];
11251
11260
  if (first === "\"" || first === "'" || first === "`") return true;
11252
11261
  if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
11253
- if (/\d/.test(first)) return true;
11254
- if ((first === "-" || first === "+") && token.length > 1 && /\d/.test(token[1])) return true;
11262
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
11255
11263
  if (first === "(" || first === "[" || first === "{") return true;
11256
11264
  if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
11257
11265
  if (first === "!" && token.length > 1 && token[1] !== "=") return true;
@@ -11414,7 +11422,7 @@ function readOptions(params, src, { at, spans }) {
11414
11422
  return options;
11415
11423
  }
11416
11424
  /** `inline %name` reads a transient variable; `inline % 2` is modulo. */
11417
- var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
11425
+ var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,]|\.(?!\d)|%(?![A-Za-z_]))/;
11418
11426
  /**
11419
11427
  * Where the rest of `src` is without the flag `word` as its last or first
11420
11428
  * term, or `null` if it has no such flag. Next to a binary operator the
@@ -13245,7 +13253,8 @@ function VarDisplay({ node }) {
13245
13253
  const localsValues = useLiveLocals();
13246
13254
  const parts = name.split(".");
13247
13255
  const root = parts[0];
13248
- const storeValue = useStoryStore((s) => scope === "local" ? void 0 : ownValue(s[STORE_NAMESPACES[scope]], root));
13256
+ const state = useStoryFields("variables", "temporary", "transient");
13257
+ const storeValue = scope === "local" ? void 0 : ownValue(state[STORE_NAMESPACES[scope]], root);
13249
13258
  const sigil = SCOPE_SIGILS[scope];
13250
13259
  const nameError = variableNameError(root, sigil + root);
13251
13260
  if (nameError) return /* @__PURE__ */ jsx("span", {
@@ -15173,6 +15182,8 @@ var ERROR_HIDDEN_KEYS$1 = [
15173
15182
  ];
15174
15183
  /** Whether `key` is an index of an array element. */
15175
15184
  var isIndexKey = (key) => key !== "4294967295" && String(Number(key) >>> 0) === key;
15185
+ /** Populated own array indices, in order, without visiting holes. */
15186
+ var arrayIndices = (value) => Object.getOwnPropertyNames(value).filter(isIndexKey);
15176
15187
  /**
15177
15188
  * The own enumerable string keys of a collection (an Array, Map or Set) that
15178
15189
  * are not its elements: what an instance of a subclass may hold besides
@@ -15346,7 +15357,7 @@ function classData(value) {
15346
15357
  const extra = () => ownData(value, extraKeys(value));
15347
15358
  if (Array.isArray(value)) {
15348
15359
  const items = new Array(value.length);
15349
- for (let i = 0; i < value.length; i++) if (i in value) items[i] = value[i];
15360
+ for (const key of arrayIndices(value)) items[Number(key)] = value[Number(key)];
15350
15361
  return [
15351
15362
  "Array",
15352
15363
  items,
@@ -15471,9 +15482,9 @@ function reviveBuiltin(name, ctor, list) {
15471
15482
  /** Set the elements of a revived collection, with the built-in methods. */
15472
15483
  function fillCollection(made, contents) {
15473
15484
  if (Array.isArray(made)) {
15485
+ for (const key of arrayIndices(made)) delete made[Number(key)];
15474
15486
  made.length = contents.length;
15475
- for (let i = 0; i < contents.length; i++) if (hasOwn(contents, i)) made[i] = contents[i];
15476
- else delete made[i];
15487
+ for (const key of arrayIndices(contents)) made[Number(key)] = contents[Number(key)];
15477
15488
  } else if (made instanceof Map) {
15478
15489
  Map.prototype.clear.call(made);
15479
15490
  for (const entry of contents) {
@@ -15482,7 +15493,15 @@ function fillCollection(made, contents) {
15482
15493
  }
15483
15494
  } else {
15484
15495
  Set.prototype.clear.call(made);
15485
- for (const member of contents) Set.prototype.add.call(made, member);
15496
+ const indices = arrayIndices(contents);
15497
+ let next = 0;
15498
+ for (const key of indices) {
15499
+ const i = Number(key);
15500
+ if (i > next) Set.prototype.add.call(made, void 0);
15501
+ Set.prototype.add.call(made, contents[i]);
15502
+ next = i + 1;
15503
+ }
15504
+ if (next < contents.length) Set.prototype.add.call(made, void 0);
15486
15505
  }
15487
15506
  }
15488
15507
  /** The object of a `[KEYS_TAG, ...entries]` list (see savedData); other data as is. */
@@ -15822,7 +15841,7 @@ function deepClone(value, options = {}) {
15822
15841
  if (seen.has(obj)) return seen.get(obj);
15823
15842
  if (Array.isArray(val)) {
15824
15843
  const arr = builtin(obj, new Array(val.length));
15825
- for (let i = 0; i < val.length; i++) if (i in val) arr[i] = clone(val[i]);
15844
+ for (const key of arrayIndices(val)) arr[Number(key)] = clone(val[Number(key)]);
15826
15845
  return arr;
15827
15846
  }
15828
15847
  if (val instanceof Map) {
@@ -15948,7 +15967,7 @@ function shareEqual(prev, curr) {
15948
15967
  }
15949
15968
  if (Array.isArray(c) && Array.isArray(p)) {
15950
15969
  const out = collection(new Array(c.length));
15951
- for (let i = 0; i < c.length; i++) if (i in c) out[i] = share(p[i], c[i]);
15970
+ for (const key of arrayIndices(c)) out[Number(key)] = shareKey(key);
15952
15971
  return out;
15953
15972
  }
15954
15973
  if (mergesWith(p, c, false)) {
@@ -16033,8 +16052,7 @@ function equal(a, b, assumed) {
16033
16052
  if (Array.isArray(a)) {
16034
16053
  const bc = b;
16035
16054
  if (a.length !== bc.length) return false;
16036
- for (let i = 0; i < a.length; i++) if (i in a !== i in bc || !equal(a[i], bc[i], assumed)) return false;
16037
- return equalExtraKeys(a, b, assumed);
16055
+ return equalKeys(a, b, assumed, (v) => arrayIndices(v)) && equalExtraKeys(a, b, assumed);
16038
16056
  }
16039
16057
  return equalKeys(a, b, assumed);
16040
16058
  }
@@ -16087,8 +16105,10 @@ function keyChanges(before, after, arrays) {
16087
16105
  if (Array.isArray(after)) {
16088
16106
  const b = before;
16089
16107
  const a = after;
16090
- for (let i = 0; i < Math.min(b.length, a.length); i++) {
16091
- const key = String(i);
16108
+ const indices = [.../* @__PURE__ */ new Set([...arrayIndices(b), ...arrayIndices(a)])].sort((x, y) => Number(x) - Number(y));
16109
+ for (const key of indices) {
16110
+ const i = Number(key);
16111
+ if (i >= Math.min(b.length, a.length)) continue;
16092
16112
  if (i in b && i in a) compare(key, b[i], a[i]);
16093
16113
  else if (i in b) changes.push({
16094
16114
  key,
@@ -16102,8 +16122,9 @@ function keyChanges(before, after, arrays) {
16102
16122
  });
16103
16123
  }
16104
16124
  let next = b.length;
16105
- for (let i = b.length; i < a.length; i++) {
16106
- if (!(i in a)) continue;
16125
+ for (const key of arrayIndices(a)) {
16126
+ const i = Number(key);
16127
+ if (i < b.length) continue;
16107
16128
  const gap = i - next;
16108
16129
  changes.push({
16109
16130
  key: String(i),
@@ -16113,8 +16134,8 @@ function keyChanges(before, after, arrays) {
16113
16134
  });
16114
16135
  next = i + 1;
16115
16136
  }
16116
- for (let i = a.length; i < b.length; i++) changes.push({
16117
- key: String(i),
16137
+ if (a.length < b.length) changes.push({
16138
+ key: String(a.length),
16118
16139
  kind: "deleted"
16119
16140
  });
16120
16141
  if (a.length > next) changes.push({
@@ -16225,8 +16246,9 @@ var entryKey = (kind, index) => ({
16225
16246
  var isEntryKey = (segment) => typeof segment !== "string";
16226
16247
  /**
16227
16248
  * What a Map, Set, Error or view holds in place of properties (keys and
16228
- * values, members, `cause` and `errors`, the buffer), each with the segment standing for it in
16229
- * a path (see entryKey); undefined for any other value.
16249
+ * values, members, `message`, `cause` and `errors`, the buffer), each with
16250
+ * the segment standing for it in a path (see entryKey); undefined for any
16251
+ * other value.
16230
16252
  */
16231
16253
  function entryChildren(value) {
16232
16254
  const children = [];
@@ -16240,7 +16262,7 @@ function entryChildren(value) {
16240
16262
  let index = 0;
16241
16263
  for (const member of setMembers(value)) children.push([entryKey("s", index++), member]);
16242
16264
  } else if (value instanceof Error) {
16243
- for (const key of ["cause", "errors"]) if (hasOwn(value, key)) children.push([entryKey(key === "cause" ? "c" : "e", 0), value[key]]);
16265
+ 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]]);
16244
16266
  } else if (ArrayBuffer.isView(value)) children.push([entryKey("b", 0), value.buffer]);
16245
16267
  else return;
16246
16268
  return children;
@@ -16272,11 +16294,13 @@ function setEntryValue(root, path, value) {
16272
16294
  return true;
16273
16295
  }
16274
16296
  /**
16275
- * The own enumerable fields of a Map, Set, Date or RegExp (an instance of a
16276
- * registered subclass may hold some besides its built-in content, #412);
16297
+ * The own enumerable fields of an Error, Map, Set, Date or RegExp (an
16298
+ * instance of a registered subclass may hold some besides its built-in
16299
+ * content, #412). Hidden Error data is visited through entryChildren;
16277
16300
  * none for any other value.
16278
16301
  */
16279
16302
  function builtinFields(value) {
16303
+ if (value instanceof Error) return Object.keys(value).filter((key) => !ERROR_HIDDEN_KEYS$1.some((hidden) => hidden === key));
16280
16304
  return value instanceof Map || value instanceof Set || value instanceof Date || value instanceof RegExp ? extraKeys(value) : [];
16281
16305
  }
16282
16306
  /** Whether `x` and `y` are built-ins of one class that may hold fields. */
@@ -16285,16 +16309,16 @@ function sameBuiltin(x, y) {
16285
16309
  }
16286
16310
  /**
16287
16311
  * Every path each object (or array, or other value) of `root` is at, the
16288
- * first appearance first, in depth-first order. Plain objects and arrays are
16289
- * entered, where first met only (an object held in an array is one object,
16290
- * however it was reached); other values are leaves. A path at or below one
16291
- * of `skip` is left out.
16312
+ * first appearance first, in depth-first order. Plain objects and arrays
16313
+ * (including non-enumerable indices) are entered, where first met only (an
16314
+ * object held in an array is one object, however it was reached); other
16315
+ * values are leaves. A path at or below one of `skip` is left out.
16292
16316
  *
16293
16317
  * With `entries`, the objects held in a Map or Set (as key, value or member)
16294
16318
  * are placed too, after everything else: one met nowhere else is at the path
16295
16319
  * of its Map or Set and the entry's segment (see entryKey), which is no path
16296
16320
  * a value can be read at (see getByEntryPath), so only to tell where an
16297
- * object is from; so are the `cause` and `errors` of an Error.
16321
+ * object is from; so are the `message`, `cause` and `errors` of an Error.
16298
16322
  */
16299
16323
  function objectPaths(root, skip = /* @__PURE__ */ new Set(), entries = false) {
16300
16324
  const all = /* @__PURE__ */ new Map();
@@ -16312,7 +16336,7 @@ function objectPaths(root, skip = /* @__PURE__ */ new Set(), entries = false) {
16312
16336
  if (entries && entryChildren(value)) collections.push([value, at]);
16313
16337
  }
16314
16338
  }
16315
- function walk(node, path, keys = Object.keys(node)) {
16339
+ function walk(node, path, keys = Array.isArray(node) ? [...arrayIndices(node), ...extraKeys(node)] : Object.keys(node)) {
16316
16340
  for (const key of keys) {
16317
16341
  const value = node[key];
16318
16342
  if (!isObjectValue(value)) continue;
@@ -16330,6 +16354,14 @@ function firstPaths(root, skip, entries) {
16330
16354
  return new Map([...objectPaths(root, skip, entries)].map(([object, paths]) => [object, paths[0]]));
16331
16355
  }
16332
16356
  /**
16357
+ * Refuse arrays whose logical length would make downstream slot scans
16358
+ * (including Immer's array freezing) excessive. Inspect populated keys and
16359
+ * collection entries only, sharing the graph walk used for structural diffs.
16360
+ */
16361
+ function assertArrayLengths(root, maxLength) {
16362
+ 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`);
16363
+ }
16364
+ /**
16333
16365
  * The objects `root` holds at more than one path (an object two variables
16334
16366
  * refer to, or one that refers to itself), with every path they are at,
16335
16367
  * parents before children.
@@ -17288,6 +17320,7 @@ function closeAllOpenDialogs() {
17288
17320
  function isDialogShowing() {
17289
17321
  return openDialogs.length > 0 || (dialogHostCallbacks?.isOpen() ?? false);
17290
17322
  }
17323
+ var MAX_SAVE_ARRAY_LENGTH = 1e6;
17291
17324
  /** A save, export or session from a version of Spindle this one cannot read. */
17292
17325
  var IncompatibleSaveError = class extends Error {
17293
17326
  constructor() {
@@ -17337,6 +17370,7 @@ function variablePathError(err) {
17337
17370
  */
17338
17371
  function encodePayload(payload) {
17339
17372
  try {
17373
+ assertArrayLengths(payload, MAX_SAVE_ARRAY_LENGTH);
17340
17374
  return {
17341
17375
  formatVersion: 1,
17342
17376
  data: serialize({
@@ -17363,7 +17397,12 @@ function isOptionalPRNGSnapshot(value) {
17363
17397
  return isRecord$1(value) && typeof value.seed === "string" && typeof value.pull === "number" && Number.isInteger(value.pull) && value.pull >= 0;
17364
17398
  }
17365
17399
  var isMoment = (value) => isRecord$1(value) && typeof value.passage === "string" && isRecord$1(value.variables) && typeof value.timestamp === "number" && isOptionalPRNGSnapshot(value.prng);
17366
- var isWatchers = (value) => value === void 0 || Array.isArray(value) && Array.from(value).every((w) => isRecord$1(w) && typeof w.condition === "string" && isRecord$1(w.options));
17400
+ /** Visit holes too, rejecting malformed metadata before copying any entries. */
17401
+ function everyEntry(value, valid) {
17402
+ for (let i = 0; i < value.length; i++) if (!hasOwn(value, i) || !valid(value[i])) return false;
17403
+ return true;
17404
+ }
17405
+ var isWatchers = (value) => value === void 0 || Array.isArray(value) && everyEntry(value, (w) => isRecord$1(w) && typeof w.condition === "string" && isRecord$1(w.options));
17367
17406
  var isCountsMap = (value) => value === void 0 || value instanceof Map && [...value.keys()].every((k) => typeof k === "string");
17368
17407
  /**
17369
17408
  * Whether a deserialized payload is well formed: every history moment is,
@@ -17375,7 +17414,7 @@ function isPayload(value) {
17375
17414
  if (typeof value.passage !== "string" || !isRecord$1(value.variables)) return false;
17376
17415
  const { history, historyIndex } = value;
17377
17416
  if (!Array.isArray(history) || history.length === 0) return false;
17378
- if (!Array.from(history).every(isMoment)) return false;
17417
+ if (!everyEntry(history, isMoment)) return false;
17379
17418
  if (typeof historyIndex !== "number" || !Number.isInteger(historyIndex) || historyIndex < 0 || historyIndex >= history.length || history[historyIndex].passage !== value.passage) return false;
17380
17419
  return isCountsMap(value.visitCounts) && isCountsMap(value.renderCounts) && isOptionalPRNGSnapshot(value.prng) && isWatchers(value.watchers) && (value.interfaceWatchers === void 0 || typeof value.interfaceWatchers === "boolean");
17381
17420
  }
@@ -17393,6 +17432,7 @@ function decodePayload(encoded) {
17393
17432
  if (typeof data !== "string") throw invalid();
17394
17433
  const body = deserialize(migrate(formatVersion, data));
17395
17434
  if (!isPayload(body)) throw invalid();
17435
+ assertArrayLengths(body, MAX_SAVE_ARRAY_LENGTH);
17396
17436
  assertTrustedWatchers(body.watchers ?? []);
17397
17437
  const payload = {
17398
17438
  ...body,
@@ -20893,11 +20933,33 @@ function defineMacro(config, source = "builtin") {
20893
20933
  "@": "locals"
20894
20934
  }[firstToken.charAt(0)];
20895
20935
  if (kind) return h("span", { class: "error" }, `{${config.name}}: ${kind} (${firstToken}) cannot be bound to input macros`);
20896
- const varExpr = firstToken.replace(/["']/g, "").replace(/^\$/, "");
20897
- const segments = varExpr.split(".");
20936
+ if (!firstToken.startsWith("$") && firstToken.split(".")[0].includes("\\")) return h(MacroError, {
20937
+ macro: config.name,
20938
+ error: /* @__PURE__ */ new Error("Escaped binding identifiers require a literal $ story-variable sigil")
20939
+ });
20940
+ let segments;
20941
+ try {
20942
+ segments = firstToken.replace(/^\$/, "").split(".").map((segment, index) => {
20943
+ if (!segment.includes("\\")) return segment;
20944
+ if (index > 0) {
20945
+ const name = parseMemberIdentifier(segment);
20946
+ if (name === null) throw new Error("Invalid bound identifier");
20947
+ return name;
20948
+ }
20949
+ const reference = parseReferencePath(`$${segment}`);
20950
+ if (!reference || reference.nested) throw new Error("Invalid bound identifier");
20951
+ return reference.name;
20952
+ });
20953
+ } catch (error) {
20954
+ return h(MacroError, {
20955
+ macro: config.name,
20956
+ error
20957
+ });
20958
+ }
20959
+ const varExpr = segments.join(".");
20898
20960
  if (segments.includes("__proto__")) return h("span", { class: "error" }, `{${config.name}}: "$${varExpr}" cannot be bound: ${RESERVED_NAME} is reserved`);
20899
20961
  ctx.varName = varExpr;
20900
- ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
20962
+ ctx.value = getByPath(useStoryFields("variables").variables, segments);
20901
20963
  ctx.getValue = () => getByPath(readState().variables, segments);
20902
20964
  ctx.setValue = displayOnly ? refuse : (value) => {
20903
20965
  noteControlEdit(segments);
@@ -21179,8 +21241,6 @@ function stableKey(value) {
21179
21241
  return "<unkeyable>";
21180
21242
  }
21181
21243
  }
21182
- /** The key of an array slot that holds no element. */
21183
- var HOLE = "<hole>";
21184
21244
  /**
21185
21245
  * The key of `val`. `seen` numbers the objects keyed so far, in the order
21186
21246
  * they were first met.
@@ -21214,7 +21274,14 @@ function keyOf(val, seen) {
21214
21274
  seen.set(obj, seen.size);
21215
21275
  if (Array.isArray(val)) {
21216
21276
  const items = [];
21217
- for (let i = 0; i < val.length; i++) items.push(i in val ? keyOf(val[i], seen) : HOLE);
21277
+ let next = 0;
21278
+ for (const index of arrayIndices(val)) {
21279
+ const i = Number(index);
21280
+ if (i > next) items.push(`<holes ${i - next}>`);
21281
+ items.push(keyOf(val[i], seen));
21282
+ next = i + 1;
21283
+ }
21284
+ if (val.length > next) items.push(`<holes ${val.length - next}>`);
21218
21285
  return withFields(`[${items.join(",")}]`);
21219
21286
  }
21220
21287
  const atomic = atomicKey(obj, seen);
package/dist/pkg/play.js CHANGED
@@ -241,6 +241,7 @@ function workerExecArgv(execArgv) {
241
241
  * Opens a session that runs the story in a worker. There `window` is
242
242
  * happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
243
243
  * globals, but `window.foo = 1` does not make a bare global `foo`.
244
+ * Requires `trusted: true`: story code has unrestricted host Node access.
244
245
  */
245
246
  function openPlaySession(options) {
246
247
  return openPlaySessionWith(options, {
@@ -258,6 +259,7 @@ function openPlaySession(options) {
258
259
  }
259
260
  /** Internal: `openPlaySession` with the worker and headless URLs given (for tests). */
260
261
  function openPlaySessionWith(options, urls) {
262
+ if (options.trusted !== true) return Promise.reject(/* @__PURE__ */ new Error("spindle: openPlaySession() requires trusted: true; story JavaScript has unrestricted access to host Node APIs, files and environment. Only run code you trust."));
261
263
  const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
262
264
  if (typeof stepTimeoutMs !== "number" || !Number.isFinite(stepTimeoutMs) || stepTimeoutMs <= 0 || stepTimeoutMs > MAX_TIMEOUT_MS) return Promise.reject(/* @__PURE__ */ new Error(`spindle: openPlaySession(): "stepTimeoutMs" must be a positive number of milliseconds, got ${String(stepTimeoutMs)}`));
263
265
  const timeoutMessage = `spindle: play session timed out after ${stepTimeoutMs} ms (the story may be stuck in a loop)`;
@@ -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
@@ -24392,12 +24391,30 @@ function markdownOptions(options) {
24392
24391
  };
24393
24392
  }
24394
24393
  //#endregion
24394
+ //#region src/format/source-lines.ts
24395
+ /** Index a source once; locate zero-based lines without rescanning its prefixes. */
24396
+ function sourceLines(source) {
24397
+ const starts = [0];
24398
+ for (let i = 0; i < source.length; i++) if (source[i] === "\n") starts.push(i + 1);
24399
+ return (offset) => {
24400
+ let low = 0;
24401
+ let high = starts.length;
24402
+ while (low < high) {
24403
+ const middle = low + high >>> 1;
24404
+ if (starts[middle] <= offset) low = middle + 1;
24405
+ else high = middle;
24406
+ }
24407
+ return Math.max(0, low - 1);
24408
+ };
24409
+ }
24410
+ //#endregion
24395
24411
  //#region src/format/markdown-lines.ts
24396
24412
  /** Source lines belonging to the given constructs in runtime Markdown documents. */
24397
24413
  function markdownLines(source, isBlock, types) {
24398
24414
  const found = /* @__PURE__ */ new Set();
24399
24415
  if (types.size === 1 && types.has("codeFenced") && !/`{3}|~{3}/.test(source)) return found;
24400
24416
  const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
24417
+ const lineAt = sourceLines(source);
24401
24418
  function visit(nodes) {
24402
24419
  let markdown = "";
24403
24420
  const spans = [];
@@ -24409,7 +24426,7 @@ function markdownLines(source, isBlock, types) {
24409
24426
  end: markdown.length,
24410
24427
  node
24411
24428
  });
24412
- if (node.body && !(node.token.type === "macro" && node.token.name === "do")) {
24429
+ if (node.body && !(node.token.type === "macro" && node.token.name.toLowerCase() === "do")) {
24413
24430
  visit(node.body.children);
24414
24431
  for (const branch of node.body.branches) visit(branch.children);
24415
24432
  }
@@ -24417,15 +24434,24 @@ function markdownLines(source, isBlock, types) {
24417
24434
  const events = postprocess(parse(markdownOptions()).document().write(preprocess()(markdown, void 0, true)));
24418
24435
  for (const [event, token] of events) {
24419
24436
  if (event !== "enter" || !types.has(token.type)) continue;
24420
- for (const span of spans) {
24437
+ let low = 0;
24438
+ let high = spans.length;
24439
+ while (low < high) {
24440
+ const middle = low + high >>> 1;
24441
+ if (spans[middle].end <= token.start.offset) low = middle + 1;
24442
+ else high = middle;
24443
+ }
24444
+ for (let i = low; i < spans.length; i++) {
24445
+ const span = spans[i];
24446
+ if (span.start >= token.end.offset) break;
24421
24447
  const start = Math.max(token.start.offset, span.start);
24422
24448
  const end = Math.min(token.end.offset, span.end);
24423
24449
  if (start >= end) continue;
24424
24450
  const text = span.node.token.type === "text";
24425
24451
  const a = text ? span.node.start + start - span.start : span.node.start;
24426
24452
  const b = text ? span.node.start + end - span.start : span.node.end;
24427
- const first = source.slice(0, a).split("\n").length - 1;
24428
- const last = source.slice(0, Math.max(a, b - 1)).split("\n").length - 1;
24453
+ const first = lineAt(a);
24454
+ const last = lineAt(Math.max(a, b - 1));
24429
24455
  for (let line = first; line <= last; line++) found.add(line);
24430
24456
  }
24431
24457
  }
@@ -24497,7 +24523,7 @@ function scanSpindleMarkup(text) {
24497
24523
  }, true);
24498
24524
  }
24499
24525
  } else if (t.type !== "text") {
24500
- if (t.type === "macro" && t.name === "do") {
24526
+ if (t.type === "macro" && t.name.toLowerCase() === "do") {
24501
24527
  if (!t.isClose) open = t;
24502
24528
  else if (open) {
24503
24529
  doBlocks.push({
@@ -24859,13 +24885,14 @@ var WHITESPACE_AS_WRITTEN = /<(?:pre|textarea)[\s>]|white-space\s*:/i;
24859
24885
  function whitespaceSensitiveLines(source, isBlock) {
24860
24886
  const lines = /* @__PURE__ */ new Set();
24861
24887
  if (!WHITESPACE_AS_WRITTEN.test(source)) return lines;
24888
+ const lineAt = sourceLines(source);
24862
24889
  const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
24863
24890
  function visit(nodes) {
24864
24891
  for (const node of nodes) {
24865
24892
  const { token, body } = node;
24866
24893
  if (token.type === "html" && (["pre", "textarea"].includes(token.tag.toLowerCase()) || Object.entries(token.attributes).some(([name, value]) => name.toLowerCase() === "style" && /white-space\s*:/i.test(value)))) {
24867
- const first = source.slice(0, node.start).split("\n").length - 1;
24868
- const last = source.slice(0, node.end - 1).split("\n").length - 1;
24894
+ const first = lineAt(node.start);
24895
+ const last = lineAt(node.end - 1);
24869
24896
  for (let line = first; line <= last; line++) lines.add(line);
24870
24897
  } else if (body) {
24871
24898
  visit(body.children);
@@ -25023,12 +25050,14 @@ var NO_WRAP = /* @__PURE__ */ new Set([
25023
25050
  "atxHeading",
25024
25051
  "setextHeading",
25025
25052
  "table",
25026
- "listItem",
25053
+ "listOrdered",
25054
+ "listUnordered",
25027
25055
  "blockQuote",
25028
25056
  "definition",
25029
25057
  "thematicBreak",
25030
25058
  "htmlFlow",
25031
25059
  "codeText",
25060
+ "codeFenced",
25032
25061
  "link",
25033
25062
  "image"
25034
25063
  ]);
@@ -25052,6 +25081,10 @@ function wrapLines(lines, maxLen, literalLines, isBlock) {
25052
25081
  continue;
25053
25082
  }
25054
25083
  const wrapped = wordWrap(trimmed, maxLen, line.match(/^(\s*)/)?.[1] ?? "");
25084
+ if (wrapped.length > 1 && markdownLines(wrapped.join("\n"), isBlock, NO_WRAP).size) {
25085
+ result.push(line);
25086
+ continue;
25087
+ }
25055
25088
  if (line.endsWith(" ")) wrapped[wrapped.length - 1] += " ";
25056
25089
  result.push(...wrapped);
25057
25090
  }
@@ -25061,9 +25094,10 @@ function wrapLines(lines, maxLen, literalLines, isBlock) {
25061
25094
  function doBodyLines(lines) {
25062
25095
  const found = /* @__PURE__ */ new Set();
25063
25096
  const text = lines.join("\n");
25097
+ const lineAt = sourceLines(text);
25064
25098
  for (const block of scanSpindleMarkup(text).doBlocks) {
25065
- const first = text.slice(0, block.bodyStart).split("\n").length - 1;
25066
- const last = text.slice(0, block.bodyEnd).split("\n").length - 1;
25099
+ const first = lineAt(block.bodyStart);
25100
+ const last = lineAt(block.bodyEnd);
25067
25101
  for (let i = first; i <= last; i++) found.add(i);
25068
25102
  }
25069
25103
  return found;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.61.3",
3
+ "version": "0.61.5",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -23,9 +23,30 @@ export async function runAutomation(
23
23
  let stepsRun = 0;
24
24
 
25
25
  // Navigate to start passage if specified
26
- if (script.start) {
27
- story.goto(script.start);
28
- await story.waitForActions();
26
+ if (script.start !== undefined) {
27
+ let started = false;
28
+ // Observe the supplied runtime, which may come from a separate package
29
+ // bundle. Valid destinations emit before rendering (and any redirects).
30
+ const unsubscribe = story.on('beforenavigate', (passage) => {
31
+ if (passage === script.start) started = true;
32
+ });
33
+ try {
34
+ story.goto(script.start);
35
+ if (!started) {
36
+ throw new Error(
37
+ `Cannot start automation at passage "${script.start}": navigation was refused`,
38
+ );
39
+ }
40
+ await story.waitForActions();
41
+ } catch (err) {
42
+ return {
43
+ success: false,
44
+ stepsRun: 0,
45
+ errors: [{ step: -1, message: errorMessage(err) }],
46
+ };
47
+ } finally {
48
+ unsubscribe();
49
+ }
29
50
  }
30
51
 
31
52
  for (let i = 0; i < script.steps.length; i++) {
@@ -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
 
@@ -1,4 +1,4 @@
1
- import { useStoryStore } from '../../store';
1
+ import { useStoryFields } from '../../hooks/use-story-fields';
2
2
  import { useLiveLocals } from '../../hooks/use-merged-locals';
3
3
  import { useInterpolate } from '../../hooks/use-interpolate';
4
4
  import { ownValue, variableNameError } from '../../utils/namespace';
@@ -23,9 +23,11 @@ export function VarDisplay({ node }: { node: VariableNode }) {
23
23
  const parts = name.split('.');
24
24
  const root = parts[0]!;
25
25
  // Own entries only, as the expression engine reads them
26
- const storeValue = useStoryStore((s) =>
27
- scope === 'local' ? undefined : ownValue(s[STORE_NAMESPACES[scope]], root),
28
- );
26
+ const state = useStoryFields('variables', 'temporary', 'transient');
27
+ const storeValue =
28
+ scope === 'local'
29
+ ? undefined
30
+ : ownValue(state[STORE_NAMESPACES[scope]], root);
29
31
 
30
32
  const sigil = SCOPE_SIGILS[scope];
31
33
  const nameError = variableNameError(root, sigil + root);
@@ -182,15 +182,8 @@ function startsLikeValue(token: string): boolean {
182
182
  if (first === '"' || first === "'" || first === '`') return true;
183
183
  // Variable ($var, _var, @var, %var), but not the modulo operator in `$a % 2`
184
184
  if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
185
- // Number literal
186
- if (/\d/.test(first)) return true;
187
- // Signed number (-1, +2)
188
- if (
189
- (first === '-' || first === '+') &&
190
- token.length > 1 &&
191
- /\d/.test(token[1]!)
192
- )
193
- return true;
185
+ // Number literal, optionally signed, including leading-dot decimals.
186
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
194
187
  // Grouped expression or collection literal
195
188
  if (first === '(' || first === '[' || first === '{') return true;
196
189
  // Boolean / null / undefined, alone or leading an expression (true||$x)
@@ -176,7 +176,7 @@ function readOptions(
176
176
  }
177
177
 
178
178
  /** `inline %name` reads a transient variable; `inline % 2` is modulo. */
179
- const LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
179
+ const LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,]|\.(?!\d)|%(?![A-Za-z_]))/;
180
180
 
181
181
  /**
182
182
  * Where the rest of `src` is without the flag `word` as its last or first