@nowline/core 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/diagnostics/index.d.ts +14 -1
  2. package/dist/diagnostics/index.d.ts.map +1 -1
  3. package/dist/diagnostics/index.js +35 -1
  4. package/dist/diagnostics/index.js.map +1 -1
  5. package/dist/i18n/codes.d.ts +1 -1
  6. package/dist/i18n/codes.d.ts.map +1 -1
  7. package/dist/i18n/codes.js +8 -0
  8. package/dist/i18n/codes.js.map +1 -1
  9. package/dist/i18n/include-message-types.d.ts +23 -0
  10. package/dist/i18n/include-message-types.d.ts.map +1 -0
  11. package/dist/i18n/include-message-types.js +5 -0
  12. package/dist/i18n/include-message-types.js.map +1 -0
  13. package/dist/i18n/index.d.ts +1 -0
  14. package/dist/i18n/index.d.ts.map +1 -1
  15. package/dist/i18n/index.js.map +1 -1
  16. package/dist/i18n/messages.en.d.ts +21 -0
  17. package/dist/i18n/messages.en.d.ts.map +1 -1
  18. package/dist/i18n/messages.en.js +40 -0
  19. package/dist/i18n/messages.en.js.map +1 -1
  20. package/dist/i18n/messages.fr.d.ts.map +1 -1
  21. package/dist/i18n/messages.fr.js +40 -0
  22. package/dist/i18n/messages.fr.js.map +1 -1
  23. package/dist/index.d.ts +3 -2
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/language/include-resolver.d.ts +35 -6
  28. package/dist/language/include-resolver.d.ts.map +1 -1
  29. package/dist/language/include-resolver.js +119 -51
  30. package/dist/language/include-resolver.js.map +1 -1
  31. package/dist/language/include-waves.d.ts +2 -2
  32. package/dist/language/include-waves.d.ts.map +1 -1
  33. package/dist/language/include-waves.js +3 -3
  34. package/dist/language/include-waves.js.map +1 -1
  35. package/dist/language/validator/properties.js +3 -3
  36. package/dist/language/validator/properties.js.map +1 -1
  37. package/dist/util/node-read-file.d.ts +1 -0
  38. package/dist/util/node-read-file.d.ts.map +1 -1
  39. package/dist/util/node-read-file.js +4 -0
  40. package/dist/util/node-read-file.js.map +1 -1
  41. package/dist/util/posix-path.d.ts +5 -0
  42. package/dist/util/posix-path.d.ts.map +1 -1
  43. package/dist/util/posix-path.js +27 -3
  44. package/dist/util/posix-path.js.map +1 -1
  45. package/package.json +1 -1
  46. package/src/diagnostics/index.ts +42 -1
  47. package/src/i18n/codes.ts +16 -0
  48. package/src/i18n/include-message-types.ts +22 -0
  49. package/src/i18n/index.ts +1 -0
  50. package/src/i18n/messages.en.ts +45 -0
  51. package/src/i18n/messages.fr.ts +46 -0
  52. package/src/index.ts +4 -0
  53. package/src/language/include-resolver.ts +166 -60
  54. package/src/language/include-waves.ts +3 -7
  55. package/src/language/validator/properties.ts +3 -3
  56. package/src/util/node-read-file.ts +5 -0
  57. package/src/util/posix-path.ts +28 -3
@@ -44,12 +44,22 @@ import {
44
44
  isWorkingDeclaration,
45
45
  } from '../generated/ast.js';
46
46
  import type { MessageCode } from '../i18n/codes.js';
47
- import { basename, dirname, resolve as resolvePath } from '../util/posix-path.js';
47
+ import type { E0203Args, E0208Args } from '../i18n/include-message-types.js';
48
+ import { type MessageArgs, tr } from '../i18n/index.js';
49
+ import {
50
+ basename,
51
+ dirname,
52
+ isAbsolute,
53
+ isWithin,
54
+ relative,
55
+ resolve as resolvePath,
56
+ } from '../util/posix-path.js';
48
57
  import { isRealIsoDate } from '../util/props.js';
49
58
  import { checkIncludedReferences } from './include-references.js';
50
59
  import {
51
60
  checkWaveAgreement,
52
61
  hasParseErrors,
62
+ nodeLocation,
53
63
  participates,
54
64
  runResolverWaveChecks,
55
65
  type WaveIncludeEdge,
@@ -68,20 +78,6 @@ function readStartProp(decl: RoadmapDeclaration | undefined): string | undefined
68
78
  return prop.value;
69
79
  }
70
80
 
71
- function formatStartMismatch(
72
- childRelPath: string,
73
- parentStart: string | undefined,
74
- childStart: string | undefined,
75
- ): string {
76
- if (parentStart && childStart) {
77
- return `Included "${childRelPath}" declares start:${childStart}, which doesn't match this file's start:${parentStart}. Both files must declare the same start date, or neither should.`;
78
- }
79
- if (parentStart) {
80
- return `Included "${childRelPath}" has no start:, but this file declares start:${parentStart}. Both files must declare the same start date, or neither should.`;
81
- }
82
- return `Included "${childRelPath}" declares start:${childStart}, but this file has no start:. Both files must declare the same start date, or neither should.`;
83
- }
84
-
85
81
  export interface ResolvedConfig {
86
82
  scale?: ScaleBlock;
87
83
  calendar?: CalendarBlock;
@@ -160,9 +156,10 @@ export interface ResolveDiagnostic {
160
156
  */
161
157
  range?: ResolveRange;
162
158
  /**
163
- * Stable code of a coded diagnostic (the wave rules, specs/waves.md
164
- * §7.4, and an included file's unresolved reference, NL.E0302). Absent
165
- * on every other resolver diagnostic.
159
+ * Stable code of a coded diagnostic: every include error (NL.E0203 to
160
+ * NL.E0210), the wave rules (specs/waves.md §7.4), and an included
161
+ * file's unresolved reference (NL.E0302). Absent on the shadow
162
+ * warnings, an included file's syntax error, and WV8.
166
163
  */
167
164
  code?: MessageCode;
168
165
  /** The message arguments as a rest tuple, as `acceptTr` stores them. */
@@ -188,9 +185,9 @@ export type IncludedSyntaxError = Extract<RawDiagnostic, { origin: 'lexer' | 'pa
188
185
 
189
186
  /**
190
187
  * True for a resolver diagnostic that consumers report like a validator
191
- * diagnostic (file, line, localized, exit 1): a coded one (the wave rules and
192
- * NL.E0302), one from the wave checks, or an included file's syntax error.
193
- * Every other resolver diagnostic keeps the include-error path
188
+ * diagnostic (file, line, localized, exit 1): a coded one (every include
189
+ * error, the wave rules and NL.E0302), one from the wave checks, or an
190
+ * included file's syntax error. What is left is the uncoded shadow warnings
194
191
  * (specs/waves.md §6.1).
195
192
  */
196
193
  export function isRoutedResolveDiagnostic(d: ResolveDiagnostic): boolean {
@@ -208,6 +205,11 @@ interface ResolveContext {
208
205
  services: NowlineServices;
209
206
  /** Absolute path of the root file, whose syntax errors the validator reports. */
210
207
  rootAbs: string;
208
+ policy?: IncludePolicy;
209
+ /** Resolves symlinks under a `rooted` policy. */
210
+ realPath: (absPath: string) => Promise<string>;
211
+ /** What a circular include's chain is shown relative to. */
212
+ displayBase: string;
211
213
  diagnostics: ResolveDiagnostic[];
212
214
  resolving: string[];
213
215
  processed: Map<string, { config: ResolvedConfig; content: ResolvedContent }>;
@@ -216,8 +218,6 @@ interface ResolveContext {
216
218
  files: Map<NowlineFile, string>;
217
219
  /** Include edges whose child was read, per including file, in include order. */
218
220
  edges: Map<string, WaveIncludeEdge[]>;
219
- /** Contents returned for a circular include (they never participate). */
220
- stubs: Set<ResolvedContent>;
221
221
  /** Children that failed include rule 12 (NL.E0202). */
222
222
  failedWaves: Set<string>;
223
223
  }
@@ -246,9 +246,33 @@ function emptyContent(): ResolvedContent {
246
246
  };
247
247
  }
248
248
 
249
+ /**
250
+ * How deep an include chain may go: the root's includes are depth 1. A
251
+ * deeper include is NL.E0210 and is not read, so a chain the cycle check
252
+ * cannot see (a symlinked directory that contains itself) still ends.
253
+ */
254
+ export const MAX_INCLUDE_DEPTH = 16;
255
+
256
+ /**
257
+ * Where includes may be read from (specs/dsl.md, Include rules 14 and 15).
258
+ * Omitted: anywhere the reader reaches, relative to the including file.
259
+ */
260
+ export type IncludePolicy =
261
+ /** Every include is NL.E0209 on its line, and nothing is read. */
262
+ | { kind: 'disabled' }
263
+ /**
264
+ * Every include, at any depth, must be a relative path that resolves,
265
+ * symlinks followed, to a `.nowline` file inside `root`; anything else
266
+ * is NL.E0208 on its line and is not read. `root` and the root file's
267
+ * path must be absolute real paths (symlinks already resolved).
268
+ * `realPath` resolves symlinks; Node's `fs.realpath` by default.
269
+ */
270
+ | { kind: 'rooted'; root: string; realPath?: (absPath: string) => Promise<string> };
271
+
249
272
  export interface ResolveIncludesOptions {
250
273
  services: NowlineServices;
251
274
  readFile?: (absPath: string) => Promise<string>;
275
+ includePolicy?: IncludePolicy;
252
276
  }
253
277
 
254
278
  export async function resolveIncludes(
@@ -265,17 +289,26 @@ export async function resolveIncludes(
265
289
  const { nodeReadFile } = await import('../util/node-read-file.js');
266
290
  return nodeReadFile(p);
267
291
  });
292
+ const policy = options.includePolicy;
293
+ const realPath =
294
+ (policy?.kind === 'rooted' ? policy.realPath : undefined) ??
295
+ (async (p: string) => {
296
+ const { nodeRealPath } = await import('../util/node-read-file.js');
297
+ return nodeRealPath(p);
298
+ });
268
299
  const absPath = resolvePath('', filePath);
269
300
  const ctx: ResolveContext = {
270
301
  services: options.services,
271
302
  rootAbs: absPath,
303
+ policy,
304
+ realPath,
305
+ displayBase: policy?.kind === 'rooted' ? policy.root : dirname(absPath),
272
306
  diagnostics: [],
273
307
  resolving: [],
274
308
  processed: new Map(),
275
309
  readFile,
276
310
  files: new Map(),
277
311
  edges: new Map(),
278
- stubs: new Set(),
279
312
  failedWaves: new Set(),
280
313
  };
281
314
  const { config, content } = await resolveFile(file, absPath, ctx);
@@ -309,17 +342,6 @@ async function resolveFile(
309
342
  if (ctx.processed.has(absPath)) {
310
343
  return ctx.processed.get(absPath)!;
311
344
  }
312
- if (ctx.resolving.includes(absPath)) {
313
- ctx.diagnostics.push({
314
- severity: 'error',
315
- message: `Circular include detected: ${[...ctx.resolving, absPath].join(' → ')}`,
316
- sourcePath: absPath,
317
- });
318
- const empty = { config: emptyConfig(), content: emptyContent() };
319
- ctx.stubs.add(empty.content);
320
- ctx.processed.set(absPath, empty);
321
- return empty;
322
- }
323
345
 
324
346
  // Each included file once, in every include mode: a `roadmap:ignore`
325
347
  // child's config is still merged (Include rule 13).
@@ -347,19 +369,52 @@ async function resolveFile(
347
369
  const seenIncludes = new Set<string>();
348
370
  for (const inc of file.includes) {
349
371
  const childRelPath = inc.path;
350
- const childAbsPath = resolvePath(dirname(absPath), childRelPath);
372
+ // Every include error is coded, at the path on the include line.
373
+ const fail = <K extends MessageCode>(code: K, ...args: MessageArgs<K>): void => {
374
+ ctx.diagnostics.push(includeError(absPath, inc, code, ...args));
375
+ };
376
+
377
+ if (ctx.policy?.kind === 'disabled') {
378
+ fail('NL.E0209', { path: childRelPath });
379
+ continue;
380
+ }
381
+ const located = await locateInclude(absPath, childRelPath, ctx);
382
+ if ('refused' in located) {
383
+ fail('NL.E0208', located.refused);
384
+ continue;
385
+ }
386
+ if ('unreadable' in located) {
387
+ fail('NL.E0203', located.unreadable);
388
+ continue;
389
+ }
390
+ const childAbsPath = located.absPath;
351
391
 
352
392
  if (seenIncludes.has(childAbsPath)) {
353
- ctx.diagnostics.push({
354
- severity: 'error',
355
- message: `Duplicate include "${childRelPath}" in ${basename(absPath)}.`,
356
- sourcePath: absPath,
357
- line: inc.$cstNode?.range.start.line,
358
- });
393
+ fail('NL.E0205', { path: childRelPath });
359
394
  continue;
360
395
  }
361
396
  seenIncludes.add(childAbsPath);
362
397
 
398
+ // Caught before the child is read, so a cycle reads nothing twice.
399
+ const cycleStart = ctx.resolving.indexOf(childAbsPath);
400
+ if (cycleStart >= 0) {
401
+ const chain = [...ctx.resolving.slice(cycleStart), childAbsPath]
402
+ .map((p) => relative(ctx.displayBase, p))
403
+ .join(' → ');
404
+ fail('NL.E0204', { path: childRelPath, chain });
405
+ continue;
406
+ }
407
+ // `resolving` holds the chain down to this file, the root included,
408
+ // so its length is the child's depth.
409
+ if (ctx.resolving.length > MAX_INCLUDE_DEPTH) {
410
+ fail('NL.E0210', { path: childRelPath, max: MAX_INCLUDE_DEPTH });
411
+ continue;
412
+ }
413
+ if (!childAbsPath.endsWith('.nowline')) {
414
+ fail('NL.E0203', { reason: 'not-nowline', path: childRelPath });
415
+ continue;
416
+ }
417
+
363
418
  const configMode = getIncludeMode(inc, 'config') ?? 'merge';
364
419
  const roadmapMode = getIncludeMode(inc, 'roadmap') ?? 'merge';
365
420
 
@@ -368,12 +423,7 @@ async function resolveFile(
368
423
  const text = await ctx.readFile(childAbsPath);
369
424
  childFile = await parseString(ctx.services, text, childAbsPath);
370
425
  } catch (err) {
371
- ctx.diagnostics.push({
372
- severity: 'error',
373
- message: `Could not read include "${childRelPath}": ${(err as Error).message}`,
374
- sourcePath: absPath,
375
- line: inc.$cstNode?.range.start.line,
376
- });
426
+ fail('NL.E0203', unreadableArgs(childRelPath, err));
377
427
  continue;
378
428
  }
379
429
 
@@ -390,7 +440,7 @@ async function resolveFile(
390
440
  mode: roadmapMode,
391
441
  childFile,
392
442
  childContent,
393
- participates: participates(childFile, childContent, ctx.stubs.has(childContent)),
443
+ participates: participates(childFile, childContent),
394
444
  });
395
445
 
396
446
  applyConfigMode(config, childConfig, configMode, childAbsPath, ctx.diagnostics);
@@ -409,12 +459,7 @@ async function resolveFile(
409
459
  const isParsed = !hasParseErrors(childFile);
410
460
 
411
461
  if (isParsed && roadmapMode === 'isolate' && !childContent.roadmap) {
412
- ctx.diagnostics.push({
413
- severity: 'error',
414
- message: `Cannot isolate "${childRelPath}": it has no roadmap declaration.`,
415
- sourcePath: absPath,
416
- line: inc.$cstNode?.range.start.line,
417
- });
462
+ fail('NL.E0206', { path: childRelPath });
418
463
  }
419
464
 
420
465
  // Non-ignored includes with a child roadmap must agree on start: with the parent.
@@ -424,11 +469,10 @@ async function resolveFile(
424
469
  const parentStart = readStartProp(file.roadmapDecl);
425
470
  const childStart = readStartProp(childFile.roadmapDecl);
426
471
  if (parentStart !== childStart) {
427
- ctx.diagnostics.push({
428
- severity: 'error',
429
- message: formatStartMismatch(childRelPath, parentStart, childStart),
430
- sourcePath: absPath,
431
- line: inc.$cstNode?.range.start.line,
472
+ fail('NL.E0207', {
473
+ path: childRelPath,
474
+ ...(parentStart ? { parentStart } : {}),
475
+ ...(childStart ? { childStart } : {}),
432
476
  });
433
477
  }
434
478
  }
@@ -450,6 +494,68 @@ async function resolveFile(
450
494
  return result;
451
495
  }
452
496
 
497
+ /** A coded include error at `inc`'s path, in the including file. */
498
+ function includeError<K extends MessageCode>(
499
+ sourcePath: string,
500
+ inc: IncludeDeclaration,
501
+ code: K,
502
+ ...args: MessageArgs<K>
503
+ ): ResolveDiagnostic {
504
+ return {
505
+ severity: 'error',
506
+ message: tr('en-US', code, ...args),
507
+ sourcePath,
508
+ ...nodeLocation(inc, 'path'),
509
+ code,
510
+ args,
511
+ };
512
+ }
513
+
514
+ type IncludeLocation = { absPath: string } | { refused: E0208Args } | { unreadable: E0203Args };
515
+
516
+ /**
517
+ * Where `include "<path>"` in `parentAbs` reads from, under the policy.
518
+ * Unrooted: the path resolved against the parent's directory, as written.
519
+ * Rooted: an absolute path, or one that leaves the root before or after
520
+ * symlinks are resolved, is refused; otherwise the real path, so a file
521
+ * reached through two spellings is one file. Nothing is read here.
522
+ */
523
+ async function locateInclude(
524
+ parentAbs: string,
525
+ path: string,
526
+ ctx: ResolveContext,
527
+ ): Promise<IncludeLocation> {
528
+ const policy = ctx.policy;
529
+ if (policy?.kind !== 'rooted') return { absPath: resolvePath(dirname(parentAbs), path) };
530
+ if (isAbsolute(path)) return { refused: { reason: 'absolute', path } };
531
+ const lexical = resolvePath(dirname(parentAbs), path);
532
+ if (!isWithin(policy.root, lexical)) return { refused: { reason: 'parent', path } };
533
+ let real: string;
534
+ try {
535
+ real = await ctx.realPath(lexical);
536
+ } catch (err) {
537
+ return { unreadable: unreadableArgs(path, err) };
538
+ }
539
+ if (!isWithin(policy.root, real)) return { refused: { reason: 'symlink', path } };
540
+ return { absPath: real };
541
+ }
542
+
543
+ /** NL.E0203's reason for a failed read; the OS error's text only when no reason fits. */
544
+ function unreadableArgs(path: string, err: unknown): E0203Args {
545
+ switch ((err as { code?: unknown } | undefined)?.code) {
546
+ case 'ENOENT':
547
+ case 'ENOTDIR':
548
+ return { reason: 'not-found', path };
549
+ case 'EISDIR':
550
+ return { reason: 'is-directory', path };
551
+ case 'EACCES':
552
+ case 'EPERM':
553
+ return { reason: 'permission-denied', path };
554
+ }
555
+ const detail = err instanceof Error ? err.message : undefined;
556
+ return { reason: 'unreadable', path, ...(detail ? { detail } : {}) };
557
+ }
558
+
453
559
  /**
454
560
  * An included file's lexer and parser errors, at their line in that file.
455
561
  * An included file is parsed without validation, so nothing else reports
@@ -77,14 +77,10 @@ export function hasParseErrors(file: NowlineFile): boolean {
77
77
  /**
78
78
  * `participates(C)` from specs/waves.md §7.1: C declares a roadmap, its
79
79
  * resolved content has a swimlane, or it declares waves. A child that failed
80
- * to parse, or a circular-include stub, never participates.
80
+ * to parse never participates.
81
81
  */
82
- export function participates(
83
- childFile: NowlineFile,
84
- childContent: ResolvedContent,
85
- isStub: boolean,
86
- ): boolean {
87
- if (isStub || hasParseErrors(childFile)) return false;
82
+ export function participates(childFile: NowlineFile, childContent: ResolvedContent): boolean {
83
+ if (hasParseErrors(childFile)) return false;
88
84
  return (
89
85
  !!childFile.roadmapDecl || childContent.swimlanes.size > 0 || ownWaves(childFile).length > 0
90
86
  );
@@ -312,9 +312,9 @@ export function checkNoRawStyleProperties(
312
312
  // NL.E1104 / NL.E1105 where it is not allowed)
313
313
  // - the keys a wave may not take (already NL.E1105)
314
314
  //
315
- // Suggests the closest known key within 2 edits when one exists, so the
316
- // existing `DID_YOU_MEAN_RE` in `packages/cli/src/diagnostics/adapt.ts` picks
317
- // it up as a structured suggestion alongside the rendered message.
315
+ // Suggests the closest known key within 2 edits when one exists; the
316
+ // `suggested` arg is also the diagnostic's structured suggestion (see
317
+ // `resolveDiagnosticSuggestion` in `packages/core/src/diagnostics/index.ts`).
318
318
  export function checkUnknownEntityProperties(
319
319
  node: {
320
320
  $type: string;
@@ -9,3 +9,8 @@ export async function nodeReadFile(absPath: string): Promise<string> {
9
9
  const fs = await import('node:fs');
10
10
  return fs.promises.readFile(absPath, 'utf-8');
11
11
  }
12
+
13
+ export async function nodeRealPath(absPath: string): Promise<string> {
14
+ const fs = await import('node:fs');
15
+ return fs.promises.realpath(absPath);
16
+ }
@@ -1,6 +1,6 @@
1
1
  // Browser-safe path helpers used by the include resolver. The set is
2
- // deliberately narrow: dirname, basename, and resolve(parentDir, relative)
3
- // — exactly the operations the resolver performs. Keeping these in the
2
+ // deliberately narrow: dirname, basename, resolve(parentDir, relative),
3
+ // relative and isWithin — exactly the operations the resolver performs. Keeping these in the
4
4
  // `@nowline/core` source tree (instead of pulling in `pathe` or
5
5
  // `path-browserify`) avoids adding an embed-bundle dependency for
6
6
  // behaviour that is ~30 lines of code, and keeps Windows / POSIX
@@ -31,7 +31,7 @@ function dominantSep(...paths: string[]): '/' | '\\' {
31
31
  return '/';
32
32
  }
33
33
 
34
- function isAbsolute(p: string): boolean {
34
+ export function isAbsolute(p: string): boolean {
35
35
  if (!p) return false;
36
36
  if (p[0] === '/' || p[0] === '\\') return true;
37
37
  // Windows drive-letter form: `C:\\…` or `C:/…`.
@@ -92,3 +92,28 @@ function normalize(p: string, sep: '/' | '\\'): string {
92
92
  }
93
93
  return prefix + segments.join(sep);
94
94
  }
95
+
96
+ // Both paths absolute; drive letters compare case-insensitively.
97
+ function segmentsOf(p: string): string[] {
98
+ const normalized = resolve('', p).replace(/\\/g, '/');
99
+ const drive = /^[A-Za-z]:/.test(normalized) ? normalized.slice(0, 2).toLowerCase() : '';
100
+ const body = drive ? normalized.slice(2) : normalized;
101
+ return [drive, ...body.split('/').filter((s) => s !== '')];
102
+ }
103
+
104
+ /** True when absolute `p` is `dir` or lies below it. Lexical: symlinks are not followed. */
105
+ export function isWithin(dir: string, p: string): boolean {
106
+ const d = segmentsOf(dir);
107
+ const t = segmentsOf(p);
108
+ return d.length <= t.length && d.every((seg, i) => seg === t[i]);
109
+ }
110
+
111
+ /** The path from absolute `from` (a directory) to absolute `to`, with `/` separators. */
112
+ export function relative(from: string, to: string): string {
113
+ const f = segmentsOf(from);
114
+ const t = segmentsOf(to);
115
+ if (f[0] !== t[0]) return to;
116
+ let i = 0;
117
+ while (i < f.length && i < t.length && f[i] === t[i]) i++;
118
+ return [...f.slice(i).map(() => '..'), ...t.slice(i)].join('/') || '.';
119
+ }