@skmtc/core 0.37.0 → 0.38.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.
@@ -4,9 +4,12 @@
4
4
  * AST-resolve each span's landmark + path, and build the sidecar.
5
5
  *
6
6
  * Pure function over its inputs — no I/O, no global state, no `toString`,
7
- * no pipeline hooks. The caller is `RenderContext` (folded in after the
8
- * single capture render), running this once per File when the run supplies
9
- * `attribution.postPass`. The CLI handles disk writes via a separate
7
+ * no pipeline hooks. The caller is `RenderContext`, which runs this right
8
+ * after each File renders, once per File, when the run supplies
9
+ * `attribution.postPass`. The capture channel's sink is still set at that
10
+ * point; it records nothing only because the sink is outside a
11
+ * `captureFile` call between files. So do not render snippets or call
12
+ * `toString` here. The CLI handles disk writes via a separate
10
13
  * `writeSidecar` wrapper.
11
14
  */
12
15
  import type { ParserAdapter } from './ParserAdapter.js';
@@ -4,9 +4,12 @@
4
4
  * AST-resolve each span's landmark + path, and build the sidecar.
5
5
  *
6
6
  * Pure function over its inputs — no I/O, no global state, no `toString`,
7
- * no pipeline hooks. The caller is `RenderContext` (folded in after the
8
- * single capture render), running this once per File when the run supplies
9
- * `attribution.postPass`. The CLI handles disk writes via a separate
7
+ * no pipeline hooks. The caller is `RenderContext`, which runs this right
8
+ * after each File renders, once per File, when the run supplies
9
+ * `attribution.postPass`. The capture channel's sink is still set at that
10
+ * point; it records nothing only because the sink is outside a
11
+ * `captureFile` call between files. So do not render snippets or call
12
+ * `toString` here. The CLI handles disk writes via a separate
10
13
  * `writeSidecar` wrapper.
11
14
  */
12
15
  import { attribute } from './attribute.js';
@@ -216,7 +216,7 @@ export class ParseContext {
216
216
  * removes those frames before it reads a trail as a document address.
217
217
  */
218
218
  parse(stackTrail) {
219
- __classPrivateFieldSet(this, _ParseContext_rootFrames, [...stackTrail.stackTrail], "f");
219
+ __classPrivateFieldSet(this, _ParseContext_rootFrames, stackTrail.stackTrail, "f");
220
220
  switch (this.protocol.type) {
221
221
  case 'oas': {
222
222
  const oasState = this.protocol;
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _RenderContext_captureChannel, _RenderContext_sink, _RenderContext_captures;
12
+ var _RenderContext_captureChannel, _RenderContext_capture;
13
13
  import invariant from 'tiny-invariant';
14
14
  import { normalizeWorkspacePath } from '../helpers/normalizeWorkspacePath.js';
15
15
  import { toResolvedArtifactPath } from '../helpers/toResolvedArtifactPath.js';
@@ -78,25 +78,11 @@ export class RenderContext {
78
78
  */
79
79
  _RenderContext_captureChannel.set(this, void 0);
80
80
  /**
81
- * Active capture sink for the in-progress render pass, or `undefined`
82
- * when rendering without attribution. `collate` checks this to decide
83
- * whether to capture; set + cleared by `render`.
81
+ * The capturing render in progress, or `undefined` when rendering
82
+ * without attribution. `collate` checks this to decide whether to
83
+ * capture; set + cleared by `render`.
84
84
  */
85
- _RenderContext_sink.set(this, void 0);
86
- /**
87
- * Per-file render output retained during a capturing render, consumed
88
- * by `render` to build sidecars. Reset each capturing render.
89
- */
90
- _RenderContext_captures.set(this, []
91
- /**
92
- * Creates a new RenderContext instance with the specified configuration.
93
- *
94
- * Initializes the rendering context with files to render, preview data,
95
- * formatting configuration, and logging/tracing infrastructure.
96
- *
97
- * @param args - Constructor arguments containing all required configuration
98
- */
99
- );
85
+ _RenderContext_capture.set(this, void 0);
100
86
  this.files = files;
101
87
  this.previews = previews;
102
88
  this.basePath = basePath;
@@ -151,11 +137,15 @@ export class RenderContext {
151
137
  // the shared channel for the single `collate` walk, and close it in
152
138
  // `finally`. Snippets' self-installed `toString` wrappers observe into
153
139
  // the sink; `collate` routes each File's render through it.
154
- const sink = new CaptureSink();
155
- __classPrivateFieldSet(this, _RenderContext_sink, sink, "f");
156
- __classPrivateFieldSet(this, _RenderContext_captures, [], "f");
140
+ const capture = {
141
+ sink: new CaptureSink(),
142
+ postPass: postPassConfig,
143
+ sidecars: {},
144
+ generationMap: []
145
+ };
146
+ __classPrivateFieldSet(this, _RenderContext_capture, capture, "f");
157
147
  if (__classPrivateFieldGet(this, _RenderContext_captureChannel, "f")) {
158
- __classPrivateFieldGet(this, _RenderContext_captureChannel, "f").sink = sink;
148
+ __classPrivateFieldGet(this, _RenderContext_captureChannel, "f").sink = capture.sink;
159
149
  }
160
150
  let result;
161
151
  try {
@@ -165,38 +155,14 @@ export class RenderContext {
165
155
  if (__classPrivateFieldGet(this, _RenderContext_captureChannel, "f")) {
166
156
  __classPrivateFieldGet(this, _RenderContext_captureChannel, "f").sink = undefined;
167
157
  }
168
- __classPrivateFieldSet(this, _RenderContext_sink, undefined, "f");
158
+ __classPrivateFieldSet(this, _RenderContext_capture, undefined, "f");
169
159
  }
170
- // Build one sidecar per captured File from the spans the sink
171
- // resolved (no re-render, no `toString`). Keyed by the resolved artifact
172
- // path, matching `artifacts` and the manifest, so a sidecar sits at
173
- // `<outDir>/<artifact key>.skm.json` where doctor looks for it.
174
- const { parser, schemaSrc, generatorMeta } = postPassConfig;
175
- const sidecars = {};
176
- const generationMap = [];
177
- for (const capture of __classPrivateFieldGet(this, _RenderContext_captures, "f")) {
178
- const sidecar = postPass({
179
- filePath: capture.filePath,
180
- source: capture.source,
181
- spans: capture.spans,
182
- schemaSrc,
183
- parser,
184
- generatorMeta
185
- });
186
- const artifactPath = toResolvedArtifactPath({
187
- basePath: this.basePath,
188
- destinationPath: capture.destinationPath
189
- });
190
- sidecars[artifactPath] = sidecar;
191
- generationMap.push(...entriesForSidecar(sidecar));
192
- }
193
- __classPrivateFieldSet(this, _RenderContext_captures, [], "f");
194
160
  return {
195
161
  artifacts: result.artifacts,
196
162
  files: result.files,
197
163
  previews: this.previews,
198
- sidecars,
199
- generationMap
164
+ sidecars: capture.sidecars,
165
+ generationMap: capture.generationMap
200
166
  };
201
167
  }
202
168
  /**
@@ -236,25 +202,26 @@ export class RenderContext {
236
202
  // JsonFile (and the non-capturing path) render plainly — the
237
203
  // installed wrapper is inert while the sink is not in a
238
204
  // `captureFile` call.
239
- let content;
240
- if (__classPrivateFieldGet(this, _RenderContext_sink, "f") && file instanceof CodeFileBase) {
241
- const captured = __classPrivateFieldGet(this, _RenderContext_sink, "f").captureFile(() => file.toString());
242
- content = captured.text;
243
- __classPrivateFieldGet(this, _RenderContext_captures, "f").push({
244
- destinationPath,
205
+ const capture = __classPrivateFieldGet(this, _RenderContext_capture, "f");
206
+ const captured = capture && file instanceof CodeFileBase
207
+ ? capture.sink.captureFile(() => file.toString())
208
+ : undefined;
209
+ const renderedFile = renderFile({
210
+ content: captured?.text ?? file.toString(),
211
+ destinationPath,
212
+ basePath: this.basePath
213
+ });
214
+ if (capture && captured) {
215
+ // The post-pass runs inside this file's trace, so a post-pass
216
+ // that throws stops the render here: this file and the files
217
+ // after it get no result, and the run fails with RUN_FAILED.
218
+ addSidecar(capture, {
219
+ artifactPath: renderedFile.path,
245
220
  filePath: file.path,
246
221
  source: captured.text,
247
222
  spans: captured.spans
248
223
  });
249
224
  }
250
- else {
251
- content = file.toString();
252
- }
253
- const renderedFile = renderFile({
254
- content,
255
- destinationPath,
256
- basePath: this.basePath
257
- });
258
225
  this.captureCurrentResult('success', st);
259
226
  return renderedFile;
260
227
  });
@@ -338,7 +305,22 @@ export class RenderContext {
338
305
  return file.findDefinitions({ name })?.[0];
339
306
  }
340
307
  }
341
- _RenderContext_captureChannel = new WeakMap(), _RenderContext_sink = new WeakMap(), _RenderContext_captures = new WeakMap();
308
+ _RenderContext_captureChannel = new WeakMap(), _RenderContext_capture = new WeakMap();
309
+ /**
310
+ * Builds the sidecar of one captured File from the spans the sink
311
+ * resolved (no re-render, no `toString`) and adds it to the capturing
312
+ * render. Keyed by the resolved artifact path, matching `artifacts` and
313
+ * the manifest, so a sidecar sits at `<outDir>/<artifact key>.skm.json`
314
+ * where doctor looks for it.
315
+ */
316
+ const addSidecar = (capture, { artifactPath, filePath, source, spans }) => {
317
+ const { parser, schemaSrc, generatorMeta } = capture.postPass;
318
+ const sidecar = postPass({ filePath, source, spans, schemaSrc, parser, generatorMeta });
319
+ capture.sidecars[artifactPath] = sidecar;
320
+ for (const entry of entriesForSidecar(sidecar)) {
321
+ capture.generationMap.push(entry);
322
+ }
323
+ };
342
324
  /**
343
325
  * Renders a single file with metadata calculation.
344
326
  *
@@ -2,7 +2,7 @@ import "../_dnt.polyfills.js";
2
2
  import { type JsonPointer } from '../types/JsonPointer.js';
3
3
  export declare class StackTrail {
4
4
  #private;
5
- constructor(stack?: string[]);
5
+ constructor(stack?: readonly string[]);
6
6
  /**
7
7
  * The canonical empty trail — used for nodes that were synthesized
8
8
  * programmatically rather than parsed from a source document (they
@@ -13,9 +13,10 @@ export declare class StackTrail {
13
13
  /** True when the trail holds no frames (a synthetic / positionless node). */
14
14
  isEmpty(): boolean;
15
15
  /**
16
- * Creates a shallow copy of the stack trail.
16
+ * Creates an independent trail with the same frames. The frames are
17
+ * shared, not copied.
17
18
  *
18
- * @returns A new StackTrail instance with copied frames
19
+ * @returns A new StackTrail instance with the same frames
19
20
  *
20
21
  * @example
21
22
  * ```typescript
@@ -29,8 +30,11 @@ export declare class StackTrail {
29
30
  */
30
31
  clone(): StackTrail;
31
32
  /**
32
- * The live array of stack frames, not a copy: {@link trace} pops it after
33
- * `fn` returns. Copy it (`[...trail.stackTrail]`) to keep the frames.
33
+ * The frames of the trail as a new read-only array, built on each read.
34
+ * Change the trail with {@link append}, {@link remove} or {@link trace},
35
+ * not through this array. The trail itself is live: {@link trace}
36
+ * removes its frame after `fn` returns, so read the frames inside `fn`
37
+ * to keep them.
34
38
  *
35
39
  * @returns Array of stack frames in order
36
40
  *
@@ -41,7 +45,7 @@ export declare class StackTrail {
41
45
  * console.log(frames); // ['components', 'schemas', 'User']
42
46
  * ```
43
47
  */
44
- get stackTrail(): string[];
48
+ get stackTrail(): readonly string[];
45
49
  /**
46
50
  * Appends frame(s) to the end of the trail.
47
51
  *
@@ -68,6 +72,10 @@ export declare class StackTrail {
68
72
  /**
69
73
  * Runs `fn` on a copy of the trail with `key` appended: one frame for a
70
74
  * string, one frame per element for an array.
75
+ *
76
+ * When `fn` returns, `key` is removed and must be the last frame. When
77
+ * `fn` throws, the copy goes back to the frames it started with and the
78
+ * error from `fn` is rethrown: a frame check there would replace it.
71
79
  */
72
80
  trace<T>(key: string | string[], fn: (st: StackTrail) => T): T;
73
81
  /** Async form of {@link trace}. */
@@ -9,16 +9,27 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _StackTrail_stack;
12
+ var _StackTrail_instances, _StackTrail_last, _StackTrail_mapFrames, _StackTrail_rootPhaseFrame, _StackTrail_frameAtDepth;
13
13
  import "../_dnt.polyfills.js";
14
14
  import { componentsKeys } from '../oas/components/Components.js';
15
15
  import { toJsonPointer } from '../types/JsonPointer.js';
16
- import { toDocumentFrames, toTrailString } from './documentTrail.js';
16
+ import { escapeTrailFrame, isPhaseFrame } from './documentTrail.js';
17
+ const toTrailFrame = (parent, frame) => ({
18
+ frame,
19
+ parent,
20
+ depth: (parent?.depth ?? 0) + 1
21
+ });
22
+ const asIs = (frame) => frame;
17
23
  export class StackTrail {
18
24
  constructor(stack = []) {
19
- /** Internal stack of traversal frames */
20
- _StackTrail_stack.set(this, void 0);
21
- __classPrivateFieldSet(this, _StackTrail_stack, stack, "f");
25
+ _StackTrail_instances.add(this);
26
+ /**
27
+ * Last frame of the trail; `undefined` for the empty trail. A parsed
28
+ * document holds one trail per node, so the frames are a shared linked
29
+ * list and not one array per trail.
30
+ */
31
+ _StackTrail_last.set(this, void 0);
32
+ __classPrivateFieldSet(this, _StackTrail_last, stack.reduce(toTrailFrame, undefined), "f");
22
33
  }
23
34
  /**
24
35
  * The canonical empty trail — used for nodes that were synthesized
@@ -31,12 +42,13 @@ export class StackTrail {
31
42
  }
32
43
  /** True when the trail holds no frames (a synthetic / positionless node). */
33
44
  isEmpty() {
34
- return __classPrivateFieldGet(this, _StackTrail_stack, "f").length === 0;
45
+ return __classPrivateFieldGet(this, _StackTrail_last, "f") === undefined;
35
46
  }
36
47
  /**
37
- * Creates a shallow copy of the stack trail.
48
+ * Creates an independent trail with the same frames. The frames are
49
+ * shared, not copied.
38
50
  *
39
- * @returns A new StackTrail instance with copied frames
51
+ * @returns A new StackTrail instance with the same frames
40
52
  *
41
53
  * @example
42
54
  * ```typescript
@@ -49,11 +61,16 @@ export class StackTrail {
49
61
  * ```
50
62
  */
51
63
  clone() {
52
- return new StackTrail([...__classPrivateFieldGet(this, _StackTrail_stack, "f")]);
64
+ const copy = new StackTrail();
65
+ __classPrivateFieldSet(copy, _StackTrail_last, __classPrivateFieldGet(this, _StackTrail_last, "f"), "f");
66
+ return copy;
53
67
  }
54
68
  /**
55
- * The live array of stack frames, not a copy: {@link trace} pops it after
56
- * `fn` returns. Copy it (`[...trail.stackTrail]`) to keep the frames.
69
+ * The frames of the trail as a new read-only array, built on each read.
70
+ * Change the trail with {@link append}, {@link remove} or {@link trace},
71
+ * not through this array. The trail itself is live: {@link trace}
72
+ * removes its frame after `fn` returns, so read the frames inside `fn`
73
+ * to keep them.
57
74
  *
58
75
  * @returns Array of stack frames in order
59
76
  *
@@ -65,7 +82,7 @@ export class StackTrail {
65
82
  * ```
66
83
  */
67
84
  get stackTrail() {
68
- return __classPrivateFieldGet(this, _StackTrail_stack, "f");
85
+ return __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_mapFrames).call(this, asIs);
69
86
  }
70
87
  /**
71
88
  * Appends frame(s) to the end of the trail.
@@ -91,7 +108,7 @@ export class StackTrail {
91
108
  */
92
109
  append(frame) {
93
110
  if (typeof frame === 'string') {
94
- __classPrivateFieldGet(this, _StackTrail_stack, "f").push(frame);
111
+ __classPrivateFieldSet(this, _StackTrail_last, toTrailFrame(__classPrivateFieldGet(this, _StackTrail_last, "f"), frame), "f");
95
112
  return this;
96
113
  }
97
114
  if (Array.isArray(frame)) {
@@ -103,8 +120,13 @@ export class StackTrail {
103
120
  /**
104
121
  * Runs `fn` on a copy of the trail with `key` appended: one frame for a
105
122
  * string, one frame per element for an array.
123
+ *
124
+ * When `fn` returns, `key` is removed and must be the last frame. When
125
+ * `fn` throws, the copy goes back to the frames it started with and the
126
+ * error from `fn` is rethrown: a frame check there would replace it.
106
127
  */
107
128
  trace(key, fn) {
129
+ const start = __classPrivateFieldGet(this, _StackTrail_last, "f");
108
130
  const stackTrail = this.clone();
109
131
  stackTrail.append(key);
110
132
  try {
@@ -113,12 +135,13 @@ export class StackTrail {
113
135
  return result;
114
136
  }
115
137
  catch (error) {
116
- stackTrail.remove(key);
138
+ __classPrivateFieldSet(stackTrail, _StackTrail_last, start, "f");
117
139
  throw error;
118
140
  }
119
141
  }
120
142
  /** Async form of {@link trace}. */
121
143
  async traceAsync(key, fn) {
144
+ const start = __classPrivateFieldGet(this, _StackTrail_last, "f");
122
145
  const stackTrail = this.clone();
123
146
  stackTrail.append(key);
124
147
  try {
@@ -127,7 +150,7 @@ export class StackTrail {
127
150
  return result;
128
151
  }
129
152
  catch (error) {
130
- stackTrail.remove(key);
153
+ __classPrivateFieldSet(stackTrail, _StackTrail_last, start, "f");
131
154
  throw error;
132
155
  }
133
156
  }
@@ -179,7 +202,7 @@ export class StackTrail {
179
202
  * ```
180
203
  */
181
204
  toJsonPointer() {
182
- return toJsonPointer(__classPrivateFieldGet(this, _StackTrail_stack, "f"));
205
+ return toJsonPointer(this.stackTrail);
183
206
  }
184
207
  /**
185
208
  * The **document-relative** JSON Pointer for a parsed node, with the
@@ -212,20 +235,20 @@ export class StackTrail {
212
235
  * ```
213
236
  */
214
237
  toSchemaPointer() {
215
- return toJsonPointer(toDocumentFrames(__classPrivateFieldGet(this, _StackTrail_stack, "f")));
238
+ return toJsonPointer(__classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_mapFrames).call(this, asIs, __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_rootPhaseFrame).call(this)));
216
239
  }
217
240
  toStackRef() {
218
- const [first, second, third] = this.stackTrail;
219
- if (first !== 'components') {
220
- return;
221
- }
222
- if (typeof second !== 'string' || !componentsKeys.includes(second)) {
241
+ // Reads the first three frames only, without building the whole array.
242
+ const third = __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_frameAtDepth).call(this, 3);
243
+ const second = third?.parent;
244
+ const first = second?.parent;
245
+ if (third === undefined || second === undefined || first?.frame !== 'components') {
223
246
  return;
224
247
  }
225
- if (typeof third !== 'string') {
248
+ if (!componentsKeys.includes(second.frame)) {
226
249
  return;
227
250
  }
228
- return `#/${first}/${second}/${third}`;
251
+ return `#/${first.frame}/${second.frame}/${third.frame}`;
229
252
  }
230
253
  /**
231
254
  * Removes frame(s) from the end of the trail.
@@ -252,9 +275,12 @@ export class StackTrail {
252
275
  */
253
276
  remove(frame) {
254
277
  if (typeof frame === 'string') {
255
- const lastItem = __classPrivateFieldGet(this, _StackTrail_stack, "f").pop();
256
- if (lastItem !== frame) {
257
- throw new Error(`Expected to remove frame '${frame}' but found '${lastItem}'`);
278
+ const last = __classPrivateFieldGet(this, _StackTrail_last, "f");
279
+ // The last frame leaves the trail whether or not it matches, as
280
+ // `Array.pop` did before the check.
281
+ __classPrivateFieldSet(this, _StackTrail_last, last?.parent, "f");
282
+ if (last?.frame !== frame) {
283
+ throw new Error(`Expected to remove frame '${frame}' but found '${last?.frame}'`);
258
284
  }
259
285
  return this;
260
286
  }
@@ -298,7 +324,7 @@ export class StackTrail {
298
324
  * ```
299
325
  */
300
326
  toString() {
301
- return toTrailString(__classPrivateFieldGet(this, _StackTrail_stack, "f"));
327
+ return __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_mapFrames).call(this, escapeTrailFrame).join(':');
302
328
  }
303
329
  /**
304
330
  * Reads a string written by {@link StackTrail.toString} back into a trail.
@@ -320,5 +346,27 @@ export class StackTrail {
320
346
  return new StackTrail(value.split(':').map(frame => frame.replace(/%(25|3A)/g, (_, code) => decodes[code])));
321
347
  }
322
348
  }
323
- _StackTrail_stack = new WeakMap();
349
+ _StackTrail_last = new WeakMap(), _StackTrail_instances = new WeakSet(), _StackTrail_mapFrames = function _StackTrail_mapFrames(fn, above) {
350
+ // Pushed and then reversed, so the array stays packed. An array made
351
+ // with `new Array(n)` stays holey in V8 after it is filled.
352
+ const frames = [];
353
+ for (let node = __classPrivateFieldGet(this, _StackTrail_last, "f"); node !== undefined && node !== above; node = node.parent) {
354
+ frames.push(fn(node.frame));
355
+ }
356
+ return frames.reverse();
357
+ }, _StackTrail_rootPhaseFrame = function _StackTrail_rootPhaseFrame() {
358
+ let found;
359
+ for (let node = __classPrivateFieldGet(this, _StackTrail_last, "f"); node !== undefined; node = node.parent) {
360
+ if (isPhaseFrame(node.frame)) {
361
+ found = node;
362
+ }
363
+ }
364
+ return found;
365
+ }, _StackTrail_frameAtDepth = function _StackTrail_frameAtDepth(depth) {
366
+ let node = __classPrivateFieldGet(this, _StackTrail_last, "f");
367
+ while (node !== undefined && node.depth > depth) {
368
+ node = node.parent;
369
+ }
370
+ return node?.depth === depth ? node : undefined;
371
+ };
324
372
  const decodes = { '25': '%', '3A': ':' };
@@ -1,10 +1,14 @@
1
+ /** Escapes `%` as `%25` and `:` as `%3A` inside one trail frame. */
2
+ export declare const escapeTrailFrame: (frame: string) => string;
3
+ /** True for a phase frame that `CoreContext.toArtifacts` seeds. */
4
+ export declare const isPhaseFrame: (frame: string) => boolean;
1
5
  /** Joins trail frames with `:`, escaping `%` as `%25` and `:` as `%3A` inside a frame. */
2
- export declare const toTrailString: (frames: string[]) => string;
6
+ export declare const toTrailString: (frames: readonly string[]) => string;
3
7
  /**
4
8
  * The frames of a trail that address the input document: everything after
5
9
  * the first phase frame, or every frame when there is no phase frame.
6
10
  */
7
- export declare const toDocumentFrames: (frames: string[]) => string[];
11
+ export declare const toDocumentFrames: (frames: readonly string[]) => readonly string[];
8
12
  /**
9
13
  * The document-relative trail in `StackTrail.toString` form.
10
14
  *
@@ -14,4 +18,4 @@ export declare const toDocumentFrames: (frames: string[]) => string[];
14
18
  * // 'paths:/pets:parameters:0'
15
19
  * ```
16
20
  */
17
- export declare const toDocumentString: (frames: string[]) => string;
21
+ export declare const toDocumentString: (frames: readonly string[]) => string;
@@ -2,8 +2,12 @@ const escapes = { '%': '%25', ':': '%3A' };
2
2
  // Phase frames seeded by `CoreContext.toArtifacts` (PhaseType plus the
3
3
  // `post-pass` trace).
4
4
  const phaseFrames = new Set(['parse', 'generate', 'render', 'post-pass']);
5
+ /** Escapes `%` as `%25` and `:` as `%3A` inside one trail frame. */
6
+ export const escapeTrailFrame = (frame) => frame.replace(/[%:]/g, character => escapes[character]);
7
+ /** True for a phase frame that `CoreContext.toArtifacts` seeds. */
8
+ export const isPhaseFrame = (frame) => phaseFrames.has(frame);
5
9
  /** Joins trail frames with `:`, escaping `%` as `%25` and `:` as `%3A` inside a frame. */
6
- export const toTrailString = (frames) => frames.map(frame => frame.replace(/[%:]/g, character => escapes[character])).join(':');
10
+ export const toTrailString = (frames) => frames.map(escapeTrailFrame).join(':');
7
11
  /**
8
12
  * The frames of a trail that address the input document: everything after
9
13
  * the first phase frame, or every frame when there is no phase frame.
@@ -13,7 +17,7 @@ export const toDocumentFrames = (frames) => {
13
17
  // FIRST match is the boundary — a document key that happens to share a
14
18
  // phase name (e.g. a schema literally named `parse`) appears later and
15
19
  // is unaffected.
16
- const phaseIndex = frames.findIndex(frame => phaseFrames.has(frame));
20
+ const phaseIndex = frames.findIndex(isPhaseFrame);
17
21
  return phaseIndex === -1 ? frames : frames.slice(phaseIndex + 1);
18
22
  };
19
23
  /**
@@ -24,8 +24,8 @@ export declare class ResultsLog {
24
24
  * Captures `result` at `stackTrail`, unless a more severe result is
25
25
  * already recorded there.
26
26
  *
27
- * Stores a copy of the frames: `StackTrail.trace` pops the live array
28
- * after its callback returns.
27
+ * Stores the frames as they are now: `StackTrail.trace` removes its
28
+ * frame from the trail after its callback returns.
29
29
  */
30
30
  capture(stackTrail: StackTrail, result: ResultType): void;
31
31
  /**
@@ -10,6 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _ResultsLog_instances, _ResultsLog_results, _ResultsLog_incomingResultIsWorse;
13
+ import { toTrailString } from '../context/documentTrail.js';
13
14
  /**
14
15
  * Records one result per stack trail and builds the `manifest.results` tree.
15
16
  *
@@ -41,13 +42,15 @@ export class ResultsLog {
41
42
  * Captures `result` at `stackTrail`, unless a more severe result is
42
43
  * already recorded there.
43
44
  *
44
- * Stores a copy of the frames: `StackTrail.trace` pops the live array
45
- * after its callback returns.
45
+ * Stores the frames as they are now: `StackTrail.trace` removes its
46
+ * frame from the trail after its callback returns.
46
47
  */
47
48
  capture(stackTrail, result) {
48
- const key = stackTrail.toString();
49
+ // `stackTrail` builds a new array on each read, so read it once.
50
+ const frames = stackTrail.stackTrail;
51
+ const key = toTrailString(frames);
49
52
  if (__classPrivateFieldGet(this, _ResultsLog_instances, "m", _ResultsLog_incomingResultIsWorse).call(this, __classPrivateFieldGet(this, _ResultsLog_results, "f").get(key)?.result, result)) {
50
- __classPrivateFieldGet(this, _ResultsLog_results, "f").set(key, { frames: [...stackTrail.stackTrail], result });
53
+ __classPrivateFieldGet(this, _ResultsLog_results, "f").set(key, { frames, result });
51
54
  }
52
55
  }
53
56
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skmtc/core",
3
- "version": "0.37.0",
3
+ "version": "0.38.0",
4
4
  "description": "Skmtc is a declarative code generation framework",
5
5
  "keywords": [
6
6
  "openapi",
@@ -4,9 +4,12 @@
4
4
  * AST-resolve each span's landmark + path, and build the sidecar.
5
5
  *
6
6
  * Pure function over its inputs — no I/O, no global state, no `toString`,
7
- * no pipeline hooks. The caller is `RenderContext` (folded in after the
8
- * single capture render), running this once per File when the run supplies
9
- * `attribution.postPass`. The CLI handles disk writes via a separate
7
+ * no pipeline hooks. The caller is `RenderContext`, which runs this right
8
+ * after each File renders, once per File, when the run supplies
9
+ * `attribution.postPass`. The capture channel's sink is still set at that
10
+ * point; it records nothing only because the sink is outside a
11
+ * `captureFile` call between files. So do not render snippets or call
12
+ * `toString` here. The CLI handles disk writes via a separate
10
13
  * `writeSidecar` wrapper.
11
14
  */
12
15
  import type { ParserAdapter } from './ParserAdapter.js';
@@ -5,9 +5,12 @@
5
5
  * AST-resolve each span's landmark + path, and build the sidecar.
6
6
  *
7
7
  * Pure function over its inputs — no I/O, no global state, no `toString`,
8
- * no pipeline hooks. The caller is `RenderContext` (folded in after the
9
- * single capture render), running this once per File when the run supplies
10
- * `attribution.postPass`. The CLI handles disk writes via a separate
8
+ * no pipeline hooks. The caller is `RenderContext`, which runs this right
9
+ * after each File renders, once per File, when the run supplies
10
+ * `attribution.postPass`. The capture channel's sink is still set at that
11
+ * point; it records nothing only because the sink is outside a
12
+ * `captureFile` call between files. So do not render snippets or call
13
+ * `toString` here. The CLI handles disk writes via a separate
11
14
  * `writeSidecar` wrapper.
12
15
  */
13
16
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -219,7 +219,7 @@ class ParseContext {
219
219
  * removes those frames before it reads a trail as a document address.
220
220
  */
221
221
  parse(stackTrail) {
222
- __classPrivateFieldSet(this, _ParseContext_rootFrames, [...stackTrail.stackTrail], "f");
222
+ __classPrivateFieldSet(this, _ParseContext_rootFrames, stackTrail.stackTrail, "f");
223
223
  switch (this.protocol.type) {
224
224
  case 'oas': {
225
225
  const oasState = this.protocol;
@@ -13,7 +13,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
13
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
15
  };
16
- var _RenderContext_captureChannel, _RenderContext_sink, _RenderContext_captures;
16
+ var _RenderContext_captureChannel, _RenderContext_capture;
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.RenderContext = void 0;
19
19
  const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
@@ -84,25 +84,11 @@ class RenderContext {
84
84
  */
85
85
  _RenderContext_captureChannel.set(this, void 0);
86
86
  /**
87
- * Active capture sink for the in-progress render pass, or `undefined`
88
- * when rendering without attribution. `collate` checks this to decide
89
- * whether to capture; set + cleared by `render`.
87
+ * The capturing render in progress, or `undefined` when rendering
88
+ * without attribution. `collate` checks this to decide whether to
89
+ * capture; set + cleared by `render`.
90
90
  */
91
- _RenderContext_sink.set(this, void 0);
92
- /**
93
- * Per-file render output retained during a capturing render, consumed
94
- * by `render` to build sidecars. Reset each capturing render.
95
- */
96
- _RenderContext_captures.set(this, []
97
- /**
98
- * Creates a new RenderContext instance with the specified configuration.
99
- *
100
- * Initializes the rendering context with files to render, preview data,
101
- * formatting configuration, and logging/tracing infrastructure.
102
- *
103
- * @param args - Constructor arguments containing all required configuration
104
- */
105
- );
91
+ _RenderContext_capture.set(this, void 0);
106
92
  this.files = files;
107
93
  this.previews = previews;
108
94
  this.basePath = basePath;
@@ -157,11 +143,15 @@ class RenderContext {
157
143
  // the shared channel for the single `collate` walk, and close it in
158
144
  // `finally`. Snippets' self-installed `toString` wrappers observe into
159
145
  // the sink; `collate` routes each File's render through it.
160
- const sink = new CaptureSink_js_1.CaptureSink();
161
- __classPrivateFieldSet(this, _RenderContext_sink, sink, "f");
162
- __classPrivateFieldSet(this, _RenderContext_captures, [], "f");
146
+ const capture = {
147
+ sink: new CaptureSink_js_1.CaptureSink(),
148
+ postPass: postPassConfig,
149
+ sidecars: {},
150
+ generationMap: []
151
+ };
152
+ __classPrivateFieldSet(this, _RenderContext_capture, capture, "f");
163
153
  if (__classPrivateFieldGet(this, _RenderContext_captureChannel, "f")) {
164
- __classPrivateFieldGet(this, _RenderContext_captureChannel, "f").sink = sink;
154
+ __classPrivateFieldGet(this, _RenderContext_captureChannel, "f").sink = capture.sink;
165
155
  }
166
156
  let result;
167
157
  try {
@@ -171,38 +161,14 @@ class RenderContext {
171
161
  if (__classPrivateFieldGet(this, _RenderContext_captureChannel, "f")) {
172
162
  __classPrivateFieldGet(this, _RenderContext_captureChannel, "f").sink = undefined;
173
163
  }
174
- __classPrivateFieldSet(this, _RenderContext_sink, undefined, "f");
164
+ __classPrivateFieldSet(this, _RenderContext_capture, undefined, "f");
175
165
  }
176
- // Build one sidecar per captured File from the spans the sink
177
- // resolved (no re-render, no `toString`). Keyed by the resolved artifact
178
- // path, matching `artifacts` and the manifest, so a sidecar sits at
179
- // `<outDir>/<artifact key>.skm.json` where doctor looks for it.
180
- const { parser, schemaSrc, generatorMeta } = postPassConfig;
181
- const sidecars = {};
182
- const generationMap = [];
183
- for (const capture of __classPrivateFieldGet(this, _RenderContext_captures, "f")) {
184
- const sidecar = (0, postPass_js_1.postPass)({
185
- filePath: capture.filePath,
186
- source: capture.source,
187
- spans: capture.spans,
188
- schemaSrc,
189
- parser,
190
- generatorMeta
191
- });
192
- const artifactPath = (0, toResolvedArtifactPath_js_1.toResolvedArtifactPath)({
193
- basePath: this.basePath,
194
- destinationPath: capture.destinationPath
195
- });
196
- sidecars[artifactPath] = sidecar;
197
- generationMap.push(...(0, generationMap_js_1.entriesForSidecar)(sidecar));
198
- }
199
- __classPrivateFieldSet(this, _RenderContext_captures, [], "f");
200
166
  return {
201
167
  artifacts: result.artifacts,
202
168
  files: result.files,
203
169
  previews: this.previews,
204
- sidecars,
205
- generationMap
170
+ sidecars: capture.sidecars,
171
+ generationMap: capture.generationMap
206
172
  };
207
173
  }
208
174
  /**
@@ -242,25 +208,26 @@ class RenderContext {
242
208
  // JsonFile (and the non-capturing path) render plainly — the
243
209
  // installed wrapper is inert while the sink is not in a
244
210
  // `captureFile` call.
245
- let content;
246
- if (__classPrivateFieldGet(this, _RenderContext_sink, "f") && file instanceof CodeFileBase_js_1.CodeFileBase) {
247
- const captured = __classPrivateFieldGet(this, _RenderContext_sink, "f").captureFile(() => file.toString());
248
- content = captured.text;
249
- __classPrivateFieldGet(this, _RenderContext_captures, "f").push({
250
- destinationPath,
211
+ const capture = __classPrivateFieldGet(this, _RenderContext_capture, "f");
212
+ const captured = capture && file instanceof CodeFileBase_js_1.CodeFileBase
213
+ ? capture.sink.captureFile(() => file.toString())
214
+ : undefined;
215
+ const renderedFile = renderFile({
216
+ content: captured?.text ?? file.toString(),
217
+ destinationPath,
218
+ basePath: this.basePath
219
+ });
220
+ if (capture && captured) {
221
+ // The post-pass runs inside this file's trace, so a post-pass
222
+ // that throws stops the render here: this file and the files
223
+ // after it get no result, and the run fails with RUN_FAILED.
224
+ addSidecar(capture, {
225
+ artifactPath: renderedFile.path,
251
226
  filePath: file.path,
252
227
  source: captured.text,
253
228
  spans: captured.spans
254
229
  });
255
230
  }
256
- else {
257
- content = file.toString();
258
- }
259
- const renderedFile = renderFile({
260
- content,
261
- destinationPath,
262
- basePath: this.basePath
263
- });
264
231
  this.captureCurrentResult('success', st);
265
232
  return renderedFile;
266
233
  });
@@ -345,7 +312,22 @@ class RenderContext {
345
312
  }
346
313
  }
347
314
  exports.RenderContext = RenderContext;
348
- _RenderContext_captureChannel = new WeakMap(), _RenderContext_sink = new WeakMap(), _RenderContext_captures = new WeakMap();
315
+ _RenderContext_captureChannel = new WeakMap(), _RenderContext_capture = new WeakMap();
316
+ /**
317
+ * Builds the sidecar of one captured File from the spans the sink
318
+ * resolved (no re-render, no `toString`) and adds it to the capturing
319
+ * render. Keyed by the resolved artifact path, matching `artifacts` and
320
+ * the manifest, so a sidecar sits at `<outDir>/<artifact key>.skm.json`
321
+ * where doctor looks for it.
322
+ */
323
+ const addSidecar = (capture, { artifactPath, filePath, source, spans }) => {
324
+ const { parser, schemaSrc, generatorMeta } = capture.postPass;
325
+ const sidecar = (0, postPass_js_1.postPass)({ filePath, source, spans, schemaSrc, parser, generatorMeta });
326
+ capture.sidecars[artifactPath] = sidecar;
327
+ for (const entry of (0, generationMap_js_1.entriesForSidecar)(sidecar)) {
328
+ capture.generationMap.push(entry);
329
+ }
330
+ };
349
331
  /**
350
332
  * Renders a single file with metadata calculation.
351
333
  *
@@ -2,7 +2,7 @@ import "../_dnt.polyfills.js";
2
2
  import { type JsonPointer } from '../types/JsonPointer.js';
3
3
  export declare class StackTrail {
4
4
  #private;
5
- constructor(stack?: string[]);
5
+ constructor(stack?: readonly string[]);
6
6
  /**
7
7
  * The canonical empty trail — used for nodes that were synthesized
8
8
  * programmatically rather than parsed from a source document (they
@@ -13,9 +13,10 @@ export declare class StackTrail {
13
13
  /** True when the trail holds no frames (a synthetic / positionless node). */
14
14
  isEmpty(): boolean;
15
15
  /**
16
- * Creates a shallow copy of the stack trail.
16
+ * Creates an independent trail with the same frames. The frames are
17
+ * shared, not copied.
17
18
  *
18
- * @returns A new StackTrail instance with copied frames
19
+ * @returns A new StackTrail instance with the same frames
19
20
  *
20
21
  * @example
21
22
  * ```typescript
@@ -29,8 +30,11 @@ export declare class StackTrail {
29
30
  */
30
31
  clone(): StackTrail;
31
32
  /**
32
- * The live array of stack frames, not a copy: {@link trace} pops it after
33
- * `fn` returns. Copy it (`[...trail.stackTrail]`) to keep the frames.
33
+ * The frames of the trail as a new read-only array, built on each read.
34
+ * Change the trail with {@link append}, {@link remove} or {@link trace},
35
+ * not through this array. The trail itself is live: {@link trace}
36
+ * removes its frame after `fn` returns, so read the frames inside `fn`
37
+ * to keep them.
34
38
  *
35
39
  * @returns Array of stack frames in order
36
40
  *
@@ -41,7 +45,7 @@ export declare class StackTrail {
41
45
  * console.log(frames); // ['components', 'schemas', 'User']
42
46
  * ```
43
47
  */
44
- get stackTrail(): string[];
48
+ get stackTrail(): readonly string[];
45
49
  /**
46
50
  * Appends frame(s) to the end of the trail.
47
51
  *
@@ -68,6 +72,10 @@ export declare class StackTrail {
68
72
  /**
69
73
  * Runs `fn` on a copy of the trail with `key` appended: one frame for a
70
74
  * string, one frame per element for an array.
75
+ *
76
+ * When `fn` returns, `key` is removed and must be the last frame. When
77
+ * `fn` throws, the copy goes back to the frames it started with and the
78
+ * error from `fn` is rethrown: a frame check there would replace it.
71
79
  */
72
80
  trace<T>(key: string | string[], fn: (st: StackTrail) => T): T;
73
81
  /** Async form of {@link trace}. */
@@ -10,18 +10,29 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _StackTrail_stack;
13
+ var _StackTrail_instances, _StackTrail_last, _StackTrail_mapFrames, _StackTrail_rootPhaseFrame, _StackTrail_frameAtDepth;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.StackTrail = void 0;
16
16
  require("../_dnt.polyfills.js");
17
17
  const Components_js_1 = require("../oas/components/Components.js");
18
18
  const JsonPointer_js_1 = require("../types/JsonPointer.js");
19
19
  const documentTrail_js_1 = require("./documentTrail.js");
20
+ const toTrailFrame = (parent, frame) => ({
21
+ frame,
22
+ parent,
23
+ depth: (parent?.depth ?? 0) + 1
24
+ });
25
+ const asIs = (frame) => frame;
20
26
  class StackTrail {
21
27
  constructor(stack = []) {
22
- /** Internal stack of traversal frames */
23
- _StackTrail_stack.set(this, void 0);
24
- __classPrivateFieldSet(this, _StackTrail_stack, stack, "f");
28
+ _StackTrail_instances.add(this);
29
+ /**
30
+ * Last frame of the trail; `undefined` for the empty trail. A parsed
31
+ * document holds one trail per node, so the frames are a shared linked
32
+ * list and not one array per trail.
33
+ */
34
+ _StackTrail_last.set(this, void 0);
35
+ __classPrivateFieldSet(this, _StackTrail_last, stack.reduce(toTrailFrame, undefined), "f");
25
36
  }
26
37
  /**
27
38
  * The canonical empty trail — used for nodes that were synthesized
@@ -34,12 +45,13 @@ class StackTrail {
34
45
  }
35
46
  /** True when the trail holds no frames (a synthetic / positionless node). */
36
47
  isEmpty() {
37
- return __classPrivateFieldGet(this, _StackTrail_stack, "f").length === 0;
48
+ return __classPrivateFieldGet(this, _StackTrail_last, "f") === undefined;
38
49
  }
39
50
  /**
40
- * Creates a shallow copy of the stack trail.
51
+ * Creates an independent trail with the same frames. The frames are
52
+ * shared, not copied.
41
53
  *
42
- * @returns A new StackTrail instance with copied frames
54
+ * @returns A new StackTrail instance with the same frames
43
55
  *
44
56
  * @example
45
57
  * ```typescript
@@ -52,11 +64,16 @@ class StackTrail {
52
64
  * ```
53
65
  */
54
66
  clone() {
55
- return new StackTrail([...__classPrivateFieldGet(this, _StackTrail_stack, "f")]);
67
+ const copy = new StackTrail();
68
+ __classPrivateFieldSet(copy, _StackTrail_last, __classPrivateFieldGet(this, _StackTrail_last, "f"), "f");
69
+ return copy;
56
70
  }
57
71
  /**
58
- * The live array of stack frames, not a copy: {@link trace} pops it after
59
- * `fn` returns. Copy it (`[...trail.stackTrail]`) to keep the frames.
72
+ * The frames of the trail as a new read-only array, built on each read.
73
+ * Change the trail with {@link append}, {@link remove} or {@link trace},
74
+ * not through this array. The trail itself is live: {@link trace}
75
+ * removes its frame after `fn` returns, so read the frames inside `fn`
76
+ * to keep them.
60
77
  *
61
78
  * @returns Array of stack frames in order
62
79
  *
@@ -68,7 +85,7 @@ class StackTrail {
68
85
  * ```
69
86
  */
70
87
  get stackTrail() {
71
- return __classPrivateFieldGet(this, _StackTrail_stack, "f");
88
+ return __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_mapFrames).call(this, asIs);
72
89
  }
73
90
  /**
74
91
  * Appends frame(s) to the end of the trail.
@@ -94,7 +111,7 @@ class StackTrail {
94
111
  */
95
112
  append(frame) {
96
113
  if (typeof frame === 'string') {
97
- __classPrivateFieldGet(this, _StackTrail_stack, "f").push(frame);
114
+ __classPrivateFieldSet(this, _StackTrail_last, toTrailFrame(__classPrivateFieldGet(this, _StackTrail_last, "f"), frame), "f");
98
115
  return this;
99
116
  }
100
117
  if (Array.isArray(frame)) {
@@ -106,8 +123,13 @@ class StackTrail {
106
123
  /**
107
124
  * Runs `fn` on a copy of the trail with `key` appended: one frame for a
108
125
  * string, one frame per element for an array.
126
+ *
127
+ * When `fn` returns, `key` is removed and must be the last frame. When
128
+ * `fn` throws, the copy goes back to the frames it started with and the
129
+ * error from `fn` is rethrown: a frame check there would replace it.
109
130
  */
110
131
  trace(key, fn) {
132
+ const start = __classPrivateFieldGet(this, _StackTrail_last, "f");
111
133
  const stackTrail = this.clone();
112
134
  stackTrail.append(key);
113
135
  try {
@@ -116,12 +138,13 @@ class StackTrail {
116
138
  return result;
117
139
  }
118
140
  catch (error) {
119
- stackTrail.remove(key);
141
+ __classPrivateFieldSet(stackTrail, _StackTrail_last, start, "f");
120
142
  throw error;
121
143
  }
122
144
  }
123
145
  /** Async form of {@link trace}. */
124
146
  async traceAsync(key, fn) {
147
+ const start = __classPrivateFieldGet(this, _StackTrail_last, "f");
125
148
  const stackTrail = this.clone();
126
149
  stackTrail.append(key);
127
150
  try {
@@ -130,7 +153,7 @@ class StackTrail {
130
153
  return result;
131
154
  }
132
155
  catch (error) {
133
- stackTrail.remove(key);
156
+ __classPrivateFieldSet(stackTrail, _StackTrail_last, start, "f");
134
157
  throw error;
135
158
  }
136
159
  }
@@ -182,7 +205,7 @@ class StackTrail {
182
205
  * ```
183
206
  */
184
207
  toJsonPointer() {
185
- return (0, JsonPointer_js_1.toJsonPointer)(__classPrivateFieldGet(this, _StackTrail_stack, "f"));
208
+ return (0, JsonPointer_js_1.toJsonPointer)(this.stackTrail);
186
209
  }
187
210
  /**
188
211
  * The **document-relative** JSON Pointer for a parsed node, with the
@@ -215,20 +238,20 @@ class StackTrail {
215
238
  * ```
216
239
  */
217
240
  toSchemaPointer() {
218
- return (0, JsonPointer_js_1.toJsonPointer)((0, documentTrail_js_1.toDocumentFrames)(__classPrivateFieldGet(this, _StackTrail_stack, "f")));
241
+ return (0, JsonPointer_js_1.toJsonPointer)(__classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_mapFrames).call(this, asIs, __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_rootPhaseFrame).call(this)));
219
242
  }
220
243
  toStackRef() {
221
- const [first, second, third] = this.stackTrail;
222
- if (first !== 'components') {
223
- return;
224
- }
225
- if (typeof second !== 'string' || !Components_js_1.componentsKeys.includes(second)) {
244
+ // Reads the first three frames only, without building the whole array.
245
+ const third = __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_frameAtDepth).call(this, 3);
246
+ const second = third?.parent;
247
+ const first = second?.parent;
248
+ if (third === undefined || second === undefined || first?.frame !== 'components') {
226
249
  return;
227
250
  }
228
- if (typeof third !== 'string') {
251
+ if (!Components_js_1.componentsKeys.includes(second.frame)) {
229
252
  return;
230
253
  }
231
- return `#/${first}/${second}/${third}`;
254
+ return `#/${first.frame}/${second.frame}/${third.frame}`;
232
255
  }
233
256
  /**
234
257
  * Removes frame(s) from the end of the trail.
@@ -255,9 +278,12 @@ class StackTrail {
255
278
  */
256
279
  remove(frame) {
257
280
  if (typeof frame === 'string') {
258
- const lastItem = __classPrivateFieldGet(this, _StackTrail_stack, "f").pop();
259
- if (lastItem !== frame) {
260
- throw new Error(`Expected to remove frame '${frame}' but found '${lastItem}'`);
281
+ const last = __classPrivateFieldGet(this, _StackTrail_last, "f");
282
+ // The last frame leaves the trail whether or not it matches, as
283
+ // `Array.pop` did before the check.
284
+ __classPrivateFieldSet(this, _StackTrail_last, last?.parent, "f");
285
+ if (last?.frame !== frame) {
286
+ throw new Error(`Expected to remove frame '${frame}' but found '${last?.frame}'`);
261
287
  }
262
288
  return this;
263
289
  }
@@ -301,7 +327,7 @@ class StackTrail {
301
327
  * ```
302
328
  */
303
329
  toString() {
304
- return (0, documentTrail_js_1.toTrailString)(__classPrivateFieldGet(this, _StackTrail_stack, "f"));
330
+ return __classPrivateFieldGet(this, _StackTrail_instances, "m", _StackTrail_mapFrames).call(this, documentTrail_js_1.escapeTrailFrame).join(':');
305
331
  }
306
332
  /**
307
333
  * Reads a string written by {@link StackTrail.toString} back into a trail.
@@ -324,5 +350,27 @@ class StackTrail {
324
350
  }
325
351
  }
326
352
  exports.StackTrail = StackTrail;
327
- _StackTrail_stack = new WeakMap();
353
+ _StackTrail_last = new WeakMap(), _StackTrail_instances = new WeakSet(), _StackTrail_mapFrames = function _StackTrail_mapFrames(fn, above) {
354
+ // Pushed and then reversed, so the array stays packed. An array made
355
+ // with `new Array(n)` stays holey in V8 after it is filled.
356
+ const frames = [];
357
+ for (let node = __classPrivateFieldGet(this, _StackTrail_last, "f"); node !== undefined && node !== above; node = node.parent) {
358
+ frames.push(fn(node.frame));
359
+ }
360
+ return frames.reverse();
361
+ }, _StackTrail_rootPhaseFrame = function _StackTrail_rootPhaseFrame() {
362
+ let found;
363
+ for (let node = __classPrivateFieldGet(this, _StackTrail_last, "f"); node !== undefined; node = node.parent) {
364
+ if ((0, documentTrail_js_1.isPhaseFrame)(node.frame)) {
365
+ found = node;
366
+ }
367
+ }
368
+ return found;
369
+ }, _StackTrail_frameAtDepth = function _StackTrail_frameAtDepth(depth) {
370
+ let node = __classPrivateFieldGet(this, _StackTrail_last, "f");
371
+ while (node !== undefined && node.depth > depth) {
372
+ node = node.parent;
373
+ }
374
+ return node?.depth === depth ? node : undefined;
375
+ };
328
376
  const decodes = { '25': '%', '3A': ':' };
@@ -1,10 +1,14 @@
1
+ /** Escapes `%` as `%25` and `:` as `%3A` inside one trail frame. */
2
+ export declare const escapeTrailFrame: (frame: string) => string;
3
+ /** True for a phase frame that `CoreContext.toArtifacts` seeds. */
4
+ export declare const isPhaseFrame: (frame: string) => boolean;
1
5
  /** Joins trail frames with `:`, escaping `%` as `%25` and `:` as `%3A` inside a frame. */
2
- export declare const toTrailString: (frames: string[]) => string;
6
+ export declare const toTrailString: (frames: readonly string[]) => string;
3
7
  /**
4
8
  * The frames of a trail that address the input document: everything after
5
9
  * the first phase frame, or every frame when there is no phase frame.
6
10
  */
7
- export declare const toDocumentFrames: (frames: string[]) => string[];
11
+ export declare const toDocumentFrames: (frames: readonly string[]) => readonly string[];
8
12
  /**
9
13
  * The document-relative trail in `StackTrail.toString` form.
10
14
  *
@@ -14,4 +18,4 @@ export declare const toDocumentFrames: (frames: string[]) => string[];
14
18
  * // 'paths:/pets:parameters:0'
15
19
  * ```
16
20
  */
17
- export declare const toDocumentString: (frames: string[]) => string;
21
+ export declare const toDocumentString: (frames: readonly string[]) => string;
@@ -1,12 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.toDocumentString = exports.toDocumentFrames = exports.toTrailString = void 0;
3
+ exports.toDocumentString = exports.toDocumentFrames = exports.toTrailString = exports.isPhaseFrame = exports.escapeTrailFrame = void 0;
4
4
  const escapes = { '%': '%25', ':': '%3A' };
5
5
  // Phase frames seeded by `CoreContext.toArtifacts` (PhaseType plus the
6
6
  // `post-pass` trace).
7
7
  const phaseFrames = new Set(['parse', 'generate', 'render', 'post-pass']);
8
+ /** Escapes `%` as `%25` and `:` as `%3A` inside one trail frame. */
9
+ const escapeTrailFrame = (frame) => frame.replace(/[%:]/g, character => escapes[character]);
10
+ exports.escapeTrailFrame = escapeTrailFrame;
11
+ /** True for a phase frame that `CoreContext.toArtifacts` seeds. */
12
+ const isPhaseFrame = (frame) => phaseFrames.has(frame);
13
+ exports.isPhaseFrame = isPhaseFrame;
8
14
  /** Joins trail frames with `:`, escaping `%` as `%25` and `:` as `%3A` inside a frame. */
9
- const toTrailString = (frames) => frames.map(frame => frame.replace(/[%:]/g, character => escapes[character])).join(':');
15
+ const toTrailString = (frames) => frames.map(exports.escapeTrailFrame).join(':');
10
16
  exports.toTrailString = toTrailString;
11
17
  /**
12
18
  * The frames of a trail that address the input document: everything after
@@ -17,7 +23,7 @@ const toDocumentFrames = (frames) => {
17
23
  // FIRST match is the boundary — a document key that happens to share a
18
24
  // phase name (e.g. a schema literally named `parse`) appears later and
19
25
  // is unaffected.
20
- const phaseIndex = frames.findIndex(frame => phaseFrames.has(frame));
26
+ const phaseIndex = frames.findIndex(exports.isPhaseFrame);
21
27
  return phaseIndex === -1 ? frames : frames.slice(phaseIndex + 1);
22
28
  };
23
29
  exports.toDocumentFrames = toDocumentFrames;
@@ -24,8 +24,8 @@ export declare class ResultsLog {
24
24
  * Captures `result` at `stackTrail`, unless a more severe result is
25
25
  * already recorded there.
26
26
  *
27
- * Stores a copy of the frames: `StackTrail.trace` pops the live array
28
- * after its callback returns.
27
+ * Stores the frames as they are now: `StackTrail.trace` removes its
28
+ * frame from the trail after its callback returns.
29
29
  */
30
30
  capture(stackTrail: StackTrail, result: ResultType): void;
31
31
  /**
@@ -13,6 +13,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
13
13
  var _ResultsLog_instances, _ResultsLog_results, _ResultsLog_incomingResultIsWorse;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.ResultsLog = void 0;
16
+ const documentTrail_js_1 = require("../context/documentTrail.js");
16
17
  /**
17
18
  * Records one result per stack trail and builds the `manifest.results` tree.
18
19
  *
@@ -44,13 +45,15 @@ class ResultsLog {
44
45
  * Captures `result` at `stackTrail`, unless a more severe result is
45
46
  * already recorded there.
46
47
  *
47
- * Stores a copy of the frames: `StackTrail.trace` pops the live array
48
- * after its callback returns.
48
+ * Stores the frames as they are now: `StackTrail.trace` removes its
49
+ * frame from the trail after its callback returns.
49
50
  */
50
51
  capture(stackTrail, result) {
51
- const key = stackTrail.toString();
52
+ // `stackTrail` builds a new array on each read, so read it once.
53
+ const frames = stackTrail.stackTrail;
54
+ const key = (0, documentTrail_js_1.toTrailString)(frames);
52
55
  if (__classPrivateFieldGet(this, _ResultsLog_instances, "m", _ResultsLog_incomingResultIsWorse).call(this, __classPrivateFieldGet(this, _ResultsLog_results, "f").get(key)?.result, result)) {
53
- __classPrivateFieldGet(this, _ResultsLog_results, "f").set(key, { frames: [...stackTrail.stackTrail], result });
56
+ __classPrivateFieldGet(this, _ResultsLog_results, "f").set(key, { frames, result });
54
57
  }
55
58
  }
56
59
  /**