@rohal12/spindle 0.61.3 → 0.61.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +40 -4
- package/dist/pkg/play.js +2 -0
- package/dist/pkg/story-variables.js +38 -9
- package/package.json +1 -1
- package/src/automation/runner.ts +24 -3
- package/src/define-macro.ts +36 -2
- package/src/format/format-passage.ts +7 -4
- package/src/format/markdown-lines.ts +16 -4
- package/src/format/placeholders.ts +1 -1
- package/src/format/source-lines.ts +17 -0
- package/src/js-lexer.ts +18 -0
- package/src/play/session.ts +10 -0
- package/src/saves/format.ts +15 -4
- package/types/play.d.ts +5 -0
package/dist/pkg/headless.js
CHANGED
|
@@ -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`.
|
|
@@ -17363,7 +17372,12 @@ function isOptionalPRNGSnapshot(value) {
|
|
|
17363
17372
|
return isRecord$1(value) && typeof value.seed === "string" && typeof value.pull === "number" && Number.isInteger(value.pull) && value.pull >= 0;
|
|
17364
17373
|
}
|
|
17365
17374
|
var isMoment = (value) => isRecord$1(value) && typeof value.passage === "string" && isRecord$1(value.variables) && typeof value.timestamp === "number" && isOptionalPRNGSnapshot(value.prng);
|
|
17366
|
-
|
|
17375
|
+
/** Visit holes too, rejecting malformed metadata before copying any entries. */
|
|
17376
|
+
function everyEntry(value, valid) {
|
|
17377
|
+
for (let i = 0; i < value.length; i++) if (!hasOwn(value, i) || !valid(value[i])) return false;
|
|
17378
|
+
return true;
|
|
17379
|
+
}
|
|
17380
|
+
var isWatchers = (value) => value === void 0 || Array.isArray(value) && everyEntry(value, (w) => isRecord$1(w) && typeof w.condition === "string" && isRecord$1(w.options));
|
|
17367
17381
|
var isCountsMap = (value) => value === void 0 || value instanceof Map && [...value.keys()].every((k) => typeof k === "string");
|
|
17368
17382
|
/**
|
|
17369
17383
|
* Whether a deserialized payload is well formed: every history moment is,
|
|
@@ -17375,7 +17389,7 @@ function isPayload(value) {
|
|
|
17375
17389
|
if (typeof value.passage !== "string" || !isRecord$1(value.variables)) return false;
|
|
17376
17390
|
const { history, historyIndex } = value;
|
|
17377
17391
|
if (!Array.isArray(history) || history.length === 0) return false;
|
|
17378
|
-
if (!
|
|
17392
|
+
if (!everyEntry(history, isMoment)) return false;
|
|
17379
17393
|
if (typeof historyIndex !== "number" || !Number.isInteger(historyIndex) || historyIndex < 0 || historyIndex >= history.length || history[historyIndex].passage !== value.passage) return false;
|
|
17380
17394
|
return isCountsMap(value.visitCounts) && isCountsMap(value.renderCounts) && isOptionalPRNGSnapshot(value.prng) && isWatchers(value.watchers) && (value.interfaceWatchers === void 0 || typeof value.interfaceWatchers === "boolean");
|
|
17381
17395
|
}
|
|
@@ -20893,8 +20907,30 @@ function defineMacro(config, source = "builtin") {
|
|
|
20893
20907
|
"@": "locals"
|
|
20894
20908
|
}[firstToken.charAt(0)];
|
|
20895
20909
|
if (kind) return h("span", { class: "error" }, `{${config.name}}: ${kind} (${firstToken}) cannot be bound to input macros`);
|
|
20896
|
-
|
|
20897
|
-
|
|
20910
|
+
if (!firstToken.startsWith("$") && firstToken.split(".")[0].includes("\\")) return h(MacroError, {
|
|
20911
|
+
macro: config.name,
|
|
20912
|
+
error: /* @__PURE__ */ new Error("Escaped binding identifiers require a literal $ story-variable sigil")
|
|
20913
|
+
});
|
|
20914
|
+
let segments;
|
|
20915
|
+
try {
|
|
20916
|
+
segments = firstToken.replace(/^\$/, "").split(".").map((segment, index) => {
|
|
20917
|
+
if (!segment.includes("\\")) return segment;
|
|
20918
|
+
if (index > 0) {
|
|
20919
|
+
const name = parseMemberIdentifier(segment);
|
|
20920
|
+
if (name === null) throw new Error("Invalid bound identifier");
|
|
20921
|
+
return name;
|
|
20922
|
+
}
|
|
20923
|
+
const reference = parseReferencePath(`$${segment}`);
|
|
20924
|
+
if (!reference || reference.nested) throw new Error("Invalid bound identifier");
|
|
20925
|
+
return reference.name;
|
|
20926
|
+
});
|
|
20927
|
+
} catch (error) {
|
|
20928
|
+
return h(MacroError, {
|
|
20929
|
+
macro: config.name,
|
|
20930
|
+
error
|
|
20931
|
+
});
|
|
20932
|
+
}
|
|
20933
|
+
const varExpr = segments.join(".");
|
|
20898
20934
|
if (segments.includes("__proto__")) return h("span", { class: "error" }, `{${config.name}}: "$${varExpr}" cannot be bound: ${RESERVED_NAME} is reserved`);
|
|
20899
20935
|
ctx.varName = varExpr;
|
|
20900
20936
|
ctx.value = useStoryStore((s) => getByPath(s.variables, segments));
|
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)`;
|
|
@@ -24392,12 +24392,30 @@ function markdownOptions(options) {
|
|
|
24392
24392
|
};
|
|
24393
24393
|
}
|
|
24394
24394
|
//#endregion
|
|
24395
|
+
//#region src/format/source-lines.ts
|
|
24396
|
+
/** Index a source once; locate zero-based lines without rescanning its prefixes. */
|
|
24397
|
+
function sourceLines(source) {
|
|
24398
|
+
const starts = [0];
|
|
24399
|
+
for (let i = 0; i < source.length; i++) if (source[i] === "\n") starts.push(i + 1);
|
|
24400
|
+
return (offset) => {
|
|
24401
|
+
let low = 0;
|
|
24402
|
+
let high = starts.length;
|
|
24403
|
+
while (low < high) {
|
|
24404
|
+
const middle = low + high >>> 1;
|
|
24405
|
+
if (starts[middle] <= offset) low = middle + 1;
|
|
24406
|
+
else high = middle;
|
|
24407
|
+
}
|
|
24408
|
+
return Math.max(0, low - 1);
|
|
24409
|
+
};
|
|
24410
|
+
}
|
|
24411
|
+
//#endregion
|
|
24395
24412
|
//#region src/format/markdown-lines.ts
|
|
24396
24413
|
/** Source lines belonging to the given constructs in runtime Markdown documents. */
|
|
24397
24414
|
function markdownLines(source, isBlock, types) {
|
|
24398
24415
|
const found = /* @__PURE__ */ new Set();
|
|
24399
24416
|
if (types.size === 1 && types.has("codeFenced") && !/`{3}|~{3}/.test(source)) return found;
|
|
24400
24417
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
24418
|
+
const lineAt = sourceLines(source);
|
|
24401
24419
|
function visit(nodes) {
|
|
24402
24420
|
let markdown = "";
|
|
24403
24421
|
const spans = [];
|
|
@@ -24409,7 +24427,7 @@ function markdownLines(source, isBlock, types) {
|
|
|
24409
24427
|
end: markdown.length,
|
|
24410
24428
|
node
|
|
24411
24429
|
});
|
|
24412
|
-
if (node.body && !(node.token.type === "macro" && node.token.name === "do")) {
|
|
24430
|
+
if (node.body && !(node.token.type === "macro" && node.token.name.toLowerCase() === "do")) {
|
|
24413
24431
|
visit(node.body.children);
|
|
24414
24432
|
for (const branch of node.body.branches) visit(branch.children);
|
|
24415
24433
|
}
|
|
@@ -24417,15 +24435,24 @@ function markdownLines(source, isBlock, types) {
|
|
|
24417
24435
|
const events = postprocess(parse(markdownOptions()).document().write(preprocess()(markdown, void 0, true)));
|
|
24418
24436
|
for (const [event, token] of events) {
|
|
24419
24437
|
if (event !== "enter" || !types.has(token.type)) continue;
|
|
24420
|
-
|
|
24438
|
+
let low = 0;
|
|
24439
|
+
let high = spans.length;
|
|
24440
|
+
while (low < high) {
|
|
24441
|
+
const middle = low + high >>> 1;
|
|
24442
|
+
if (spans[middle].end <= token.start.offset) low = middle + 1;
|
|
24443
|
+
else high = middle;
|
|
24444
|
+
}
|
|
24445
|
+
for (let i = low; i < spans.length; i++) {
|
|
24446
|
+
const span = spans[i];
|
|
24447
|
+
if (span.start >= token.end.offset) break;
|
|
24421
24448
|
const start = Math.max(token.start.offset, span.start);
|
|
24422
24449
|
const end = Math.min(token.end.offset, span.end);
|
|
24423
24450
|
if (start >= end) continue;
|
|
24424
24451
|
const text = span.node.token.type === "text";
|
|
24425
24452
|
const a = text ? span.node.start + start - span.start : span.node.start;
|
|
24426
24453
|
const b = text ? span.node.start + end - span.start : span.node.end;
|
|
24427
|
-
const first =
|
|
24428
|
-
const last =
|
|
24454
|
+
const first = lineAt(a);
|
|
24455
|
+
const last = lineAt(Math.max(a, b - 1));
|
|
24429
24456
|
for (let line = first; line <= last; line++) found.add(line);
|
|
24430
24457
|
}
|
|
24431
24458
|
}
|
|
@@ -24497,7 +24524,7 @@ function scanSpindleMarkup(text) {
|
|
|
24497
24524
|
}, true);
|
|
24498
24525
|
}
|
|
24499
24526
|
} else if (t.type !== "text") {
|
|
24500
|
-
if (t.type === "macro" && t.name === "do") {
|
|
24527
|
+
if (t.type === "macro" && t.name.toLowerCase() === "do") {
|
|
24501
24528
|
if (!t.isClose) open = t;
|
|
24502
24529
|
else if (open) {
|
|
24503
24530
|
doBlocks.push({
|
|
@@ -24859,13 +24886,14 @@ var WHITESPACE_AS_WRITTEN = /<(?:pre|textarea)[\s>]|white-space\s*:/i;
|
|
|
24859
24886
|
function whitespaceSensitiveLines(source, isBlock) {
|
|
24860
24887
|
const lines = /* @__PURE__ */ new Set();
|
|
24861
24888
|
if (!WHITESPACE_AS_WRITTEN.test(source)) return lines;
|
|
24889
|
+
const lineAt = sourceLines(source);
|
|
24862
24890
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
24863
24891
|
function visit(nodes) {
|
|
24864
24892
|
for (const node of nodes) {
|
|
24865
24893
|
const { token, body } = node;
|
|
24866
24894
|
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 =
|
|
24868
|
-
const last =
|
|
24895
|
+
const first = lineAt(node.start);
|
|
24896
|
+
const last = lineAt(node.end - 1);
|
|
24869
24897
|
for (let line = first; line <= last; line++) lines.add(line);
|
|
24870
24898
|
} else if (body) {
|
|
24871
24899
|
visit(body.children);
|
|
@@ -25061,9 +25089,10 @@ function wrapLines(lines, maxLen, literalLines, isBlock) {
|
|
|
25061
25089
|
function doBodyLines(lines) {
|
|
25062
25090
|
const found = /* @__PURE__ */ new Set();
|
|
25063
25091
|
const text = lines.join("\n");
|
|
25092
|
+
const lineAt = sourceLines(text);
|
|
25064
25093
|
for (const block of scanSpindleMarkup(text).doBlocks) {
|
|
25065
|
-
const first =
|
|
25066
|
-
const last =
|
|
25094
|
+
const first = lineAt(block.bodyStart);
|
|
25095
|
+
const last = lineAt(block.bodyEnd);
|
|
25067
25096
|
for (let i = first; i <= last; i++) found.add(i);
|
|
25068
25097
|
}
|
|
25069
25098
|
return found;
|
package/package.json
CHANGED
package/src/automation/runner.ts
CHANGED
|
@@ -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
|
-
|
|
28
|
-
|
|
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++) {
|
package/src/define-macro.ts
CHANGED
|
@@ -28,6 +28,7 @@ import { evaluateDisplay } from './expression';
|
|
|
28
28
|
import { useStoryStore } from './store';
|
|
29
29
|
import { getByPath, setByPath } from './utils/object-path';
|
|
30
30
|
import { RESERVED_NAME } from './utils/namespace';
|
|
31
|
+
import { parseMemberIdentifier, parseReferencePath } from './js-lexer';
|
|
31
32
|
import { useAction } from './hooks/use-action';
|
|
32
33
|
import type { UseActionOptions } from './hooks/use-action';
|
|
33
34
|
import { collectText } from './utils/extract-text';
|
|
@@ -255,8 +256,41 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
|
|
|
255
256
|
);
|
|
256
257
|
}
|
|
257
258
|
|
|
258
|
-
|
|
259
|
-
|
|
259
|
+
if (
|
|
260
|
+
!firstToken.startsWith('$') &&
|
|
261
|
+
firstToken.split('.')[0]!.includes('\\')
|
|
262
|
+
) {
|
|
263
|
+
return h(MacroError, {
|
|
264
|
+
macro: config.name,
|
|
265
|
+
error: new Error(
|
|
266
|
+
'Escaped binding identifiers require a literal $ story-variable sigil',
|
|
267
|
+
),
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
let segments: string[];
|
|
272
|
+
try {
|
|
273
|
+
segments = firstToken
|
|
274
|
+
.replace(/^\$/, '')
|
|
275
|
+
.split('.')
|
|
276
|
+
.map((segment, index) => {
|
|
277
|
+
if (!segment.includes('\\')) return segment;
|
|
278
|
+
// Members follow JavaScript's identifier grammar, which accepts
|
|
279
|
+
// more names than story-variable roots (for example $foo and é).
|
|
280
|
+
if (index > 0) {
|
|
281
|
+
const name = parseMemberIdentifier(segment);
|
|
282
|
+
if (name === null) throw new Error('Invalid bound identifier');
|
|
283
|
+
return name;
|
|
284
|
+
}
|
|
285
|
+
const reference = parseReferencePath(`$${segment}`);
|
|
286
|
+
if (!reference || reference.nested)
|
|
287
|
+
throw new Error('Invalid bound identifier');
|
|
288
|
+
return reference.name;
|
|
289
|
+
});
|
|
290
|
+
} catch (error) {
|
|
291
|
+
return h(MacroError, { macro: config.name, error });
|
|
292
|
+
}
|
|
293
|
+
const varExpr = segments.join('.');
|
|
260
294
|
if (segments.includes(RESERVED_NAME)) {
|
|
261
295
|
return h(
|
|
262
296
|
'span',
|
|
@@ -4,6 +4,7 @@ import type { PairedNode } from '../markup/pair';
|
|
|
4
4
|
import type { MacroToken } from '../markup/tokens';
|
|
5
5
|
import { segmentRegions } from './segment';
|
|
6
6
|
import { markdownLines } from './markdown-lines';
|
|
7
|
+
import { sourceLines } from './source-lines';
|
|
7
8
|
import {
|
|
8
9
|
formatJS,
|
|
9
10
|
formatCSS,
|
|
@@ -379,6 +380,7 @@ function whitespaceSensitiveLines(
|
|
|
379
380
|
): Set<number> {
|
|
380
381
|
const lines = new Set<number>();
|
|
381
382
|
if (!WHITESPACE_AS_WRITTEN.test(source)) return lines;
|
|
383
|
+
const lineAt = sourceLines(source);
|
|
382
384
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
383
385
|
function visit(nodes: PairedNode[]): void {
|
|
384
386
|
for (const node of nodes) {
|
|
@@ -391,8 +393,8 @@ function whitespaceSensitiveLines(
|
|
|
391
393
|
name.toLowerCase() === 'style' && /white-space\s*:/i.test(value),
|
|
392
394
|
))
|
|
393
395
|
) {
|
|
394
|
-
const first =
|
|
395
|
-
const last =
|
|
396
|
+
const first = lineAt(node.start);
|
|
397
|
+
const last = lineAt(node.end - 1);
|
|
396
398
|
for (let line = first; line <= last; line++) lines.add(line);
|
|
397
399
|
} else if (body) {
|
|
398
400
|
visit(body.children);
|
|
@@ -678,9 +680,10 @@ function wrapLines(
|
|
|
678
680
|
function doBodyLines(lines: string[]): Set<number> {
|
|
679
681
|
const found = new Set<number>();
|
|
680
682
|
const text = lines.join('\n');
|
|
683
|
+
const lineAt = sourceLines(text);
|
|
681
684
|
for (const block of scanSpindleMarkup(text).doBlocks) {
|
|
682
|
-
const first =
|
|
683
|
-
const last =
|
|
685
|
+
const first = lineAt(block.bodyStart);
|
|
686
|
+
const last = lineAt(block.bodyEnd);
|
|
684
687
|
for (let i = first; i <= last; i++) found.add(i);
|
|
685
688
|
}
|
|
686
689
|
return found;
|
|
@@ -2,6 +2,7 @@ import { parse, postprocess, preprocess } from 'micromark';
|
|
|
2
2
|
import { analyzeMarkup } from '../markup/parse';
|
|
3
3
|
import { markdownOptions } from '../markup/markdown';
|
|
4
4
|
import type { PairedNode } from '../markup/pair';
|
|
5
|
+
import { sourceLines } from './source-lines';
|
|
5
6
|
|
|
6
7
|
/** Source lines belonging to the given constructs in runtime Markdown documents. */
|
|
7
8
|
export function markdownLines(
|
|
@@ -14,6 +15,7 @@ export function markdownLines(
|
|
|
14
15
|
if (types.size === 1 && types.has('codeFenced') && !/`{3}|~{3}/.test(source))
|
|
15
16
|
return found;
|
|
16
17
|
const { nodes } = analyzeMarkup(source, { hooks: { isBlock } });
|
|
18
|
+
const lineAt = sourceLines(source);
|
|
17
19
|
|
|
18
20
|
function visit(nodes: PairedNode[]): void {
|
|
19
21
|
let markdown = '';
|
|
@@ -29,7 +31,7 @@ export function markdownLines(
|
|
|
29
31
|
spans.push({ start, end: markdown.length, node });
|
|
30
32
|
if (
|
|
31
33
|
node.body &&
|
|
32
|
-
!(node.token.type === 'macro' && node.token.name === 'do')
|
|
34
|
+
!(node.token.type === 'macro' && node.token.name.toLowerCase() === 'do')
|
|
33
35
|
) {
|
|
34
36
|
visit(node.body.children);
|
|
35
37
|
for (const branch of node.body.branches) visit(branch.children);
|
|
@@ -42,15 +44,25 @@ export function markdownLines(
|
|
|
42
44
|
);
|
|
43
45
|
for (const [event, token] of events) {
|
|
44
46
|
if (event !== 'enter' || !types.has(token.type)) continue;
|
|
45
|
-
|
|
47
|
+
// Spans are ordered and disjoint. Locate only those this token overlaps.
|
|
48
|
+
let low = 0;
|
|
49
|
+
let high = spans.length;
|
|
50
|
+
while (low < high) {
|
|
51
|
+
const middle = (low + high) >>> 1;
|
|
52
|
+
if (spans[middle]!.end <= token.start.offset) low = middle + 1;
|
|
53
|
+
else high = middle;
|
|
54
|
+
}
|
|
55
|
+
for (let i = low; i < spans.length; i++) {
|
|
56
|
+
const span = spans[i]!;
|
|
57
|
+
if (span.start >= token.end.offset) break;
|
|
46
58
|
const start = Math.max(token.start.offset, span.start);
|
|
47
59
|
const end = Math.min(token.end.offset, span.end);
|
|
48
60
|
if (start >= end) continue;
|
|
49
61
|
const text = span.node.token.type === 'text';
|
|
50
62
|
const a = text ? span.node.start + start - span.start : span.node.start;
|
|
51
63
|
const b = text ? span.node.start + end - span.start : span.node.end;
|
|
52
|
-
const first =
|
|
53
|
-
const last =
|
|
64
|
+
const first = lineAt(a);
|
|
65
|
+
const last = lineAt(Math.max(a, b - 1));
|
|
54
66
|
for (let line = first; line <= last; line++) found.add(line);
|
|
55
67
|
}
|
|
56
68
|
}
|
|
@@ -82,7 +82,7 @@ export function scanSpindleMarkup(text: string): MarkupScan {
|
|
|
82
82
|
}
|
|
83
83
|
} else if (t.type !== 'text') {
|
|
84
84
|
// The body of {do} is one text token, so nothing in it is a token
|
|
85
|
-
if (t.type === 'macro' && t.name === 'do') {
|
|
85
|
+
if (t.type === 'macro' && t.name.toLowerCase() === 'do') {
|
|
86
86
|
if (!t.isClose) open = t;
|
|
87
87
|
else if (open) {
|
|
88
88
|
doBlocks.push({
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Index a source once; locate zero-based lines without rescanning its prefixes. */
|
|
2
|
+
export function sourceLines(source: string): (offset: number) => number {
|
|
3
|
+
const starts = [0];
|
|
4
|
+
for (let i = 0; i < source.length; i++) {
|
|
5
|
+
if (source[i] === '\n') starts.push(i + 1);
|
|
6
|
+
}
|
|
7
|
+
return (offset) => {
|
|
8
|
+
let low = 0;
|
|
9
|
+
let high = starts.length;
|
|
10
|
+
while (low < high) {
|
|
11
|
+
const middle = (low + high) >>> 1;
|
|
12
|
+
if (starts[middle]! <= offset) low = middle + 1;
|
|
13
|
+
else high = middle;
|
|
14
|
+
}
|
|
15
|
+
return Math.max(0, low - 1);
|
|
16
|
+
};
|
|
17
|
+
}
|
package/src/js-lexer.ts
CHANGED
|
@@ -587,6 +587,24 @@ export function parseReferencePath(src: string): ReferencePath | null {
|
|
|
587
587
|
return { sigil: sigil[0], name: sigil[1], nested };
|
|
588
588
|
}
|
|
589
589
|
|
|
590
|
+
/** Decode one dot-member identifier, including keywords and Unicode names. */
|
|
591
|
+
export function parseMemberIdentifier(src: string): string | null {
|
|
592
|
+
const { ast } = parseWithAst(`x.${src}`, 'expression');
|
|
593
|
+
if (ast.type !== 'MemberExpression' || ast.computed) return null;
|
|
594
|
+
const object = ast.object as AnyNode;
|
|
595
|
+
const property = ast.property as AnyNode;
|
|
596
|
+
if (
|
|
597
|
+
object.type !== 'Identifier' ||
|
|
598
|
+
object.start !== 0 ||
|
|
599
|
+
object.end !== 1 ||
|
|
600
|
+
property.type !== 'Identifier' ||
|
|
601
|
+
property.start !== 2 ||
|
|
602
|
+
property.end !== src.length + 2
|
|
603
|
+
)
|
|
604
|
+
return null;
|
|
605
|
+
return property.name as string;
|
|
606
|
+
}
|
|
607
|
+
|
|
590
608
|
/**
|
|
591
609
|
* Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
|
|
592
610
|
* noting where it read a transient in `transientsRead`.
|
package/src/play/session.ts
CHANGED
|
@@ -11,6 +11,8 @@ import type { Op, Request, WorkerData, WorkerMessage } from './protocol';
|
|
|
11
11
|
|
|
12
12
|
export interface PlaySessionOptions {
|
|
13
13
|
html: string;
|
|
14
|
+
/** Explicitly allow story JavaScript to access host Node APIs. Default false. */
|
|
15
|
+
trusted?: boolean;
|
|
14
16
|
/** Per call. Default 10_000. */
|
|
15
17
|
stepTimeoutMs?: number;
|
|
16
18
|
/** Passed to createTranscript() inside the worker. Default { limit: 10 }. */
|
|
@@ -73,6 +75,7 @@ export function workerExecArgv(execArgv: readonly string[]): string[] {
|
|
|
73
75
|
* Opens a session that runs the story in a worker. There `window` is
|
|
74
76
|
* happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
|
|
75
77
|
* globals, but `window.foo = 1` does not make a bare global `foo`.
|
|
78
|
+
* Requires `trusted: true`: story code has unrestricted host Node access.
|
|
76
79
|
*/
|
|
77
80
|
export function openPlaySession(
|
|
78
81
|
options: PlaySessionOptions,
|
|
@@ -90,6 +93,13 @@ export function openPlaySessionWith(
|
|
|
90
93
|
options: PlaySessionOptions,
|
|
91
94
|
urls: { workerUrl: URL; headlessUrl: URL },
|
|
92
95
|
): Promise<PlaySession> {
|
|
96
|
+
if (options.trusted !== true) {
|
|
97
|
+
return Promise.reject(
|
|
98
|
+
new Error(
|
|
99
|
+
'spindle: openPlaySession() requires trusted: true; story JavaScript has unrestricted access to host Node APIs, files and environment. Only run code you trust.',
|
|
100
|
+
),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
93
103
|
const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
|
|
94
104
|
if (
|
|
95
105
|
typeof stepTimeoutMs !== 'number' ||
|
package/src/saves/format.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { assertTrustedWatchers } from '../triggers';
|
|
5
5
|
import { deserialize, serialize } from '../class-registry';
|
|
6
|
-
import { createCounts } from '../utils/namespace';
|
|
6
|
+
import { createCounts, hasOwn } from '../utils/namespace';
|
|
7
7
|
import type { SavePayload } from './types';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -136,10 +136,22 @@ const isMoment = (value: unknown): boolean =>
|
|
|
136
136
|
typeof value.timestamp === 'number' &&
|
|
137
137
|
isOptionalPRNGSnapshot(value.prng);
|
|
138
138
|
|
|
139
|
+
/** Visit holes too, rejecting malformed metadata before copying any entries. */
|
|
140
|
+
function everyEntry(
|
|
141
|
+
value: unknown[],
|
|
142
|
+
valid: (entry: unknown) => boolean,
|
|
143
|
+
): boolean {
|
|
144
|
+
for (let i = 0; i < value.length; i++) {
|
|
145
|
+
if (!hasOwn(value, i) || !valid(value[i])) return false;
|
|
146
|
+
}
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
|
|
139
150
|
const isWatchers = (value: unknown): boolean =>
|
|
140
151
|
value === undefined ||
|
|
141
152
|
(Array.isArray(value) &&
|
|
142
|
-
|
|
153
|
+
everyEntry(
|
|
154
|
+
value,
|
|
143
155
|
(w) =>
|
|
144
156
|
isRecord(w) && typeof w.condition === 'string' && isRecord(w.options),
|
|
145
157
|
));
|
|
@@ -160,9 +172,8 @@ function isPayload(value: unknown): value is Record<string, unknown> {
|
|
|
160
172
|
return false;
|
|
161
173
|
}
|
|
162
174
|
const { history, historyIndex } = value;
|
|
163
|
-
// Array.from: every() skips the holes of a sparse array
|
|
164
175
|
if (!Array.isArray(history) || history.length === 0) return false;
|
|
165
|
-
if (!
|
|
176
|
+
if (!everyEntry(history, isMoment)) return false;
|
|
166
177
|
if (
|
|
167
178
|
typeof historyIndex !== 'number' ||
|
|
168
179
|
!Number.isInteger(historyIndex) ||
|
package/types/play.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export function resolveStoryHtml(input: StoryInput): Promise<ResolvedStory>;
|
|
|
26
26
|
/** Options for {@link openPlaySession}. */
|
|
27
27
|
export interface PlaySessionOptions {
|
|
28
28
|
html: string;
|
|
29
|
+
/** Explicitly allow story JavaScript to access host Node APIs. Default false. */
|
|
30
|
+
trusted?: boolean;
|
|
29
31
|
/** Per call. Default 10_000. */
|
|
30
32
|
stepTimeoutMs?: number;
|
|
31
33
|
/** Passed to createTranscript() inside the worker. Default { limit: 10 }. */
|
|
@@ -67,6 +69,9 @@ export interface PlaySession {
|
|
|
67
69
|
* peer dependency) and resolve with a session once the first passage is
|
|
68
70
|
* shown. Calls run one at a time; a call that takes longer than
|
|
69
71
|
* `stepTimeoutMs` closes the session.
|
|
72
|
+
* Requires `trusted: true`: story JavaScript has unrestricted access to host
|
|
73
|
+
* Node APIs, files and environment. Worker threads and happy-dom are not a
|
|
74
|
+
* security sandbox. Only run code you trust.
|
|
70
75
|
*
|
|
71
76
|
* In the worker, `window` is happy-dom's window, not `globalThis`. Story code
|
|
72
77
|
* sees `Story` and the DOM globals as in a browser, but a property set on
|