@deepseek-ai/cordis-plugin-include 1.1.0 → 1.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { EntryGroup, EntryTree, isJsExpr } from "@deepseek-ai/cordis-plugin-loader";
2
- import { Service } from "@deepseek-ai/cordis";
2
+ import { Context, Service } from "@deepseek-ai/cordis";
3
3
  import { deepEqual, omit } from "@deepseek-ai/cosmokit";
4
4
  import { basename, dirname, extname, join } from "node:path";
5
5
  import { access, constants, readFile, rename, rm, writeFile } from "node:fs/promises";
6
6
  import { setTimeout } from "node:timers/promises";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
- import * as yaml from "js-yaml";
8
+ import { LineCounter, Scalar, YAMLError, YAMLParseError, isAlias, isMap, isNode, isScalar, isSeq, parseDocument, stringify, visit } from "yaml";
9
+ import { stringifyString } from "yaml/util";
9
10
  //#region lib/types/journal.js
10
11
  function diffOptions(legacy, options) {
11
12
  const changes = {};
@@ -211,106 +212,24 @@ function ensureIds(entries, used) {
211
212
  function ensureInsertIds(patches, used) {
212
213
  for (const patch of patches ?? []) if (patch.insert) ensureIds(patch.insert, used);
213
214
  }
214
- /**
215
- * Overlay `patches` onto a fresh clone of `data`. Inserted entries are cloned
216
- * too, so the tree owns every object it mounts.
217
- */
218
- function applyPatches(data, patches, warn) {
219
- data = structuredClone(data);
220
- if (!patches?.length) return data;
221
- const entryMap = /* @__PURE__ */ new Map();
222
- const buildMap = (entries) => {
223
- for (const entry of entries) {
224
- if (entry.id) entryMap.set(entry.id, entry);
225
- if (entry.group && Array.isArray(entry.config)) buildMap(entry.config);
226
- }
227
- };
228
- buildMap(data);
229
- for (const patch of patches) {
230
- const { id, insert, name, ...overrides } = patch;
231
- if (insert) {
232
- const clone = structuredClone(insert);
233
- if (id) {
234
- const target = entryMap.get(id);
235
- if (!target) {
236
- warn("patch insert: entry %C not found", id);
237
- continue;
238
- }
239
- if (!target.group) {
240
- warn("patch insert: entry %C is not a group", id);
241
- continue;
242
- }
243
- if (!Array.isArray(target.config)) target.config = [];
244
- target.config.push(...clone);
245
- } else data.push(...clone);
246
- buildMap(clone);
247
- continue;
248
- }
249
- if (!id) {
250
- warn("patch: id is required for non-insert patches");
251
- continue;
252
- }
253
- const target = entryMap.get(id);
254
- if (!target) {
255
- warn("patch: entry %C not found", id);
256
- continue;
257
- }
258
- if (name && name !== target.name) {
259
- warn("patch: name mismatch for %C (expected %C, got %C), skipping", id, target.name, name);
260
- continue;
261
- }
262
- for (const [key, value] of Object.entries(overrides)) {
263
- if (key === "id") continue;
264
- target[key] = value;
265
- }
266
- }
267
- return data;
268
- }
215
+ const FILE = { type: "file" };
216
+ /** Where every entry and key of a patched tree comes from. */
269
217
  var PatchIndex = class {
270
- patches;
271
- keys = /* @__PURE__ */ new Map();
272
- inserts = /* @__PURE__ */ new Map();
273
- constructor(patches) {
274
- this.patches = patches;
275
- patches.forEach((patch, index) => {
276
- const { id, insert } = patch;
277
- if (insert) {
278
- const walk = (list, parent) => {
279
- for (const options of list) {
280
- this.inserts.set(options.id, {
281
- type: "insert",
282
- index,
283
- list,
284
- options,
285
- parent
286
- });
287
- if (options.group && Array.isArray(options.config)) walk(options.config, options.id);
288
- }
289
- };
290
- walk(insert, id ?? null);
291
- return;
292
- }
293
- if (!id) return;
294
- const keys = this.keys.get(id) ?? /* @__PURE__ */ new Map();
295
- for (const key of Object.keys(omit(patch, [
296
- "id",
297
- "insert",
298
- "name"
299
- ]))) keys.set(key, index);
300
- this.keys.set(id, keys);
301
- });
218
+ owners;
219
+ keys;
220
+ constructor(owners, keys) {
221
+ this.owners = owners;
222
+ this.keys = keys;
302
223
  }
303
224
  /** Owner of the entry as a whole. */
304
225
  entry(id) {
305
- if (id === null) return { type: "file" };
306
- return this.inserts.get(id) ?? { type: "file" };
226
+ if (id === null) return FILE;
227
+ return this.owners.get(id) ?? FILE;
307
228
  }
308
229
  /** Owner of one key of an entry. */
309
230
  key(id, key) {
310
- const insert = this.inserts.get(id);
311
- if (insert) return insert;
312
231
  const index = this.keys.get(id)?.get(key);
313
- return index === void 0 ? { type: "file" } : {
232
+ return index === void 0 ? this.entry(id) : {
314
233
  type: "patch",
315
234
  index
316
235
  };
@@ -320,50 +239,142 @@ var PatchIndex = class {
320
239
  }
321
240
  };
322
241
  /**
242
+ * Overlay `patches` onto a fresh clone of `data`. Entry lists from patches
243
+ * are cloned too, so the tree owns every entry it mounts. The index is built
244
+ * in the same pass, so a patch that does not apply owns nothing.
245
+ */
246
+ function applyPatches(data, patches, warn = () => {}) {
247
+ data = structuredClone(data);
248
+ const entries = /* @__PURE__ */ new Map();
249
+ const owners = /* @__PURE__ */ new Map();
250
+ const keys = /* @__PURE__ */ new Map();
251
+ const mount = (list, owner) => {
252
+ for (const options of list) {
253
+ if (options.id) {
254
+ entries.set(options.id, options);
255
+ owners.set(options.id, owner);
256
+ keys.delete(options.id);
257
+ }
258
+ if (options.group && Array.isArray(options.config)) mount(options.config, owner);
259
+ }
260
+ };
261
+ const unmount = (list) => {
262
+ for (const options of list) {
263
+ if (options.id) {
264
+ entries.delete(options.id);
265
+ owners.delete(options.id);
266
+ keys.delete(options.id);
267
+ }
268
+ if (options.group && Array.isArray(options.config)) unmount(options.config);
269
+ }
270
+ };
271
+ mount(data, FILE);
272
+ patches?.forEach((patch, index) => {
273
+ const { id, insert, name, ...overrides } = patch;
274
+ const target = id ? entries.get(id) : void 0;
275
+ if (insert) {
276
+ if (id && !target) return warn("patch insert: entry %C not found", id);
277
+ if (target && !target.group) return warn("patch insert: entry %C is not a group", id);
278
+ const clone = structuredClone(insert);
279
+ if (target) {
280
+ if (!Array.isArray(target.config)) target.config = [];
281
+ target.config.push(...clone);
282
+ } else data.push(...clone);
283
+ mount(clone, {
284
+ type: "embedded",
285
+ index,
286
+ key: "insert"
287
+ });
288
+ return;
289
+ }
290
+ if (!id) return warn("patch: id is required for non-insert patches");
291
+ if (!target) return warn("patch: entry %C not found", id);
292
+ if (name && name !== target.name) return warn("patch: name mismatch for %C (expected %C, got %C), skipping", id, target.name, name);
293
+ if ("config" in overrides && target.group && Array.isArray(target.config)) unmount(target.config);
294
+ const overridden = keys.get(id) ?? /* @__PURE__ */ new Map();
295
+ keys.set(id, overridden);
296
+ for (const [key, value] of Object.entries(overrides)) {
297
+ target[key] = value;
298
+ overridden.set(key, index);
299
+ }
300
+ if ("config" in overrides && target.group && Array.isArray(target.config)) {
301
+ ensureIds(target.config, (id) => entries.has(id));
302
+ target.config = structuredClone(target.config);
303
+ mount(target.config, {
304
+ type: "embedded",
305
+ index,
306
+ key: "config"
307
+ });
308
+ }
309
+ });
310
+ return {
311
+ data,
312
+ index: new PatchIndex(owners, keys)
313
+ };
314
+ }
315
+ /**
323
316
  * Route a journal to its owners: file-owned changes are applied to `data`,
324
317
  * patch-owned ones to `patches`. Both are mutated in place, so pass clones.
325
318
  * Returns whether any patch changed.
326
319
  */
327
320
  function routeJournal(journal, data, patches, warn) {
328
- const index = new PatchIndex(patches);
321
+ let { index } = applyPatches(data, patches);
329
322
  let patched = false;
330
- const insertList = (owner) => owner.options.config ??= [];
323
+ const reindex = () => {
324
+ index = applyPatches(data, patches).index;
325
+ };
326
+ const container = (owner) => {
327
+ if (owner.type === "file") return {
328
+ list: data,
329
+ parent: null
330
+ };
331
+ const patch = patches[owner.index];
332
+ return {
333
+ list: patch[owner.key],
334
+ parent: patch.id ?? null
335
+ };
336
+ };
337
+ const children = (parent) => {
338
+ const owner = index.key(parent, "config");
339
+ if (owner.type === "file") return;
340
+ if (owner.type === "patch") {
341
+ const config = patches[owner.index].config;
342
+ return Array.isArray(config) ? config : void 0;
343
+ }
344
+ const found = flatten(container(owner).list).get(parent);
345
+ return found && (found.options.config ??= []);
346
+ };
331
347
  const placeAt = (options, parent, position) => {
332
- const owner = index.entry(parent);
333
- if (owner.type === "insert") {
334
- const list = insertList(owner);
348
+ const list = parent === null ? void 0 : children(parent);
349
+ if (list) {
335
350
  list.splice(Math.min(position, list.length), 0, options);
336
351
  patched = true;
337
352
  } else if (!place(data, options, parent, position)) warn("cannot place entry %C: group %C not found", options.id, parent);
338
353
  };
339
354
  for (const [id, record] of journal) {
340
355
  const owner = index.entry(id);
356
+ const { list, parent: base } = container(owner);
357
+ const embedded = owner.type === "embedded";
341
358
  if (record.kind === "remove") {
342
- if (owner.type === "insert") {
343
- owner.list.splice(owner.list.indexOf(owner.options), 1);
344
- patched = true;
345
- } else detach(data, id);
359
+ detach(list, id);
360
+ patched ||= embedded;
361
+ reindex();
346
362
  continue;
347
363
  }
348
- const current = owner.type === "insert" ? owner : flatten(data).get(id);
364
+ const current = flatten(list).get(id);
349
365
  if (!current) {
350
366
  const options = { id };
351
367
  applyChanges(options, record.changes);
352
368
  placeAt(options, record.parent ?? null, record.position);
369
+ reindex();
353
370
  continue;
354
371
  }
355
- if (record.parent !== void 0 && current.parent !== record.parent) {
356
- if (owner.type === "insert") {
357
- owner.list.splice(owner.list.indexOf(owner.options), 1);
358
- patched = true;
359
- } else detach(data, id);
372
+ if (record.parent !== void 0 && (current.parent ?? base) !== record.parent) {
373
+ detach(list, id);
374
+ patched ||= embedded;
360
375
  applyChanges(current.options, record.changes);
361
376
  placeAt(current.options, record.parent, record.position);
362
- continue;
363
- }
364
- if (owner.type === "insert") {
365
- applyChanges(current.options, record.changes);
366
- patched = true;
377
+ reindex();
367
378
  continue;
368
379
  }
369
380
  const patchChanges = {};
@@ -373,6 +384,7 @@ function routeJournal(journal, data, patches, warn) {
373
384
  (patchChanges[keyOwner.index] ??= {})[key] = record.changes[key];
374
385
  return false;
375
386
  });
387
+ patched ||= embedded;
376
388
  for (const [i, changes] of Object.entries(patchChanges)) {
377
389
  applyChanges(patches[i], changes);
378
390
  patched = true;
@@ -382,27 +394,118 @@ function routeJournal(journal, data, patches, warn) {
382
394
  }
383
395
  //#endregion
384
396
  //#region lib/types/index.js
385
- const JsExpr = new yaml.Type("tag:yaml.org,2002:js", {
386
- kind: "scalar",
387
- resolve: (data) => typeof data === "string",
388
- construct: (data) => ({ __jsExpr: data }),
389
- predicate: isJsExpr,
390
- represent: (data) => data["__jsExpr"]
391
- });
392
- /** YAML dialect preserving child-owned JavaScript expression nodes. */
393
- const entryListSchema = yaml.JSON_SCHEMA.extend(JsExpr);
394
- const schema = entryListSchema;
397
+ const driveLetter = /^[A-Za-z]:[\\/]/;
398
+ const yamlOptions = {
399
+ schema: "core",
400
+ customTags: [{
401
+ tag: "tag:yaml.org,2002:js",
402
+ identify: isJsExpr,
403
+ resolve: (source) => ({ __jsExpr: source }),
404
+ stringify: (item, ctx, onComment, onChompKeep) => {
405
+ const scalar = new Scalar(item.value.__jsExpr);
406
+ return stringifyString(Object.assign(scalar, { type: item.type }), ctx, onComment, onChompKeep);
407
+ }
408
+ }]
409
+ };
410
+ /**
411
+ * Parse text in Include's YAML dialect: YAML 1.2 under the core schema, plus `!!js`. A `!!js` scalar becomes a
412
+ * child-owned JavaScript expression node that stays literal until its owning Loader entry evaluates it. Include
413
+ * reads its own file with the same options.
414
+ * @param content - YAML source text.
415
+ * @returns the parsed value, or `undefined` for an empty document.
416
+ * @throws the first parse error, or the first warning such as an unknown tag; {@link entryYamlErrorPosition} reads its location.
417
+ */
418
+ function parseEntryYaml(content) {
419
+ const lines = new LineCounter();
420
+ const document = parseDocument(content, {
421
+ ...yamlOptions,
422
+ lineCounter: lines
423
+ });
424
+ const [error] = [
425
+ ...document.errors,
426
+ ...document.warnings,
427
+ ...unresolvedAliases(document)
428
+ ];
429
+ if (error) {
430
+ error.linePos ??= [lines.linePos(error.pos[0]), lines.linePos(error.pos[1])];
431
+ throw error;
432
+ }
433
+ return document.contents === null ? void 0 : document.toJS();
434
+ }
435
+ /**
436
+ * Serialize a value in Include's YAML dialect. JavaScript expression nodes are written as `!!js` scalars. The output
437
+ * never contains anchors or aliases: repeated object references are written out in full, and no option changes this.
438
+ * @param value - entry list, patch list, or entry fragment to serialize.
439
+ * @param options - output formatting.
440
+ * @returns YAML text ending with a newline.
441
+ */
442
+ function stringifyEntryYaml(value, options = {}) {
443
+ return stringify(value, {
444
+ ...yamlOptions,
445
+ singleQuote: true,
446
+ aliasDuplicateObjects: false,
447
+ lineWidth: options.lineWidth ?? 80
448
+ });
449
+ }
450
+ /**
451
+ * Locate a parse error thrown by {@link parseEntryYaml}.
452
+ * @param error - any caught value; only a parse error thrown by {@link parseEntryYaml} yields a position.
453
+ * @returns the one-based line and column of the error, or `undefined` when the error carries no source location.
454
+ */
455
+ function entryYamlErrorPosition(error) {
456
+ if (!(error instanceof YAMLError) || !error.linePos) return void 0;
457
+ const [{ line, col }] = error.linePos;
458
+ return {
459
+ line,
460
+ column: col
461
+ };
462
+ }
395
463
  const types = {
396
464
  ".json": "application/json",
397
465
  ".yaml": "application/yaml",
398
466
  ".yml": "application/yaml"
399
467
  };
468
+ function parseSyntax(content) {
469
+ const lines = new LineCounter();
470
+ return {
471
+ document: parseDocument(content, {
472
+ ...yamlOptions,
473
+ prettyErrors: false,
474
+ lineCounter: lines
475
+ }),
476
+ lines
477
+ };
478
+ }
479
+ /**
480
+ * The parser accepts an alias without a preceding anchor, which only fails in
481
+ * `toJS()` with an unlocated `ReferenceError`. Nodes are visited in document
482
+ * order, so an anchor is known exactly when it precedes the alias.
483
+ */
484
+ function unresolvedAliases(document) {
485
+ const anchors = /* @__PURE__ */ new Set();
486
+ const unresolved = [];
487
+ visit(document, (_, node) => {
488
+ if (isAlias(node)) {
489
+ if (!anchors.has(node.source)) unresolved.push(node);
490
+ } else if (isNode(node) && node.anchor) anchors.add(node.anchor);
491
+ });
492
+ return unresolved.map((node) => {
493
+ const [start, end] = node.range;
494
+ const message = anchors.has(node.source) ? `Alias *${node.source} must follow its anchor` : `Unresolved alias: *${node.source}`;
495
+ return new YAMLParseError([start, end], "BAD_ALIAS", message);
496
+ });
497
+ }
498
+ const jsonPosition = /\s+at position (\d+)(?: \(line \d+ column \d+\))?$/;
400
499
  var ConfigFileError = class extends Error {
401
500
  stage;
501
+ issues;
402
502
  name = "ConfigFileError";
403
- constructor(stage, path, cause) {
404
- super(`failed to ${stage} config file ${path}`, { cause });
503
+ constructor(stage, path, cause, issues = []) {
504
+ super([`failed to ${stage} config file ${path}`, ...issues.map(({ message, location }) => {
505
+ return ` - ${message} (at ${location.filename}:${location.line}:${location.column})`;
506
+ })].join("\n"), { cause });
405
507
  this.stage = stage;
508
+ this.issues = issues;
406
509
  }
407
510
  };
408
511
  /** The file changed under us between the pre-check and the rename. */
@@ -424,6 +527,53 @@ function isTransientRenameError(error) {
424
527
  const code = error?.code;
425
528
  return code === "EACCES" || code === "EPERM" || code === "EBUSY";
426
529
  }
530
+ /** Index path of an entry in a nested entry list. */
531
+ function findEntry(entries, id) {
532
+ for (const [index, options] of entries.entries()) {
533
+ if (options.id === id) return [index];
534
+ if (!options.group || !Array.isArray(options.config)) continue;
535
+ const path = findEntry(options.config, id);
536
+ if (path) return [
537
+ index,
538
+ "config",
539
+ ...path
540
+ ];
541
+ }
542
+ }
543
+ function findInvalidEntries(entries, prefix = []) {
544
+ return entries.flatMap((options, index) => {
545
+ if (!options || typeof options !== "object" || Array.isArray(options)) return [[...prefix, index]];
546
+ if (!options.group || !Array.isArray(options.config)) return [];
547
+ return findInvalidEntries(options.config, [
548
+ ...prefix,
549
+ index,
550
+ "config"
551
+ ]);
552
+ });
553
+ }
554
+ /**
555
+ * Range of the node at `path`, or of its deepest ancestor. A collection is
556
+ * represented by the key that holds it.
557
+ */
558
+ function seek(document, path) {
559
+ let node = document.contents;
560
+ let anchor = isNode(node) ? node.range : void 0;
561
+ for (const key of path) {
562
+ if (isAlias(node)) node = node.resolve(document);
563
+ if (isMap(node)) {
564
+ const pair = node.items.find((pair) => String(isScalar(pair.key) ? pair.key.value : pair.key) === String(key));
565
+ if (!pair) break;
566
+ node = pair.value;
567
+ if (isNode(pair.key)) anchor = pair.key.range;
568
+ } else if (isSeq(node)) {
569
+ const item = node.items[key];
570
+ if (!isNode(item)) break;
571
+ node = item;
572
+ anchor = item.range;
573
+ } else break;
574
+ }
575
+ return isScalar(node) ? node.range : anchor;
576
+ }
427
577
  var Include = class extends EntryTree {
428
578
  config;
429
579
  static inject = ["loader"];
@@ -434,6 +584,8 @@ var Include = class extends EntryTree {
434
584
  cache;
435
585
  /** Tree-side changes that have not reached the file yet. */
436
586
  journal = /* @__PURE__ */ new Map();
587
+ /** Where the entries of the applied tree come from. */
588
+ index;
437
589
  /** Ids we assigned to entries the file leaves anonymous. */
438
590
  anonymous = /* @__PURE__ */ new Map();
439
591
  dirtyRead = false;
@@ -449,7 +601,7 @@ var Include = class extends EntryTree {
449
601
  super(ctx);
450
602
  this.config = config;
451
603
  this.enableLogs = config.enableLogs ?? ctx.fiber.entry?.parent.tree.enableLogs ?? false;
452
- this.filename = fileURLToPath(new URL(this.config.path, this.ctx.baseUrl));
604
+ this.filename = fileURLToPath(process.platform === "win32" && driveLetter.test(this.config.path) ? pathToFileURL(this.config.path) : new URL(this.config.path, this.ctx.baseUrl));
453
605
  const ext = extname(this.filename);
454
606
  if (!types[ext]) throw new Error(`extension "${ext}" not supported`);
455
607
  this.type = types[ext];
@@ -464,7 +616,7 @@ var Include = class extends EntryTree {
464
616
  });
465
617
  }
466
618
  warn = (format, ...args) => {
467
- this.ctx.root.logger?.("loader").warn(format, ...args);
619
+ this.ctx[Context.root].logger?.("loader").warn(format, ...args);
468
620
  };
469
621
  async *[Service.init]() {
470
622
  try {
@@ -562,21 +714,67 @@ var Include = class extends EntryTree {
562
714
  }
563
715
  if (content === this.cache?.content) return;
564
716
  let data;
565
- try {
566
- data = this.type === "application/yaml" ? yaml.load(content, { schema }) : JSON.parse(content);
717
+ let syntax;
718
+ if (this.type === "application/yaml") {
719
+ syntax = parseSyntax(content);
720
+ const { document, lines } = syntax;
721
+ const errors = [
722
+ ...document.errors,
723
+ ...document.warnings,
724
+ ...unresolvedAliases(document)
725
+ ];
726
+ if (errors.length) {
727
+ const issues = errors.map((error) => ({
728
+ message: error.message,
729
+ location: this._locate(lines, error.pos[0])
730
+ }));
731
+ throw new ConfigFileError("parse", this.filename, void 0, issues);
732
+ }
733
+ data = document.toJS();
734
+ } else try {
735
+ data = JSON.parse(content);
567
736
  } catch (error) {
568
- throw new ConfigFileError("parse", this.filename, error);
737
+ const match = error instanceof SyntaxError && error.message.match(jsonPosition);
738
+ if (!match) throw new ConfigFileError("parse", this.filename, error);
739
+ const message = error.message.slice(0, match.index);
740
+ const location = this._locate(parseSyntax(content).lines, +match[1]);
741
+ throw new ConfigFileError("parse", this.filename, void 0, [{
742
+ message,
743
+ location
744
+ }]);
745
+ }
746
+ if (!Array.isArray(data)) {
747
+ const message = "config file must be a top-level array";
748
+ const { document, lines } = syntax ?? parseSyntax(content);
749
+ const range = document.contents?.range;
750
+ if (!range) throw new ConfigFileError("validate", this.filename, /* @__PURE__ */ new TypeError(message));
751
+ throw new ConfigFileError("validate", this.filename, void 0, [{
752
+ message,
753
+ location: this._locate(lines, range[0])
754
+ }]);
755
+ }
756
+ const invalid = findInvalidEntries(data);
757
+ if (invalid.length) {
758
+ const { document, lines } = syntax ?? parseSyntax(content);
759
+ const issues = invalid.map((path) => {
760
+ const range = seek(document, path);
761
+ return {
762
+ message: "entry must be an object",
763
+ location: this._locate(lines, range?.[0] ?? 0)
764
+ };
765
+ });
766
+ throw new ConfigFileError("validate", this.filename, void 0, issues);
569
767
  }
570
- if (!Array.isArray(data)) throw new ConfigFileError("validate", this.filename, /* @__PURE__ */ new TypeError("config file must be a top-level array"));
571
768
  this._assignIds(data);
572
769
  if (this.cache) {
573
- const index = new PatchIndex(this.config.patches ?? []);
770
+ const { index } = applyPatches(data, this.config.patches);
574
771
  const conflicts = reconcile(this.journal, flatten(this.cache.data), flatten(data), (id, key) => index.fileOwned(id, key));
575
772
  for (const { id, reason } of conflicts) this.ctx.logger.error("config conflict in %C: entry %C %s; file wins", this.filename, id, reason);
576
773
  }
577
774
  this.cache = {
578
775
  content,
579
- data
776
+ data,
777
+ syntax
580
778
  };
581
779
  this._scheduleApply();
582
780
  if (this.journal.size) this.dirtyWrite = true;
@@ -678,55 +876,100 @@ var Include = class extends EntryTree {
678
876
  }
679
877
  }
680
878
  dump(data) {
681
- return this.type === "application/yaml" ? yaml.dump(data, { schema }) : JSON.stringify(data, null, 2);
879
+ return this.type === "application/yaml" ? stringify(data, {
880
+ ...yamlOptions,
881
+ singleQuote: true
882
+ }) : JSON.stringify(data, null, 2);
883
+ }
884
+ getLocation(id, path) {
885
+ if (!this.cache || !this.index) return;
886
+ const record = this.journal.get(id);
887
+ if (record?.kind === "remove") return;
888
+ if (path.length && record && String(path[0]) in record.changes) return;
889
+ const owner = path.length ? this.index.key(id, String(path[0])) : this.index.entry(id);
890
+ if (owner.type === "patch") return this.ctx.fiber.entry?.getLocation([
891
+ "config",
892
+ "patches",
893
+ owner.index,
894
+ ...path
895
+ ]);
896
+ else if (owner.type === "embedded") {
897
+ const prefix = findEntry(this.config.patches[owner.index][owner.key], id);
898
+ if (!prefix) return;
899
+ return this.ctx.fiber.entry?.getLocation([
900
+ "config",
901
+ "patches",
902
+ owner.index,
903
+ owner.key,
904
+ ...prefix,
905
+ ...path
906
+ ]);
907
+ }
908
+ const prefix = findEntry(this.cache.data, id);
909
+ if (!prefix) return;
910
+ const { document, lines } = this.cache.syntax ??= parseSyntax(this.cache.content);
911
+ const range = seek(document, [...prefix, ...path]);
912
+ if (range) return this._locate(lines, range[0]);
913
+ }
914
+ _locate(lines, offset) {
915
+ const { line, col } = lines.linePos(offset);
916
+ return {
917
+ filename: this.filename,
918
+ line,
919
+ column: col
920
+ };
682
921
  }
683
922
  /**
684
923
  * Entries the file leaves anonymous get an id here, before the loader sees
685
924
  * them. One that looks exactly like an entry we named on the previous read
686
- * keeps that id, so editing a neighbor does not restart it; anything else
687
- * gets a fresh id. Assigned ids stay in memory until the next write.
925
+ * keeps that id, unless it is already explicitly owned, so editing a
926
+ * neighbor does not restart it; anything else gets a fresh id. Assigned
927
+ * ids stay in memory until the next write.
688
928
  */
689
929
  _assignIds(data) {
690
930
  const used = /* @__PURE__ */ new Set();
691
- const pending = [];
692
- const walk = (entries, parent) => {
931
+ const collect = (entries) => {
693
932
  for (const options of entries) {
694
933
  if (options.id) used.add(options.id);
695
- else pending.push({
696
- options,
697
- parent
698
- });
699
- if (options.group && Array.isArray(options.config)) walk(options.config, options.id ?? null);
934
+ if (options.group && Array.isArray(options.config)) collect(options.config);
700
935
  }
701
936
  };
702
- walk(data, null);
937
+ collect(data);
938
+ for (const patch of this.config.patches ?? []) if (patch.insert) collect(patch.insert);
703
939
  const previous = this.anonymous;
704
940
  this.anonymous = /* @__PURE__ */ new Map();
705
- for (const { options, parent } of pending) {
706
- let id;
707
- for (const [candidate, info] of previous) {
708
- if (info.parent !== parent || !deepEqual(info.options, options)) continue;
709
- id = candidate;
710
- previous.delete(candidate);
711
- break;
941
+ const assign = (entries, parent) => {
942
+ for (const options of entries) {
943
+ if (!options.id) {
944
+ let id;
945
+ for (const [candidate, info] of previous) {
946
+ if (info.parent !== parent || used.has(candidate) || !deepEqual(info.options, options)) continue;
947
+ id = candidate;
948
+ previous.delete(candidate);
949
+ break;
950
+ }
951
+ if (!id) do
952
+ id = Math.random().toString(16).slice(2, 10);
953
+ while (used.has(id) || this.store[id]);
954
+ used.add(id);
955
+ this.anonymous.set(id, {
956
+ parent,
957
+ options: structuredClone(options)
958
+ });
959
+ const rest = { ...options };
960
+ for (const key of Object.keys(options)) delete options[key];
961
+ Object.assign(options, { id }, rest);
962
+ }
963
+ if (options.group && Array.isArray(options.config)) assign(options.config, options.id);
712
964
  }
713
- if (!id) do
714
- id = Math.random().toString(16).slice(2, 10);
715
- while (used.has(id) || this.store[id]);
716
- used.add(id);
717
- this.anonymous.set(id, {
718
- parent,
719
- options: structuredClone(options)
720
- });
721
- const rest = { ...options };
722
- for (const key of Object.keys(options)) delete options[key];
723
- Object.assign(options, { id }, rest);
724
- }
965
+ };
966
+ assign(data, null);
725
967
  }
726
968
  _scheduleApply() {
727
969
  if (this._disposed || !this.cache) return;
728
- const tree = applyPatches(this.cache.data, this.config.patches, this.warn);
729
- this._pendingTree = applyJournal(tree, this.journal, void 0, this.warn);
970
+ const { data, index } = applyPatches(this.cache.data, this.config.patches, this.warn);
971
+ this.index = index;
972
+ this._pendingTree = applyJournal(data, this.journal, void 0, this.warn);
730
973
  this._applyTask ??= (async () => {
731
974
  try {
732
975
  while (this._pendingTree) {
@@ -741,4 +984,4 @@ var Include = class extends EntryTree {
741
984
  }
742
985
  };
743
986
  //#endregion
744
- export { ConfigFileError, Include, Include as default, applyPatches as applyEntryPatches, entryListSchema };
987
+ export { ConfigFileError, Include, Include as default, applyPatches as applyEntryPatches, entryYamlErrorPosition, parseEntryYaml, stringifyEntryYaml };