@rohal12/spindle 0.59.21 → 0.59.23

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.
@@ -5,13 +5,21 @@
5
5
  * line and column they are at, instead of failing when the passage renders.
6
6
  * Tooling runs it too (see src/tooling.ts).
7
7
  */
8
- import { lineColumn, MarkupError, parseMarkup, tokenizeMarkup } from './parse';
9
- import type { Token } from './tokens';
8
+ import {
9
+ lineColumn,
10
+ MarkupError,
11
+ parseMarkup,
12
+ tokenizeMarkup,
13
+ type MarkupErrorCode,
14
+ } from './parse';
15
+ import type { Span, Token } from './tokens';
10
16
  import { parseWidgetDef } from '../widgets/widget-def';
11
17
  import {
12
- codeAndText,
13
18
  parseOrError,
19
+ passagePiecesOf,
20
+ pieceOffset,
14
21
  withParseCache,
22
+ type CodePiece,
15
23
  type ParametersOf,
16
24
  } from '../code-check';
17
25
  import { CodeSyntaxError } from '../js-lexer';
@@ -28,14 +36,39 @@ export interface MarkupPassage {
28
36
  metadata?: Record<string, string>;
29
37
  }
30
38
 
31
- /** An error in a passage's markup. */
32
- export interface MarkupDiagnostic {
39
+ /**
40
+ * The kinds of diagnostic, which stay the same where the wording of the
41
+ * message changes. The kinds of malformed markup are those of MarkupError.
42
+ */
43
+ export type MarkupDiagnosticCode =
44
+ | MarkupErrorCode
45
+ | 'unknown-macro'
46
+ | 'argument-error'
47
+ | 'code-syntax'
48
+ | 'unknown-passage'
49
+ | 'unquoted-passage-name';
50
+
51
+ /** What a diagnostic names, by code (see docs/tooling.md). */
52
+ export type MarkupDiagnosticData = Readonly<
53
+ Record<string, string | readonly string[]>
54
+ >;
55
+
56
+ /**
57
+ * An error in a passage's markup, at the offending text from `start` up to
58
+ * `end`: UTF-16 offsets into the passage's content, of which `line` and
59
+ * `column` are those of `start`.
60
+ */
61
+ export interface MarkupDiagnostic extends Span {
33
62
  passage: string;
34
63
  /** 1-based line within the passage's content. */
35
64
  line: number;
36
65
  /** 1-based column (UTF-16 code units). */
37
66
  column: number;
38
67
  message: string;
68
+ /** The kind of error, which tools tell apart without reading `message`. */
69
+ code: MarkupDiagnosticCode;
70
+ /** What the diagnostic names, by `code`: the macro, the passage, what to try. */
71
+ data?: MarkupDiagnosticData;
39
72
  /** The source file and line, when the passage says where it came from. */
40
73
  file?: string;
41
74
  fileLine?: number;
@@ -110,17 +143,13 @@ function distance(a: string, b: string): number {
110
143
  return prev[b.length]!;
111
144
  }
112
145
 
113
- /**
114
- * " Did you mean …?" with the known name closest to `name`, written by
115
- * `quote`, if one is close.
116
- */
117
- function didYouMean(
146
+ /** The known name closest to `name`, if one is close. */
147
+ function closestName(
118
148
  name: string,
119
149
  names: Iterable<string>,
120
- quote: (name: string) => string,
121
- ): string {
150
+ ): string | undefined {
122
151
  const lower = name.toLowerCase();
123
- let best = '';
152
+ let best: string | undefined;
124
153
  let bestDistance = Math.max(2, Math.floor(lower.length / 3)) + 1;
125
154
  for (const candidate of names) {
126
155
  const d = distance(lower, candidate.toLowerCase());
@@ -129,9 +158,15 @@ function didYouMean(
129
158
  bestDistance = d;
130
159
  }
131
160
  }
132
- return best ? ` Did you mean ${quote(best)}?` : '';
161
+ return best;
133
162
  }
134
163
 
164
+ /** " Did you mean …?" with `best`, written by `quote`, if there is one. */
165
+ const didYouMean = (
166
+ best: string | undefined,
167
+ quote: (name: string) => string,
168
+ ) => (best ? ` Did you mean ${quote(best)}?` : '');
169
+
135
170
  /** What a passage argument may be, after an error in one. */
136
171
  const PASSAGE_ARGUMENT_HINT =
137
172
  ' (a passage name is a quoted string or an expression)';
@@ -160,14 +195,25 @@ export function validateMarkup(
160
195
  const hooks = options.isBlockMacro
161
196
  ? { isBlock: options.isBlockMacro }
162
197
  : undefined;
163
- const report = (passage: MarkupPassage, offset: number, message: string) => {
164
- const { line, column } = lineColumn(passage.content, offset);
198
+ const report = (
199
+ passage: MarkupPassage,
200
+ start: number,
201
+ end: number,
202
+ code: MarkupDiagnosticCode,
203
+ message: string,
204
+ data?: MarkupDiagnosticData,
205
+ ) => {
206
+ const { line, column } = lineColumn(passage.content, start);
165
207
  const d: MarkupDiagnostic = {
166
208
  passage: passage.name,
167
209
  line,
168
210
  column,
169
211
  message,
212
+ code,
213
+ start,
214
+ end,
170
215
  };
216
+ if (data) d.data = data;
171
217
  const file = passage.metadata?.['data-source-file'];
172
218
  if (file) {
173
219
  d.file = file;
@@ -176,6 +222,20 @@ export function validateMarkup(
176
222
  }
177
223
  diagnostics.push(d);
178
224
  };
225
+ /** Report malformed markup. */
226
+ const reportError = (
227
+ passage: MarkupPassage,
228
+ err: MarkupError,
229
+ where: string,
230
+ ) =>
231
+ report(
232
+ passage,
233
+ err.offset,
234
+ err.end,
235
+ err.code,
236
+ where + err.reason,
237
+ err.data,
238
+ );
179
239
 
180
240
  // Parse every passage first: the widgets they define are known macros.
181
241
  const parsed: [MarkupPassage, Token[]][] = [];
@@ -200,18 +260,15 @@ export function validateMarkup(
200
260
  parsed.push([passage, tokens]);
201
261
  } catch (err) {
202
262
  if (!(err instanceof MarkupError)) throw err;
203
- if (reported) {
204
- report(passage, err.offset, err.reason);
205
- }
263
+ if (reported) reportError(passage, err, '');
206
264
  }
207
265
  }
208
266
  const names = [...(options.macroNames ?? []), ...widgets];
209
267
 
210
- /** Report the unknown macros among `tokens`, which start at `base`. */
268
+ /** Report the unknown macros among `tokens`, with `where` in front. */
211
269
  const checkMacros = (
212
270
  passage: MarkupPassage,
213
- tokens: Token[],
214
- base: number,
271
+ tokens: readonly Token[],
215
272
  where: string,
216
273
  ) => {
217
274
  for (const token of tokens) {
@@ -224,10 +281,14 @@ export function validateMarkup(
224
281
  ) {
225
282
  continue;
226
283
  }
284
+ const best = closestName(token.name, names);
227
285
  report(
228
286
  passage,
229
- base + token.start,
230
- `${where}Unknown macro {${token.name}}.${didYouMean(token.name, names, (n) => `{${n}}`)}`,
287
+ token.start,
288
+ token.end,
289
+ 'unknown-macro',
290
+ `${where}Unknown macro {${token.name}}.${didYouMean(best, (n) => `{${n}}`)}`,
291
+ { name: token.name, suggestions: best ? [best] : [] },
231
292
  );
232
293
  }
233
294
  };
@@ -235,71 +296,98 @@ export function validateMarkup(
235
296
  const parametersOf: ParametersOf = options.parametersOf ?? (() => undefined);
236
297
 
237
298
  /**
238
- * Check `tokens`, the tokens of `src`, which starts at `base` in the
239
- * passage: their macros, the code in them and the markup in their text.
299
+ * Check the pieces of a passage: its macros, the code in them, the passage
300
+ * names they write out and the markup in their text.
240
301
  */
241
- const checkTokens = (
242
- passage: MarkupPassage,
243
- src: string,
244
- tokens: Token[],
245
- base: number,
246
- where: string,
247
- ) => {
248
- checkMacros(passage, tokens, base, where);
249
- for (const piece of codeAndText(src, tokens, parametersOf)) {
250
- const at = base + piece.offset;
251
- if (piece.kind === 'argument-error') {
252
- report(passage, at, `${where}${piece.message} in ${piece.label}`);
253
- continue;
254
- }
255
- if (piece.kind === 'passage') {
256
- if (
257
- options.checkPassageNames !== false &&
258
- !passageNames.has(piece.name)
259
- ) {
260
- const hint = didYouMean(piece.name, passageNames, JSON.stringify);
302
+ const checkPassage = (passage: MarkupPassage, tokens: readonly Token[]) => {
303
+ checkMacros(passage, tokens, '');
304
+ // The markup of a text with an error in it is not read further
305
+ let skipTo = 0;
306
+ for (const piece of passagePiecesOf(passage.content, tokens, parametersOf, {
307
+ isBlock: options.isBlockMacro,
308
+ })) {
309
+ if (piece.nested && piece.offset < skipTo) continue;
310
+ const at = piece.offset;
311
+ const where = piece.where && piece.nested ? piece.where : '';
312
+ switch (piece.kind) {
313
+ case 'argument-error':
261
314
  report(
262
315
  passage,
263
316
  at,
264
- `${where}No passage named ${JSON.stringify(piece.name)} in ${piece.label}.${hint}`,
317
+ at + piece.length,
318
+ 'argument-error',
319
+ `${where}${piece.message} in ${piece.label}`,
320
+ { macro: piece.macro },
265
321
  );
266
- }
267
- continue;
268
- }
269
- if (piece.kind === 'code') {
270
- const result = parseOrError(piece.code, piece.goal);
271
- const code = piece.code.trim();
272
- if (result instanceof CodeSyntaxError) {
273
- const reason = result.reasonIn(passage.content, at);
274
- report(
275
- passage,
276
- at + result.pos,
277
- `${where}${reason} in ${piece.label}` +
278
- (piece.passage ? PASSAGE_ARGUMENT_HINT : ''),
279
- );
280
- } else if (piece.passage && BARE_WORD_RE.test(code)) {
281
- report(
282
- passage,
283
- at,
284
- `${where}Unquoted passage name in ${piece.label}: write ${JSON.stringify(code)}${PASSAGE_ARGUMENT_HINT}`,
285
- );
286
- }
287
- continue;
288
- }
289
- if (!piece.text.includes('{')) continue;
290
- try {
291
- parseMarkup(piece.text, { text: true, hooks });
292
- const inner = tokenizeMarkup(piece.text, { text: true });
293
- checkTokens(passage, piece.text, inner, at, piece.where);
294
- } catch (err) {
295
- if (!(err instanceof MarkupError)) throw err;
296
- report(passage, at + err.offset, piece.where + err.reason);
322
+ break;
323
+ case 'passage':
324
+ if (
325
+ options.checkPassageNames !== false &&
326
+ !passageNames.has(piece.name)
327
+ ) {
328
+ const best = closestName(piece.name, passageNames);
329
+ report(
330
+ passage,
331
+ at,
332
+ at + piece.length,
333
+ 'unknown-passage',
334
+ `${where}No passage named ${JSON.stringify(piece.name)} in ${piece.label}.${didYouMean(best, JSON.stringify)}`,
335
+ {
336
+ name: piece.name,
337
+ macro: piece.macro,
338
+ suggestions: best ? [best] : [],
339
+ },
340
+ );
341
+ }
342
+ break;
343
+ case 'code':
344
+ checkCode(passage, piece, where);
345
+ break;
346
+ case 'text':
347
+ if (piece.errors.length > 0) {
348
+ reportError(passage, piece.errors[0]!, piece.where);
349
+ skipTo = pieceOffset(piece, piece.text.length);
350
+ } else {
351
+ checkMacros(passage, piece.tokens, piece.where);
352
+ }
297
353
  }
298
354
  }
299
355
  };
300
356
 
357
+ const checkCode = (
358
+ passage: MarkupPassage,
359
+ piece: CodePiece,
360
+ where: string,
361
+ ) => {
362
+ const at = piece.offset;
363
+ const result = parseOrError(piece.code, piece.goal);
364
+ const code = piece.code.trim();
365
+ if (result instanceof CodeSyntaxError) {
366
+ const offending = /^(?:[\w$]+|\S)/.exec(piece.code.slice(result.pos));
367
+ report(
368
+ passage,
369
+ pieceOffset(piece, result.pos),
370
+ pieceOffset(piece, result.pos + (offending?.[0].length ?? 0)),
371
+ 'code-syntax',
372
+ `${where}${result.reasonIn(passage.content, at)} in ${piece.label}` +
373
+ (piece.passage ? PASSAGE_ARGUMENT_HINT : ''),
374
+ piece.macro ? { macro: piece.macro } : undefined,
375
+ );
376
+ } else if (piece.passage && BARE_WORD_RE.test(code)) {
377
+ const lead = piece.code.length - piece.code.trimStart().length;
378
+ report(
379
+ passage,
380
+ pieceOffset(piece, lead),
381
+ pieceOffset(piece, lead + code.length),
382
+ 'unquoted-passage-name',
383
+ `${where}Unquoted passage name in ${piece.label}: write ${JSON.stringify(code)}${PASSAGE_ARGUMENT_HINT}`,
384
+ { name: code, macro: piece.macro ?? '' },
385
+ );
386
+ }
387
+ };
388
+
301
389
  for (const [passage, tokens] of parsed) {
302
- withParseCache(() => checkTokens(passage, passage.content, tokens, 0, ''));
390
+ withParseCache(() => checkPassage(passage, tokens));
303
391
  }
304
392
  return diagnostics;
305
393
  }
@@ -337,6 +337,8 @@ async function createSaveNow(
337
337
 
338
338
  const record = storedRecord(meta, payload);
339
339
  await (await getBackend()).putSave(record);
340
+ // Save dialogs open in other tabs list it (#445)
341
+ announceSlots(ifid);
340
342
  return record;
341
343
  }
342
344
 
@@ -423,6 +425,8 @@ export function deleteSaveById(saveId: string): Promise<void> {
423
425
  if (!record) return;
424
426
 
425
427
  await emptySlotsHolding(record.meta.ifid, (id) => id === saveId);
428
+ // A save in no slot is gone from the other tabs' dialogs too (#445)
429
+ announceSlots(record.meta.ifid);
426
430
  });
427
431
  }
428
432
 
@@ -441,6 +445,7 @@ export function renameSave(saveId: string, newTitle: string): Promise<void> {
441
445
  },
442
446
  };
443
447
  await backend.putSave(updated);
448
+ announceSlots(updated.meta.ifid);
444
449
  });
445
450
  }
446
451
 
@@ -980,6 +985,7 @@ export function importSave(data: unknown, ifid: string): Promise<SaveRecord> {
980
985
  return inOrder(async () => {
981
986
  const record = await prepareImport(data, ifid);
982
987
  await (await getBackend()).putSave(record);
988
+ announceSlots(ifid);
983
989
  return record;
984
990
  });
985
991
  }
@@ -1105,6 +1111,8 @@ export function deletePlaythroughData(
1105
1111
  // Clear the slots that held deleted saves (pointer and slot index)
1106
1112
  const deletedSet = new Set(deletedSaveIds);
1107
1113
  await emptySlotsHolding(ifid, (id) => deletedSet.has(id));
1114
+ // Saves in no slot are gone from other tabs' dialogs too
1115
+ announceSlots(ifid);
1108
1116
 
1109
1117
  if (replacement && (await replacement.current) === playthroughId) {
1110
1118
  await startNewPlaythroughNow(ifid, replacement.id);
@@ -197,6 +197,16 @@ function lsDel(key: string): void {
197
197
  localStorage.removeItem(key);
198
198
  }
199
199
 
200
+ /** Put an item back as it was (`raw` null: absent); best effort. */
201
+ function lsRestore(key: string, raw: string | null): void {
202
+ try {
203
+ if (raw === null) localStorage.removeItem(key);
204
+ else localStorage.setItem(key, raw);
205
+ } catch {
206
+ // The quota forbids even the old value: nothing more to do
207
+ }
208
+ }
209
+
200
210
  function lsIndex(key: string): string[] {
201
211
  return lsGet<string[]>(key) ?? [];
202
212
  }
@@ -239,13 +249,22 @@ export function createLocalStorageBackend(): StorageBackend {
239
249
  // after a restart, under the new playthrough) leaves the old list
240
250
  const previous = lsGet<T>(`${prefix}${key}`);
241
251
  const lists = listsOf(value);
242
- if (previous !== undefined) {
243
- for (const list of listsOf(previous)) {
244
- if (!lists.includes(list)) lsIndexRemove(list, key);
245
- }
252
+ const obsolete =
253
+ previous === undefined
254
+ ? []
255
+ : listsOf(previous).filter((list) => !lists.includes(list));
256
+ // A write that fails (the quota) puts back what it changed: a record
257
+ // no index lists is neither shown nor cleared with its story (#443)
258
+ const touched = [`${prefix}${key}`, ...obsolete, ...lists];
259
+ const before = touched.map((k) => localStorage.getItem(k));
260
+ try {
261
+ for (const list of obsolete) lsIndexRemove(list, key);
262
+ lsSet(`${prefix}${key}`, value);
263
+ for (const list of lists) lsIndexAdd(list, key);
264
+ } catch (err) {
265
+ touched.forEach((k, i) => lsRestore(k, before[i] ?? null));
266
+ throw err;
246
267
  }
247
- lsSet(`${prefix}${key}`, value);
248
- for (const list of lists) lsIndexAdd(list, key);
249
268
  },
250
269
  async delete(key) {
251
270
  const record = lsGet<T>(`${prefix}${key}`);