@deepseek-ai/cordis-plugin-loader 1.0.6 → 1.0.7-alpha.2

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/README.md CHANGED
@@ -48,6 +48,24 @@ root.loader.update(id, { config: { enabled: false } })
48
48
 
49
49
  For file-backed trees, use `@cordisjs/plugin-include`.
50
50
 
51
+ ## Module resolution
52
+
53
+ Without Node module internals, Loader resolves bare specifiers, package imports and self-references in the nearest package scope containing the configuration file. Relative specifiers use the configuration URL directly, and `cordis:` builtins bypass filesystem resolution. Other specifiers, including `node:` builtins and absolute URLs, initialize an ignored `.cordis/resolve.mjs` helper in that scope to preserve native ESM import conditions.
54
+
55
+ If no scope exists or writing the helper files fails, Loader uses its native import fallback. This fallback emits no diagnostic of its own; project-only dependencies can remain unavailable, and the resulting import error can name the Loader module rather than the configuration project. Failure to import a written helper propagates to the caller without this fallback.
56
+
57
+ Initialization results are cached for the lifetime of the resolver module, including failed writes and rejected helper imports. Fixing the filesystem does not retry initialization for an already cached scope. Concurrent initialization through filesystem aliases of the same package can contend for the temporary helper files and cause a write failure.
58
+
59
+ Node module internals are classified by their available APIs, including the v1 API used by Node 24.0–24.11.
60
+
51
61
  ## Volatile configuration
52
62
 
53
63
  `Entry.update` compares raw entry options strictly; when only `config` changed on an active fiber in an unchanged context, the pure `equalExceptVolatile` function in `config/diff.ts` compares the raw configs using Schemastery metadata. It ignores volatile fields at fixed object paths without executing expressions, validators or `internal/config` hooks. Object nodes use their declared defaults for null or absent values, including objects without volatile fields; equivalent defaults skip updates. Other ordinary values, parent expressions and unknown fields retain raw comparison. Recursive schema backedges use raw comparison. Entry passes the actual plugin schema; a non-Schemastery schema compares raw. Context changes, other option changes and pending fibers use ordinary updates. A volatile-only change retains the raw Fiber config for later activation, then `_commitVolatile` parses it through the fiber's `internal/config` hook and schema, commits the new values into the running references when every ordinary effective value still matches, and emits `loader/volatile-update` to the owning fiber with the changed paths. A changed ordinary effective value uses the ordinary remount with a debug log naming the entry; because strict comparison treats class instances other than URL, Date and RegExp by identity, an ordinary field whose transform builds a fresh instance on every parse always takes that remount. An invalid candidate is logged and leaves the running references unchanged. A throwing `loader/volatile-update` listener is logged and does not fail the update; the values are already committed. Group/Include retain child dispatch, and programmatic Fiber updates preserve saving and `noSave`; `simplify` is called with its schema receiver so saved config contains plain values.
64
+
65
+ ## Update completion
66
+
67
+ Entry updates await `loader/patch-context`, the Fiber update waterfall and disabled-entry disposal. Combined context/config changes refresh required bindings before restarting. Group and Include updates expose completion of their child updates; file persistence completes through Include’s `flush()`.
68
+
69
+ ## Tree mutation reports
70
+
71
+ `EntryTree.commit(change)` receives each mutation made through `EntryTree` methods synchronously after options and group membership change; file-driven `EntryGroup` reconciliation does not report. A missing `legacy` means creation; missing `options` means removal. Updates carry both, with `from` naming the previous group after a move within the tree; a move into another tree transfers the registrations of the entry and its group members, reports a removal to the source tree and a creation to the destination tree, and is rejected when the destination tree already holds the id. Explicit Fiber saves report their simplified configuration. File-driven reconciliation, parent teardown and Loader removal do not produce spurious self-disable reports. In-memory trees implement a no-op; Include journals the reports and reconciles them with file edits. Explicit entry ids may contain `:`; `resolve()` cannot address such entries by nested path, because `:` separates nested tree paths.
package/lib/index.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import { createRequire } from "node:module";
2
- import { Context, Inject, Service, composeError, resolveConfig } from "@deepseek-ai/cordis";
2
+ import { Context, Inject, Service, composeError } from "@deepseek-ai/cordis";
3
3
  import { deepEqual, defineProperty, isNonNullable, isNullable, updateVolatile, valueMap, volatileEntries } from "@deepseek-ai/cosmokit";
4
+ import fs from "node:fs";
5
+ import fsPromises from "node:fs/promises";
6
+ import path from "node:path";
7
+ import url from "node:url";
4
8
  //#region lib/types/internal.js
5
9
  /** Helpers for locating the current Node internal module loader. */
6
10
  var ModuleLoader;
@@ -69,10 +73,10 @@ var EntryGroup = class {
69
73
  }
70
74
  remove(id, isDispose = false) {
71
75
  const entry = this.tree.store[id];
72
- if (!entry) return;
76
+ if (!entry || entry.parent !== this) return;
77
+ delete this.tree.store[id];
73
78
  entry.fiber?.dispose();
74
79
  if (!isDispose) this.unlink(entry.options);
75
- delete this.tree.store[id];
76
80
  this.context.emit("loader/partial-dispose", entry, entry.options, false);
77
81
  }
78
82
  async update(config) {
@@ -105,9 +109,7 @@ var Group = class extends EntryGroup {
105
109
  super(ctx, ctx.fiber.entry.parent.tree);
106
110
  this.ctx = ctx;
107
111
  this.config = config;
108
- ctx.on("internal/update", (config) => {
109
- this.update(config);
110
- });
112
+ ctx.on("internal/update", (config) => this.update(config));
111
113
  }
112
114
  async *[Service.init]() {
113
115
  yield () => this.stop();
@@ -115,6 +117,67 @@ var Group = class extends EntryGroup {
115
117
  }
116
118
  };
117
119
  //#endregion
120
+ //#region lib/types/resolve.js
121
+ var __rewriteRelativeImportExtension$1 = function(path, preserveJsx) {
122
+ if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
123
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
124
+ });
125
+ return path;
126
+ };
127
+ const HELPER_FILES = {
128
+ ".gitignore": "# created by cordis automatically\n*\n",
129
+ "resolve.mjs": "export default (specifier) => import.meta.resolve(specifier)\n"
130
+ };
131
+ const cache = Object.create(null);
132
+ /** Nearest ancestor of `dir` that owns a `package.json`, if any. */
133
+ function findScope(dir) {
134
+ while (true) {
135
+ if (fs.existsSync(path.join(dir, "package.json"))) return dir;
136
+ const parent = path.dirname(dir);
137
+ if (parent === dir) return;
138
+ dir = parent;
139
+ }
140
+ }
141
+ function resolveScope(baseUrl) {
142
+ if (!baseUrl) return;
143
+ let dir;
144
+ try {
145
+ dir = url.fileURLToPath(new URL(".", baseUrl));
146
+ } catch {
147
+ return;
148
+ }
149
+ return findScope(path.resolve(dir));
150
+ }
151
+ async function write(filename, content) {
152
+ const temp = `${filename}.${process.pid}`;
153
+ await fsPromises.writeFile(temp, content);
154
+ await fsPromises.rename(temp, filename);
155
+ }
156
+ async function _createResolve(scope) {
157
+ const dir = path.join(scope, ".cordis");
158
+ try {
159
+ await fsPromises.mkdir(dir, { recursive: true });
160
+ for (const [name, content] of Object.entries(HELPER_FILES)) await write(path.join(dir, name), content);
161
+ } catch {
162
+ return;
163
+ }
164
+ const helperUrl = url.pathToFileURL(path.join(dir, "resolve.mjs")).href;
165
+ return (await import(__rewriteRelativeImportExtension$1(
166
+ /* @vite-ignore */
167
+ helperUrl
168
+ ))).default;
169
+ }
170
+ /**
171
+ * Create or reuse a native ESM resolver anchored in the config project's package scope.
172
+ * @param baseUrl Config file URL; absent, non-file or unscoped URLs cannot supply a resolver.
173
+ * @returns The project resolver, or undefined when no package scope exists or its helper cannot be written.
174
+ */
175
+ async function createResolve(baseUrl) {
176
+ const scope = resolveScope(baseUrl);
177
+ if (!scope) return;
178
+ return await (cache[scope] ??= _createResolve(scope));
179
+ }
180
+ //#endregion
118
181
  //#region lib/types/config/tree.js
119
182
  var __rewriteRelativeImportExtension = function(path, preserveJsx) {
120
183
  if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
@@ -122,6 +185,18 @@ var __rewriteRelativeImportExtension = function(path, preserveJsx) {
122
185
  });
123
186
  return path;
124
187
  };
188
+ /** The entry and the same-tree members of its group, recursively. */
189
+ function members(entry) {
190
+ const { tree } = entry.parent;
191
+ const result = [entry];
192
+ const group = entry.subgroup;
193
+ if (group?.tree !== tree) return result;
194
+ for (const options of group.data) {
195
+ const member = tree.store[options.id];
196
+ if (member?.parent === group) result.push(...members(member));
197
+ }
198
+ return result;
199
+ }
125
200
  /** Mutable tree of loader entries. Persistence is supplied by subclasses. */
126
201
  var EntryTree = class EntryTree {
127
202
  static sep = ":";
@@ -158,6 +233,13 @@ var EntryTree = class EntryTree {
158
233
  await Promise.allSettled(tasks);
159
234
  }
160
235
  }
236
+ /**
237
+ * Assign a random tree-local id when `options.id` is absent. Explicit ids
238
+ * may contain `EntryTree.sep`; `resolve()` and `resolveGroup()` cannot
239
+ * address such entries by nested path.
240
+ * @param options - Entry options; a generated id is written to `options.id`.
241
+ * @returns The existing or generated id.
242
+ */
161
243
  ensureId(options) {
162
244
  if (!options.id) do
163
245
  options.id = Math.random().toString(16).slice(2, 10);
@@ -186,29 +268,71 @@ var EntryTree = class EntryTree {
186
268
  /** Create an entry in the root group or a nested group. */
187
269
  async create(options, parent = null, position = Infinity) {
188
270
  const group = this.resolveGroup(parent);
271
+ const id = group.tree.ensureId(options);
189
272
  group.data.splice(position, 0, options);
190
- group.tree.write();
273
+ group.tree.commit({
274
+ id,
275
+ group,
276
+ options
277
+ });
191
278
  return group.create(options);
192
279
  }
193
280
  /** Stop and remove an entry from its parent group. */
194
281
  remove(id) {
195
282
  const entry = this.resolve(id);
196
- entry.parent.remove(id);
197
- entry.parent.tree.write();
283
+ const group = entry.parent;
284
+ const legacy = entry.options;
285
+ group.remove(legacy.id);
286
+ group.tree.commit({
287
+ id: legacy.id,
288
+ group,
289
+ legacy
290
+ });
198
291
  }
199
292
  /** Update an entry and optionally move it to another group. */
200
293
  async update(id, options, parent, position) {
201
294
  const entry = this.resolve(id);
202
295
  const source = entry.parent;
296
+ const legacy = { ...entry.options };
203
297
  if (parent !== void 0) {
204
298
  const target = this.resolveGroup(parent);
299
+ const moved = target.tree === source.tree ? [] : members(entry);
300
+ for (const member of moved) {
301
+ const { id } = member.options;
302
+ if (target.tree.store[id]) throw new Error(`entry ${id} already exists in the target tree`);
303
+ }
205
304
  source.unlink(entry.options);
206
305
  target.data.splice(position ?? Infinity, 0, entry.options);
207
- target.tree.write();
208
306
  entry.parent = target;
307
+ for (const member of moved) {
308
+ delete source.tree.store[member.options.id];
309
+ target.tree.store[member.options.id] = member;
310
+ if (member.subgroup?.tree === source.tree) member.subgroup.tree = target.tree;
311
+ }
209
312
  }
210
- source.tree.write();
211
- return entry.update(options, false, true);
313
+ const task = entry.update(options, false, true);
314
+ if (entry.parent.tree !== source.tree) {
315
+ source.tree.commit({
316
+ id: legacy.id,
317
+ group: source,
318
+ legacy
319
+ });
320
+ entry.parent.tree.commit({
321
+ id: legacy.id,
322
+ group: entry.parent,
323
+ options: entry.options
324
+ });
325
+ } else {
326
+ const from = entry.parent === source ? void 0 : source;
327
+ entry.parent.tree.commit({
328
+ id: legacy.id,
329
+ group: entry.parent,
330
+ from,
331
+ options: entry.options,
332
+ legacy
333
+ });
334
+ }
335
+ return task;
212
336
  }
213
337
  /** Import a plugin module from a specifier or `cordis:` builtin. */
214
338
  import(name, getOuterStack) {
@@ -220,10 +344,13 @@ var EntryTree = class EntryTree {
220
344
  /* @vite-ignore */
221
345
  new URL(name, this.ctx.baseUrl).href
222
346
  ));
223
- else return await import(__rewriteRelativeImportExtension(
224
- /* @vite-ignore */
225
- name
226
- ));
347
+ else {
348
+ const resolve = await createResolve(this.ctx.baseUrl);
349
+ return await import(__rewriteRelativeImportExtension(
350
+ /* @vite-ignore */
351
+ resolve ? resolve(name) : name
352
+ ));
353
+ }
227
354
  }, getOuterStack);
228
355
  }
229
356
  };
@@ -337,7 +464,7 @@ var Entry = class Entry {
337
464
  if (this.options.group) return false;
338
465
  let entry = this;
339
466
  do {
340
- if (this.disabledOf(entry.options)) return true;
467
+ if (this._resolveDisabled(entry.options)) return true;
341
468
  entry = entry.parent.ctx.fiber.entry;
342
469
  } while (entry);
343
470
  return false;
@@ -346,16 +473,20 @@ var Entry = class Entry {
346
473
  * Effective disabled state: a `!!js` expression evaluates against the loader
347
474
  * context. The raw node stays in the options, so write-back keeps the form.
348
475
  */
349
- disabledOf(options) {
476
+ _resolveDisabled(options) {
350
477
  return isJsExpr(options.disabled) ? Boolean(this.evaluate(options.disabled.__jsExpr)) : Boolean(options.disabled);
351
478
  }
352
479
  evaluate(expr) {
353
480
  return evaluate(this.ctx, expr);
354
481
  }
355
- _patchContext(diff) {
356
- this.context.waterfall("loader/patch-context", this, () => {
482
+ async _patchContext(diff) {
483
+ await this.context.waterfall("loader/patch-context", this, async () => {
357
484
  Object.setPrototypeOf(this.ctx, this.parent.ctx);
358
- if (this.fiber?.uid && (diff.includes("config") || this.options.group)) this.fiber.update(this.options.config, true);
485
+ if (this.fiber?.uid && (diff.includes("config") || this.options.group)) {
486
+ const fiber = this.fiber.ctx.fiber;
487
+ for (const name of Object.keys(fiber.inject)) fiber._checkImpl(name);
488
+ await fiber.update(this.options.config, true);
489
+ }
359
490
  });
360
491
  }
361
492
  async refresh() {
@@ -371,7 +502,7 @@ var Entry = class Entry {
371
502
  else this.options[key] = value;
372
503
  sortKeys(this.options);
373
504
  if (this.disabled) {
374
- this.fiber?.dispose();
505
+ await this.fiber?.dispose();
375
506
  return;
376
507
  }
377
508
  if (this.fiber?.uid) {
@@ -380,11 +511,11 @@ var Entry = class Entry {
380
511
  ...legacy
381
512
  }).filter((key) => !deepEqual(this.options[key], legacy[key], key === "config"));
382
513
  const volatileOnly = changes.length === 1 && changes[0] === "config" && this.fiber.state === 2 && Object.getPrototypeOf(this.ctx) === this.parent.ctx && equalExceptVolatile(legacy.config, this.options.config, this.fiber.runtime?.Config);
383
- if (volatileOnly) this.fiber._config = this.options.config;
514
+ if (volatileOnly) this.fiber.rawConfig = this.options.config;
384
515
  const pending = volatileOnly && this._commitVolatile() ? [] : changes;
385
516
  if (!pending.length && !force) return;
386
517
  this.context.emit("loader/partial-dispose", this, legacy, true);
387
- this._patchContext(pending);
518
+ await this._patchContext(pending);
388
519
  } else await this.init();
389
520
  }
390
521
  /**
@@ -393,19 +524,19 @@ var Entry = class Entry {
393
524
  * @returns `false` when an ordinary effective value changed, so the caller applies the ordinary update lifecycle.
394
525
  */
395
526
  _commitVolatile() {
396
- const fiber = this.fiber;
397
- const refs = volatileEntries(fiber.config);
527
+ const fiber = this.fiber.ctx.fiber;
528
+ const refs = volatileEntries(fiber.effectiveConfig);
398
529
  if (!refs.length) return true;
399
530
  const raw = this.options.config;
400
531
  let candidate;
401
532
  try {
402
- candidate = resolveConfig(fiber.runtime, fiber.ctx.waterfall(fiber, "internal/config", raw, () => raw));
533
+ candidate = fiber.resolveConfig(raw);
403
534
  } catch (error) {
404
535
  this.ctx.logger.warn("volatile config update failed for %C", this.options.id);
405
536
  this.ctx.logger.warn(error);
406
537
  return true;
407
538
  }
408
- if (!deepEqual(fiber.config, candidate, true)) {
539
+ if (!deepEqual(fiber.effectiveConfig, candidate, true)) {
409
540
  this.ctx.logger.debug("ordinary config values of %C changed with its volatile values; applying the ordinary update", this.options.id);
410
541
  return false;
411
542
  }
@@ -441,11 +572,10 @@ var Entry = class Entry {
441
572
  } finally {
442
573
  this._initTask = void 0;
443
574
  }
444
- const notify = () => {
575
+ this.fiber?.await().catch(() => {}).finally(() => {
445
576
  if (this.loader.getTasks().length) return;
446
577
  this.ctx.reflect.notify(["loader"]);
447
- };
448
- this.fiber?.await().then(notify, notify);
578
+ });
449
579
  }
450
580
  async _init() {
451
581
  let moduleNamespace;
@@ -454,13 +584,11 @@ var Entry = class Entry {
454
584
  } catch (error) {
455
585
  this.ctx.logger.error(error);
456
586
  return;
457
- } finally {
458
- this._initTask = void 0;
459
587
  }
460
588
  const plugin = this.loader.unwrapExports(moduleNamespace);
461
- this._patchContext([]);
589
+ await this._patchContext([]);
462
590
  this.loader.showLog(this, "apply");
463
- this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack).ctx.fiber;
591
+ this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack);
464
592
  this.moduleNamespace = moduleNamespace;
465
593
  }
466
594
  };
@@ -523,7 +651,7 @@ function isolate(ctx) {
523
651
  entry.ctx[Context.intercept] = Object.create(entry.ctx[Context.intercept]);
524
652
  entry.ctx[Context.isolate] = Object.create(entry.ctx[Context.isolate]);
525
653
  });
526
- ctx.on("loader/patch-context", (entry, next) => {
654
+ ctx.on("loader/patch-context", async (entry, next) => {
527
655
  const newMap = Object.create(entry.parent.ctx[Context.isolate]);
528
656
  for (const name of Object.keys(entry.options.isolate ?? {})) newMap[name] = access(entry, name, true);
529
657
  const diff = Object.create(null);
@@ -538,7 +666,8 @@ function isolate(ctx) {
538
666
  for (const symbol of [oldMap[name], newMap[name]]) {
539
667
  const impl = symbol && entry.ctx.reflect.store[symbol];
540
668
  if (!impl) continue;
541
- if (!impl.fiber) {
669
+ const fiber = impl.ctx.fiber;
670
+ if (!fiber) {
542
671
  entry.ctx.logger.warn(/* @__PURE__ */ new Error(`expected service ${name} to be implemented`));
543
672
  continue;
544
673
  }
@@ -546,19 +675,23 @@ function isolate(ctx) {
546
675
  oldMap[name],
547
676
  newMap[name],
548
677
  entry.ctx[delim],
549
- impl.fiber.ctx[delim]
678
+ fiber.ctx[delim]
550
679
  ];
551
- if (entry.ctx[delim] !== impl.fiber.ctx[delim]) break;
680
+ if (entry.ctx[delim] !== fiber.ctx[delim]) break;
552
681
  }
553
682
  }
554
683
  Object.setPrototypeOf(entry.ctx[Context.isolate], entry.parent.ctx[Context.isolate]);
555
684
  Object.setPrototypeOf(entry.ctx[Context.intercept], entry.parent.ctx[Context.intercept]);
556
685
  swap(entry.ctx[Context.isolate], newMap);
557
686
  swap(entry.ctx[Context.intercept], entry.options.intercept);
558
- next();
559
- for (const [symbol1, symbol2, flag1, flag2] of Object.values(diff)) if (flag1 === flag2 && entry.ctx.reflect.store[symbol1] && !entry.ctx.reflect.store[symbol2]) {
560
- entry.ctx.reflect.store[symbol2] = entry.ctx.reflect.store[symbol1];
561
- delete entry.ctx.reflect.store[symbol1];
687
+ await next();
688
+ for (const [symbol1, symbol2, flag1, flag2] of Object.values(diff)) {
689
+ const impl = entry.ctx.reflect.store[symbol1];
690
+ if (flag1 === flag2 && impl && !entry.ctx.reflect.store[symbol2]) {
691
+ entry.ctx.reflect.store[symbol2] = impl;
692
+ delete entry.ctx.reflect.store[symbol1];
693
+ impl.isolate = symbol2;
694
+ }
562
695
  }
563
696
  ctx.reflect.notify(Object.keys(diff), (ctx, name) => {
564
697
  const [symbol1, symbol2, flag1, flag2] = diff[name];
@@ -585,7 +718,7 @@ function isolate(ctx) {
585
718
  /**
586
719
  * Service that owns a loader entry tree and imports configured plugins.
587
720
  *
588
- * Subclasses provide persistence by implementing `write()` on `EntryTree`.
721
+ * Subclasses provide persistence by implementing `commit(change)` on `EntryTree`.
589
722
  */
590
723
  var Loader = class extends EntryTree {
591
724
  config;
@@ -604,23 +737,27 @@ var Loader = class extends EntryTree {
604
737
  noShadow: true
605
738
  });
606
739
  ctx.reflect.provide("loader", this, this[Service.check]);
607
- ctx.on("internal/config", function(_config, next) {
740
+ ctx.on("internal/config", (fiber, next) => {
608
741
  const config = next();
609
- if (!this.entry || this.parent.fiber?.entry === this.entry) return config;
610
- if ((this.runtime?.callback)?.[EntryGroup.key]) return config;
611
- return interpolate(this.ctx, config);
612
- }, { global: true });
613
- ctx.on("internal/update", function(config, noSave, next) {
614
- if (!this.entry || noSave || this.parent.fiber?.entry === this.entry) return next();
615
- const unparse = this.runtime?.Config?.["simplify"];
616
- this.entry.options.config = unparse ? unparse.call(this.runtime.Config, config) : config;
617
- this.entry.parent.tree.write();
618
- return next();
619
- }, {
620
- global: true,
621
- prepend: true
742
+ if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return config;
743
+ if (fiber.runtime?.callback[EntryGroup.key]) return config;
744
+ return interpolate(fiber.ctx, config);
622
745
  });
623
- ctx.on("internal/update", function(config, _, next) {
746
+ ctx.on("internal/commit", (fiber, config) => {
747
+ if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return;
748
+ const schema = fiber.runtime?.Config;
749
+ const unparse = schema?.["simplify"];
750
+ const { entry } = fiber;
751
+ const legacy = { ...entry.options };
752
+ entry.options.config = unparse ? unparse.call(schema, config) : config;
753
+ entry.parent.tree.commit({
754
+ id: entry.options.id,
755
+ group: entry.parent,
756
+ options: entry.options,
757
+ legacy
758
+ });
759
+ });
760
+ ctx.on("internal/update", function(config, next) {
624
761
  if (!this.entry || this.parent.fiber?.entry === this.entry) return next();
625
762
  self.showLog(this.entry, "reload");
626
763
  return next();
@@ -634,16 +771,24 @@ var Loader = class extends EntryTree {
634
771
  if (!fiber.entry) return;
635
772
  if (fiber.parent.fiber?.entry === fiber.entry) return;
636
773
  if (!ctx.registry.has(fiber.runtime.callback)) return;
637
- const treeOwner = fiber.entry.parent.tree.ctx.fiber;
638
- if (!treeOwner.uid || treeOwner.state === 5) return;
639
- this.showLog(fiber.entry, "unload");
640
- if (fiber.entry.disabled) return;
641
- fiber.entry.options.disabled = true;
642
- fiber.entry.parent.tree.write();
774
+ if (!fiber.entry.parent.tree.ctx.fiber.uid) return;
775
+ const { entry } = fiber;
776
+ this.showLog(entry, "unload");
777
+ if (fiber.parent.fiber.state === 5) return;
778
+ if (entry.parent.tree.store[entry.options.id] !== entry) return;
779
+ if (entry.disabled) return;
780
+ const legacy = { ...entry.options };
781
+ entry.options.disabled = true;
782
+ entry.parent.tree.commit({
783
+ id: entry.options.id,
784
+ group: entry.parent,
785
+ options: entry.options,
786
+ legacy
787
+ });
643
788
  });
644
789
  ctx.plugin(isolate);
645
790
  }
646
- write() {}
791
+ commit(_change) {}
647
792
  [Service.check]() {
648
793
  if (Service.prototype[Service.resolveConfig].call(this).await && this.getTasks().length) return false;
649
794
  return true;
@@ -39,7 +39,7 @@ export declare class Entry {
39
39
  * Effective disabled state: a `!!js` expression evaluates against the loader
40
40
  * context. The raw node stays in the options, so write-back keeps the form.
41
41
  */
42
- private disabledOf;
42
+ private _resolveDisabled;
43
43
  evaluate(expr: string): any;
44
44
  private _patchContext;
45
45
  refresh(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"entry.d.ts","sourceRoot":"","sources":["../../../src/config/entry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAc,MAAM,EAAiB,MAAM,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ts","sourceRoot":"","sources":["../../../src/config/isolate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAC7C,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAElC,OAAO,QAAQ,YAAY,CAAC;IAC1B,UAAU,YAAY;QACpB,SAAS,CAAC,EAAE,IAAI,GAAG,IAAI,CAAA;QACvB,OAAO,CAAC,EAAE,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,GAAG,IAAI,CAAA;KACrC;IAED,UAAU,KAAK;QACb,KAAK,EAAE,UAAU,CAAA;KAClB;CACF;AAWD,8EAA8E;AAC9E,8BAAsB,KAAK;IACzB,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,CAAsB;IAEnD,QAAQ,KAAK,MAAM,IAAI,MAAM,CAAA;IAE7B,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,UAAQ;IAQlC,MAAM,CAAC,GAAG,EAAE,MAAM;IAIlB,IAAI,IAAI,WAEP;CACF;AAED,mCAAmC;AACnC,qBAAa,UAAW,SAAQ,KAAK;IACvB,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,KAAK;IAIhC,IAAI,MAAM,WAET;CACF;AAED,uEAAuE;AACvE,qBAAa,WAAY,SAAQ,KAAK;IACjB,KAAK,EAAE,MAAM;gBAAb,KAAK,EAAE,MAAM;IAIhC,IAAI,MAAM,WAET;CACF;AAED,+EAA+E;AAC/E,MAAM,CAAC,OAAO,UAAU,OAAO,CAAC,GAAG,EAAE,OAAO,QAyG3C"}
@@ -2,6 +2,28 @@ import { Context } from '@deepseek-ai/cordis';
2
2
  import { type Dict } from '@deepseek-ai/cosmokit';
3
3
  import { Entry, type EntryOptions } from './entry.ts';
4
4
  import { EntryGroup } from './group.ts';
5
+ /**
6
+ * One tree-side mutation, reported to `EntryTree.commit()` synchronously after
7
+ * it has been applied to `entry.options` / `group.data`.
8
+ *
9
+ * - `options` absent: the entry was removed from `group`.
10
+ * - `legacy` absent: the entry was created in `group`.
11
+ * - both present: the entry was updated and now lives in `group`; `from` is
12
+ * the group it left if the update moved it within the same tree. A move to
13
+ * another tree reports a removal to the source tree and a creation to the
14
+ * destination tree.
15
+ *
16
+ * `id` is local to the receiving tree; `Entry.id` prefixes it with the parent
17
+ * tree's path. Only `EntryTree` mutation methods and explicit Fiber saves
18
+ * report changes; file-driven `EntryGroup` reconciliation does not.
19
+ */
20
+ export interface EntryChange {
21
+ id: string;
22
+ group: EntryGroup;
23
+ from?: EntryGroup;
24
+ options?: EntryOptions;
25
+ legacy?: EntryOptions;
26
+ }
5
27
  /** Mutable tree of loader entries. Persistence is supplied by subclasses. */
6
28
  export declare abstract class EntryTree {
7
29
  static readonly sep = ":";
@@ -17,6 +39,13 @@ export declare abstract class EntryTree {
17
39
  getTasks(): Promise<void>[];
18
40
  /** Wait until this tree has no pending import or lifecycle tasks. */
19
41
  await(): Promise<void>;
42
+ /**
43
+ * Assign a random tree-local id when `options.id` is absent. Explicit ids
44
+ * may contain `EntryTree.sep`; `resolve()` and `resolveGroup()` cannot
45
+ * address such entries by nested path.
46
+ * @param options - Entry options; a generated id is written to `options.id`.
47
+ * @returns The existing or generated id.
48
+ */
20
49
  ensureId(options: Partial<EntryOptions>): string;
21
50
  /** Resolve an entry by id, including nested ids separated by `EntryTree.sep`. */
22
51
  resolve(id: string): Entry;
@@ -29,7 +58,7 @@ export declare abstract class EntryTree {
29
58
  update(id: string, options: Omit<EntryOptions, 'id' | 'name'>, parent?: string | null, position?: number): Promise<void>;
30
59
  /** Import a plugin module from a specifier or `cordis:` builtin. */
31
60
  import(name: string, getOuterStack?: () => string[]): any;
32
- /** Persist current tree state. In-memory trees may implement this as a no-op. */
33
- abstract write(): void;
61
+ /** Report an applied mutation synchronously. In-memory trees may use a no-op. */
62
+ abstract commit(change: EntryChange): void;
34
63
  }
35
64
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C,YAAY,CAAC;IASvC,iFAAiF;IACjF,OAAO,CAAC,EAAE,EAAE,MAAM;IAalB,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI;IAO9B,2DAA2D;IACrD,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,EAAE,MAAM,GAAE,MAAM,GAAG,IAAW,EAAE,QAAQ,SAAW;IAQjG,sDAAsD;IACtD,MAAM,CAAC,EAAE,EAAE,MAAM;IAQjB,+DAA+D;IACzD,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,GAAG,MAAM,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,CAAC,EAAE,MAAM;IAqC9G,oEAAoE;IACpE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,MAAM,EAAE;IAqBnD,iFAAiF;IACjF,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;CAC3C"}
@@ -1,8 +1,8 @@
1
- import { Context, Service, type Fiber } from '@deepseek-ai/cordis';
2
- import { type Dict } from '@deepseek-ai/cosmokit';
1
+ import { Context, Service } from '@deepseek-ai/cordis';
2
+ import { type Awaitable, type Dict } from '@deepseek-ai/cosmokit';
3
3
  import { ModuleLoader } from './internal.ts';
4
4
  import { Entry, type EntryOptions } from './config/entry.ts';
5
- import { EntryTree } from './config/tree.ts';
5
+ import { EntryTree, type EntryChange } from './config/tree.ts';
6
6
  /** Re-export entry node APIs. */
7
7
  export * from './config/entry.ts';
8
8
  /** Re-export nested entry group APIs. */
@@ -33,7 +33,7 @@ declare module '@deepseek-ai/cordis' {
33
33
  * @param next - continue context refresh and Loader's config update.
34
34
  * @mode waterfall
35
35
  */
36
- 'loader/patch-context'(entry: Entry, next: () => void): void;
36
+ 'loader/patch-context'(entry: Entry, next: () => Awaitable<void>): Awaitable<void>;
37
37
  }
38
38
  interface Context {
39
39
  loader: Loader;
@@ -61,7 +61,7 @@ export declare namespace Loader {
61
61
  /**
62
62
  * Service that owns a loader entry tree and imports configured plugins.
63
63
  *
64
- * Subclasses provide persistence by implementing `write()` on `EntryTree`.
64
+ * Subclasses provide persistence by implementing `commit(change)` on `EntryTree`.
65
65
  */
66
66
  export declare class Loader extends EntryTree {
67
67
  config: Loader.Config;
@@ -71,11 +71,11 @@ export declare class Loader extends EntryTree {
71
71
  internal: ModuleLoader | undefined;
72
72
  builtins: Dict<any>;
73
73
  constructor(ctx: Context, config?: Loader.Config);
74
- write(): void;
74
+ commit(_change: EntryChange): void;
75
75
  [Service.check](): boolean;
76
76
  showLog(entry: Entry, type: string): void;
77
77
  /** Return the loader entry id that owns `fiber`, if any. */
78
- locate(fiber?: Fiber): string | undefined;
78
+ locate(fiber?: import("@deepseek-ai/cordis").Fiber): string | undefined;
79
79
  /** Hook for hosts that can restart the process on full-reload requests. */
80
80
  exit(): void;
81
81
  /** Normalize ESM/CJS/default export shapes before applying a plugin. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAsB,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,qBAAqB,CAAA;AACtF,OAAO,EAA8B,KAAK,IAAI,EAAE,MAAM,uBAAuB,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5C,OAAO,EAAE,KAAK,EAAE,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAG5D,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAG5C,iCAAiC;AACjC,cAAc,mBAAmB,CAAA;AACjC,yCAAyC;AACzC,cAAc,mBAAmB,CAAA;AACjC,2CAA2C;AAC3C,cAAc,qBAAqB,CAAA;AACnC,6CAA6C;AAC7C,cAAc,kBAAkB,CAAA;AAChC,kDAAkD;AAClD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AAE,IAAI,EAAE,MAAM;IAKlC,4DAA4D;IAC5D,MAAM,CAAC,KAAK,sCAAiB;IAS7B,2EAA2E;IAC3E,IAAI;IAGJ,wEAAwE;IACxE,aAAa,CAAC,OAAO,EAAE,GAAG;CAQ3B;AAED,eAAe,MAAM,CAAA"}
@@ -0,0 +1,9 @@
1
+ /** Resolve a specifier to its URL in one configuration project. */
2
+ export type Resolve = (specifier: string) => string;
3
+ /**
4
+ * Create or reuse a native ESM resolver anchored in the config project's package scope.
5
+ * @param baseUrl Config file URL; absent, non-file or unscoped URLs cannot supply a resolver.
6
+ * @returns The project resolver, or undefined when no package scope exists or its helper cannot be written.
7
+ */
8
+ export declare function createResolve(baseUrl: string | undefined): Promise<Resolve | undefined>;
9
+ //# sourceMappingURL=resolve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/resolve.ts"],"names":[],"mappings":"AAMA,mEAAmE;AACnE,MAAM,MAAM,OAAO,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,CAAA;AA0DnD;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,gCAI9D"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deepseek-ai/cordis-plugin-loader",
3
3
  "description": "Plugin loader for cordis",
4
- "version": "1.0.6",
4
+ "version": "1.0.7-alpha.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -30,7 +30,7 @@
30
30
  "author": "Shigma <shigma10826@gmail.com>",
31
31
  "license": "MIT",
32
32
  "peerDependencies": {
33
- "@deepseek-ai/cordis": "~4.0.5",
33
+ "@deepseek-ai/cordis": "~4.0.6-alpha.2",
34
34
  "node-addon-require-builtin": "^0.1.9"
35
35
  },
36
36
  "peerDependenciesMeta": {
@@ -39,7 +39,7 @@
39
39
  }
40
40
  },
41
41
  "dependencies": {
42
- "@deepseek-ai/cosmokit": "~1.8.6",
43
- "@deepseek-ai/schemastery": "~3.18.5"
42
+ "@deepseek-ai/cosmokit": "~1.8.7-alpha.2",
43
+ "@deepseek-ai/schemastery": "~3.18.6-alpha.2"
44
44
  }
45
45
  }
@@ -1,4 +1,4 @@
1
- import { Context, Fiber, FiberState, Inject, resolveConfig } from '@deepseek-ai/cordis'
1
+ import { Context, Fiber, FiberState, Inject } from '@deepseek-ai/cordis'
2
2
  import { deepEqual, isNullable, updateVolatile, volatileEntries, type Volatile } from '@deepseek-ai/cosmokit'
3
3
  import { Loader } from '../index.ts'
4
4
  import { EntryGroup } from './group.ts'
@@ -78,7 +78,7 @@ export class Entry {
78
78
  if (this.options.group) return false
79
79
  let entry: Entry | undefined = this
80
80
  do {
81
- if (this.disabledOf(entry.options)) return true
81
+ if (this._resolveDisabled(entry.options)) return true
82
82
  entry = entry.parent.ctx.fiber.entry
83
83
  } while (entry)
84
84
  return false
@@ -88,7 +88,7 @@ export class Entry {
88
88
  * Effective disabled state: a `!!js` expression evaluates against the loader
89
89
  * context. The raw node stays in the options, so write-back keeps the form.
90
90
  */
91
- private disabledOf(options: EntryOptions): boolean {
91
+ private _resolveDisabled(options: EntryOptions): boolean {
92
92
  return isJsExpr(options.disabled)
93
93
  ? Boolean(this.evaluate(options.disabled.__jsExpr))
94
94
  : Boolean(options.disabled)
@@ -98,12 +98,15 @@ export class Entry {
98
98
  return evaluate(this.ctx, expr)
99
99
  }
100
100
 
101
- private _patchContext(diff: string[]) {
102
- this.context.waterfall('loader/patch-context', this, () => {
101
+ private async _patchContext(diff: string[]) {
102
+ await this.context.waterfall('loader/patch-context', this, async () => {
103
103
  Object.setPrototypeOf(this.ctx, this.parent.ctx)
104
104
 
105
105
  if (this.fiber?.uid && (diff.includes('config') || this.options.group)) {
106
- this.fiber.update(this.options.config, true)
106
+ // A simultaneous context/config edit must restart against the new dependencies.
107
+ const fiber = this.fiber.ctx.fiber
108
+ for (const name of Object.keys(fiber.inject)) fiber._checkImpl(name)
109
+ await fiber.update(this.options.config, true)
107
110
  }
108
111
  })
109
112
  }
@@ -134,7 +137,7 @@ export class Entry {
134
137
 
135
138
  // step 2: execute
136
139
  if (this.disabled) {
137
- this.fiber?.dispose()
140
+ await this.fiber?.dispose()
138
141
  return
139
142
  }
140
143
 
@@ -146,11 +149,11 @@ export class Entry {
146
149
  const volatileOnly = changes.length === 1 && changes[0] === 'config'
147
150
  && this.fiber.state === FiberState.ACTIVE && Object.getPrototypeOf(this.ctx) === this.parent.ctx
148
151
  && equalExceptVolatile(legacy.config, this.options.config, this.fiber.runtime?.Config)
149
- if (volatileOnly) this.fiber._config = this.options.config
152
+ if (volatileOnly) this.fiber.rawConfig = this.options.config
150
153
  const pending = volatileOnly && this._commitVolatile() ? [] : changes
151
154
  if (!pending.length && !force) return
152
155
  this.context.emit('loader/partial-dispose', this, legacy, true)
153
- this._patchContext(pending)
156
+ await this._patchContext(pending)
154
157
  } else {
155
158
  await this.init()
156
159
  }
@@ -162,19 +165,19 @@ export class Entry {
162
165
  * @returns `false` when an ordinary effective value changed, so the caller applies the ordinary update lifecycle.
163
166
  */
164
167
  private _commitVolatile(): boolean {
165
- const fiber = this.fiber!
166
- const refs = volatileEntries(fiber.config)
168
+ const fiber = this.fiber!.ctx.fiber
169
+ const refs = volatileEntries(fiber.effectiveConfig)
167
170
  if (!refs.length) return true
168
171
  const raw = this.options.config
169
172
  let candidate: unknown
170
173
  try {
171
- candidate = resolveConfig(fiber.runtime!, fiber.ctx.waterfall(fiber, 'internal/config', raw, () => raw))
174
+ candidate = fiber.resolveConfig(raw)
172
175
  } catch (error) {
173
176
  this.ctx.logger.warn('volatile config update failed for %C', this.options.id)
174
177
  this.ctx.logger.warn(error)
175
178
  return true
176
179
  }
177
- if (!deepEqual(fiber.config, candidate, true)) {
180
+ if (!deepEqual(fiber.effectiveConfig, candidate, true)) {
178
181
  this.ctx.logger.debug('ordinary config values of %C changed with its volatile values; applying the ordinary update', this.options.id)
179
182
  return false
180
183
  }
@@ -213,11 +216,10 @@ export class Entry {
213
216
  } finally {
214
217
  this._initTask = undefined
215
218
  }
216
- const notify = () => {
219
+ this.fiber?.await().catch(() => {}).finally(() => {
217
220
  if (this.loader.getTasks().length) return
218
221
  this.ctx.reflect.notify(['loader'])
219
- }
220
- this.fiber?.await().then(notify, notify)
222
+ })
221
223
  }
222
224
 
223
225
  private async _init() {
@@ -227,13 +229,11 @@ export class Entry {
227
229
  } catch (error) {
228
230
  this.ctx.logger.error(error)
229
231
  return
230
- } finally {
231
- this._initTask = undefined
232
232
  }
233
233
  const plugin = this.loader.unwrapExports(moduleNamespace)
234
- this._patchContext([])
234
+ await this._patchContext([])
235
235
  this.loader.showLog(this, 'apply')
236
- this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack).ctx.fiber
236
+ this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack)
237
237
  this.moduleNamespace = moduleNamespace
238
238
  }
239
239
  }
@@ -36,12 +36,13 @@ export class EntryGroup {
36
36
 
37
37
  remove(id: string, isDispose = false) {
38
38
  const entry = this.tree.store[id]
39
- if (!entry) return
39
+ if (!entry || entry.parent !== this) return
40
+ // Unregister before disposal so Loader can distinguish removal from self-disposal.
41
+ delete this.tree.store[id]
40
42
  entry.fiber?.dispose()
41
43
  if (!isDispose) {
42
44
  this.unlink(entry.options)
43
45
  }
44
- delete this.tree.store[id]
45
46
  this.context.emit('loader/partial-dispose', entry, entry.options, false)
46
47
  }
47
48
 
@@ -78,9 +79,7 @@ export class Group extends EntryGroup {
78
79
 
79
80
  constructor(public ctx: Context, public config: EntryOptions[]) {
80
81
  super(ctx, ctx.fiber.entry!.parent.tree)
81
- ctx.on('internal/update', (config) => {
82
- this.update(config)
83
- })
82
+ ctx.on('internal/update', config => this.update(config))
84
83
  }
85
84
 
86
85
  async* [Service.init]() {
@@ -93,7 +93,7 @@ export default function isolate(ctx: Context) {
93
93
  entry.ctx[Context.isolate] = Object.create(entry.ctx[Context.isolate])
94
94
  })
95
95
 
96
- ctx.on('loader/patch-context', (entry, next) => {
96
+ ctx.on('loader/patch-context', async (entry, next) => {
97
97
  // step 1: generate new isolate map
98
98
  const newMap: Dict<symbol> = Object.create(entry.parent.ctx[Context.isolate])
99
99
  for (const name of Object.keys(entry.options.isolate ?? {})) {
@@ -110,12 +110,13 @@ export default function isolate(ctx: Context) {
110
110
  for (const symbol of [oldMap[name], newMap[name]]) {
111
111
  const impl = symbol && entry.ctx.reflect.store[symbol]
112
112
  if (!impl) continue
113
- if (!impl.fiber) {
113
+ const fiber = impl.ctx.fiber
114
+ if (!fiber) {
114
115
  entry.ctx.logger.warn(new Error(`expected service ${name} to be implemented`))
115
116
  continue
116
117
  }
117
- diff[name] = [oldMap[name], newMap[name], entry.ctx[delim], impl.fiber.ctx[delim]]
118
- if (entry.ctx[delim] !== impl.fiber.ctx[delim]) break
118
+ diff[name] = [oldMap[name], newMap[name], entry.ctx[delim], fiber.ctx[delim]]
119
+ if (entry.ctx[delim] !== fiber.ctx[delim]) break
119
120
  }
120
121
  }
121
122
 
@@ -126,13 +127,15 @@ export default function isolate(ctx: Context) {
126
127
  swap(entry.ctx[Context.intercept], entry.options.intercept)
127
128
 
128
129
  // step 4: reload fiber
129
- next()
130
+ await next()
130
131
 
131
132
  // step 5: replace service impl
132
133
  for (const [symbol1, symbol2, flag1, flag2] of Object.values(diff)) {
133
- if (flag1 === flag2 && entry.ctx.reflect.store[symbol1] && !entry.ctx.reflect.store[symbol2]) {
134
- entry.ctx.reflect.store[symbol2] = entry.ctx.reflect.store[symbol1]
134
+ const impl = entry.ctx.reflect.store[symbol1]
135
+ if (flag1 === flag2 && impl && !entry.ctx.reflect.store[symbol2]) {
136
+ entry.ctx.reflect.store[symbol2] = impl
135
137
  delete entry.ctx.reflect.store[symbol1]
138
+ impl.isolate = symbol2
136
139
  }
137
140
  }
138
141
 
@@ -2,6 +2,43 @@ import { composeError, Context } from '@deepseek-ai/cordis'
2
2
  import { isNonNullable, type Dict } from '@deepseek-ai/cosmokit'
3
3
  import { Entry, type EntryOptions } from './entry.ts'
4
4
  import { EntryGroup } from './group.ts'
5
+ import { createResolve } from '../resolve.ts'
6
+
7
+ /**
8
+ * One tree-side mutation, reported to `EntryTree.commit()` synchronously after
9
+ * it has been applied to `entry.options` / `group.data`.
10
+ *
11
+ * - `options` absent: the entry was removed from `group`.
12
+ * - `legacy` absent: the entry was created in `group`.
13
+ * - both present: the entry was updated and now lives in `group`; `from` is
14
+ * the group it left if the update moved it within the same tree. A move to
15
+ * another tree reports a removal to the source tree and a creation to the
16
+ * destination tree.
17
+ *
18
+ * `id` is local to the receiving tree; `Entry.id` prefixes it with the parent
19
+ * tree's path. Only `EntryTree` mutation methods and explicit Fiber saves
20
+ * report changes; file-driven `EntryGroup` reconciliation does not.
21
+ */
22
+ export interface EntryChange {
23
+ id: string
24
+ group: EntryGroup
25
+ from?: EntryGroup
26
+ options?: EntryOptions
27
+ legacy?: EntryOptions
28
+ }
29
+
30
+ /** The entry and the same-tree members of its group, recursively. */
31
+ function members(entry: Entry): Entry[] {
32
+ const { tree } = entry.parent
33
+ const result = [entry]
34
+ const group = entry.subgroup
35
+ if (group?.tree !== tree) return result
36
+ for (const options of group.data) {
37
+ const member = tree.store[options.id]
38
+ if (member?.parent === group) result.push(...members(member))
39
+ }
40
+ return result
41
+ }
5
42
 
6
43
  /** Mutable tree of loader entries. Persistence is supplied by subclasses. */
7
44
  export abstract class EntryTree {
@@ -48,6 +85,13 @@ export abstract class EntryTree {
48
85
  }
49
86
  }
50
87
 
88
+ /**
89
+ * Assign a random tree-local id when `options.id` is absent. Explicit ids
90
+ * may contain `EntryTree.sep`; `resolve()` and `resolveGroup()` cannot
91
+ * address such entries by nested path.
92
+ * @param options - Entry options; a generated id is written to `options.id`.
93
+ * @returns The existing or generated id.
94
+ */
51
95
  ensureId(options: Partial<EntryOptions>) {
52
96
  if (!options.id) {
53
97
  do {
@@ -81,31 +125,57 @@ export abstract class EntryTree {
81
125
  /** Create an entry in the root group or a nested group. */
82
126
  async create(options: Omit<EntryOptions, 'id'>, parent: string | null = null, position = Infinity) {
83
127
  const group = this.resolveGroup(parent)
128
+ const id = group.tree.ensureId(options)
84
129
  group.data.splice(position, 0, options as EntryOptions)
85
- group.tree.write()
130
+ group.tree.commit({ id, group, options: options as EntryOptions })
86
131
  return group.create(options)
87
132
  }
88
133
 
89
134
  /** Stop and remove an entry from its parent group. */
90
135
  remove(id: string) {
91
136
  const entry = this.resolve(id)
92
- entry.parent.remove(id)
93
- entry.parent.tree.write()
137
+ const group = entry.parent
138
+ const legacy = entry.options
139
+ group.remove(legacy.id)
140
+ group.tree.commit({ id: legacy.id, group, legacy })
94
141
  }
95
142
 
96
143
  /** Update an entry and optionally move it to another group. */
97
144
  async update(id: string, options: Omit<EntryOptions, 'id' | 'name'>, parent?: string | null, position?: number) {
98
145
  const entry = this.resolve(id)
99
146
  const source = entry.parent
147
+ const legacy = { ...entry.options }
100
148
  if (parent !== undefined) {
101
149
  const target = this.resolveGroup(parent)
150
+ const moved = target.tree === source.tree ? [] : members(entry)
151
+ for (const member of moved) {
152
+ const { id } = member.options
153
+ if (target.tree.store[id]) throw new Error(`entry ${id} already exists in the target tree`)
154
+ }
102
155
  source.unlink(entry.options)
103
156
  target.data.splice(position ?? Infinity, 0, entry.options)
104
- target.tree.write()
105
157
  entry.parent = target
158
+ // The target tree owns the moved entries from now on, so that it adopts
159
+ // them instead of creating new ones when it reconciles its source.
160
+ for (const member of moved) {
161
+ delete source.tree.store[member.options.id]
162
+ target.tree.store[member.options.id] = member
163
+ if (member.subgroup?.tree === source.tree) member.subgroup.tree = target.tree
164
+ }
165
+ }
166
+ // `Entry.update` assigns the new options before its first `await`, so the
167
+ // change is fully visible to `commit()` once the call returns.
168
+ const task = entry.update(options, false, true)
169
+ if (entry.parent.tree !== source.tree) {
170
+ // a move across trees removes the entry from the source tree and
171
+ // creates it in the target tree
172
+ source.tree.commit({ id: legacy.id, group: source, legacy })
173
+ entry.parent.tree.commit({ id: legacy.id, group: entry.parent, options: entry.options })
174
+ } else {
175
+ const from = entry.parent === source ? undefined : source
176
+ entry.parent.tree.commit({ id: legacy.id, group: entry.parent, from, options: entry.options, legacy })
106
177
  }
107
- source.tree.write()
108
- return entry.update(options, false, true)
178
+ return task
109
179
  }
110
180
 
111
181
  /** Import a plugin module from a specifier or `cordis:` builtin. */
@@ -123,11 +193,13 @@ export abstract class EntryTree {
123
193
  } else if (name.startsWith('.')) {
124
194
  return await import(/* @vite-ignore */new URL(name, this.ctx.baseUrl).href)
125
195
  } else {
126
- return await import(/* @vite-ignore */name)
196
+ const resolve = await createResolve(this.ctx.baseUrl)
197
+ const url = resolve ? resolve(name) : name
198
+ return await import(/* @vite-ignore */ url)
127
199
  }
128
200
  }, getOuterStack)
129
201
  }
130
202
 
131
- /** Persist current tree state. In-memory trees may implement this as a no-op. */
132
- abstract write(): void
203
+ /** Report an applied mutation synchronously. In-memory trees may use a no-op. */
204
+ abstract commit(change: EntryChange): void
133
205
  }
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { Context, FiberState, Inject, Service, type Fiber } from '@deepseek-ai/cordis'
2
- import { defineProperty, isNullable, type Dict } from '@deepseek-ai/cosmokit'
1
+ import { Context, FiberState, Inject, Service } from '@deepseek-ai/cordis'
2
+ import { defineProperty, isNullable, type Awaitable, type Dict } from '@deepseek-ai/cosmokit'
3
3
  import { ModuleLoader } from './internal.ts'
4
4
  import { Entry, type EntryOptions } from './config/entry.ts'
5
5
  import { EntryGroup } from './config/group.ts'
6
6
  import isolate from './config/isolate.ts'
7
- import { EntryTree } from './config/tree.ts'
7
+ import { EntryTree, type EntryChange } from './config/tree.ts'
8
8
  import { interpolate } from './config/utils.ts'
9
9
 
10
10
  /** Re-export entry node APIs. */
@@ -38,7 +38,7 @@ declare module '@deepseek-ai/cordis' {
38
38
  * @param next - continue context refresh and Loader's config update.
39
39
  * @mode waterfall
40
40
  */
41
- 'loader/patch-context'(entry: Entry, next: () => void): void
41
+ 'loader/patch-context'(entry: Entry, next: () => Awaitable<void>): Awaitable<void>
42
42
  }
43
43
 
44
44
  interface Context {
@@ -72,7 +72,7 @@ export namespace Loader {
72
72
  /**
73
73
  * Service that owns a loader entry tree and imports configured plugins.
74
74
  *
75
- * Subclasses provide persistence by implementing `write()` on `EntryTree`.
75
+ * Subclasses provide persistence by implementing `commit(change)` on `EntryTree`.
76
76
  */
77
77
  export class Loader extends EntryTree {
78
78
  declare [Service.config]: Loader.Intercept
@@ -101,26 +101,25 @@ export class Loader extends EntryTree {
101
101
 
102
102
  ctx.reflect.provide('loader', this, this[Service.check])
103
103
 
104
- ctx.on('internal/config', function (this: Fiber, _config, next) {
104
+ ctx.on('internal/config', (fiber, next) => {
105
105
  const config = next()
106
- if (!this.entry || this.parent.fiber?.entry === this.entry) return config
107
- // Tree carriers (Group, Include) keep their configs literal: their
108
- // entry and patch lists hold other rows' configs, whose `!!js`
109
- // expressions belong to those rows' own fibers.
110
- const plugin = this.runtime?.callback as Record<PropertyKey, unknown> | undefined
111
- if (plugin?.[EntryGroup.key]) return config
112
- return interpolate(this.ctx, config)
113
- }, { global: true })
106
+ if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return config
107
+ // Tree carriers preserve the expressions owned by their child entries.
108
+ if (fiber.runtime?.callback[EntryGroup.key]) return config
109
+ return interpolate(fiber.ctx, config)
110
+ })
114
111
 
115
- ctx.on('internal/update', function (config, noSave, next) {
116
- if (!this.entry || noSave || this.parent.fiber?.entry === this.entry) return next()
117
- const unparse = this.runtime?.Config?.['simplify']
118
- this.entry.options.config = unparse ? unparse.call(this.runtime!.Config, config) : config
119
- this.entry.parent.tree.write()
120
- return next()
121
- }, { global: true, prepend: true })
112
+ ctx.on('internal/commit', (fiber, config) => {
113
+ if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return
114
+ const schema = fiber.runtime?.Config
115
+ const unparse = schema?.['simplify']
116
+ const { entry } = fiber
117
+ const legacy = { ...entry.options }
118
+ entry.options.config = unparse ? unparse.call(schema, config) : config
119
+ entry.parent.tree.commit({ id: entry.options.id, group: entry.parent, options: entry.options, legacy })
120
+ })
122
121
 
123
- ctx.on('internal/update', function (config, _, next) {
122
+ ctx.on('internal/update', function (config, next) {
124
123
  if (!this.entry || this.parent.fiber?.entry === this.entry) return next()
125
124
  self.showLog(this.entry, 'reload')
126
125
  return next()
@@ -152,24 +151,33 @@ export class Loader extends EntryTree {
152
151
  if (!ctx.registry.has(fiber.runtime!.callback)) return
153
152
 
154
153
  // case 5: the entry's tree is being disposed
155
- const treeOwner = fiber.entry.parent.tree.ctx.fiber
156
- if (!treeOwner.uid || treeOwner.state === FiberState.UNLOADING) return
154
+ if (!fiber.entry.parent.tree.ctx.fiber.uid) return
155
+
156
+ const { entry } = fiber
157
+ this.showLog(entry, 'unload')
158
+
159
+ // case 6: the entry's parent is being unloaded, which takes the entry with it
160
+ // (the parent may still be registered, e.g. when it has lost a dependency)
161
+ if (fiber.parent.fiber.state === FiberState.UNLOADING) return
157
162
 
158
- this.showLog(fiber.entry, 'unload')
163
+ // case 7: the entry is being removed by the loader (`EntryGroup.remove`
164
+ // unregisters it before disposing the fiber)
165
+ if (entry.parent.tree.store[entry.options.id] !== entry) return
159
166
 
160
- // case 6: fiber is disposed by loader behavior
167
+ // case 8: fiber is disposed by loader behavior
161
168
  // such as inject checker, config file update, ancestor group disable
162
- if (fiber.entry.disabled) return
169
+ if (entry.disabled) return
163
170
 
164
- fiber.entry.options.disabled = true
165
- fiber.entry.parent.tree.write()
171
+ const legacy = { ...entry.options }
172
+ entry.options.disabled = true
173
+ entry.parent.tree.commit({ id: entry.options.id, group: entry.parent, options: entry.options, legacy })
166
174
  })
167
175
 
168
176
  ctx.plugin(isolate)
169
177
  }
170
178
 
171
- write() {
172
- // Loader's root tree is in-memory; writes are no-ops.
179
+ commit(_change: EntryChange) {
180
+ // Loader's root tree is in-memory; commits are no-ops.
173
181
  }
174
182
 
175
183
  [Service.check]() {
package/src/resolve.ts ADDED
@@ -0,0 +1,75 @@
1
+ import fs from 'node:fs'
2
+ import fsPromises from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import url from 'node:url'
5
+ import type { Dict } from '@deepseek-ai/cosmokit'
6
+
7
+ /** Resolve a specifier to its URL in one configuration project. */
8
+ export type Resolve = (specifier: string) => string
9
+
10
+ // Order matters: the directory ignores itself before the helper appears in it.
11
+ const HELPER_FILES = {
12
+ '.gitignore': '# created by cordis automatically\n*\n',
13
+ // The one-argument form of `import.meta.resolve` anchors on this file, so
14
+ // resolution happens in the project scope. A resolve call also survives a
15
+ // bundling host, which transforms modules inside its root and redirects the
16
+ // `import()` in them to its own resolver.
17
+ 'resolve.mjs': 'export default (specifier) => import.meta.resolve(specifier)\n',
18
+ }
19
+
20
+ const cache: Dict<Promise<Resolve | undefined>> = Object.create(null)
21
+
22
+ /** Nearest ancestor of `dir` that owns a `package.json`, if any. */
23
+ function findScope(dir: string) {
24
+ while (true) {
25
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir
26
+ const parent = path.dirname(dir)
27
+ if (parent === dir) return
28
+ dir = parent
29
+ }
30
+ }
31
+
32
+ function resolveScope(baseUrl: string | undefined) {
33
+ if (!baseUrl) return
34
+ let dir: string
35
+ try {
36
+ dir = url.fileURLToPath(new URL('.', baseUrl))
37
+ } catch {
38
+ return
39
+ }
40
+ return findScope(path.resolve(dir))
41
+ }
42
+
43
+ async function write(filename: string, content: string) {
44
+ // Another process may be writing the same path; `rename` is atomic, so a
45
+ // concurrent reader only ever observes the complete helper.
46
+ const temp = `${filename}.${process.pid}`
47
+ await fsPromises.writeFile(temp, content)
48
+ await fsPromises.rename(temp, filename)
49
+ }
50
+
51
+ async function _createResolve(scope: string): Promise<Resolve | undefined> {
52
+ const dir = path.join(scope, '.cordis')
53
+ try {
54
+ await fsPromises.mkdir(dir, { recursive: true })
55
+ for (const [name, content] of Object.entries(HELPER_FILES)) {
56
+ await write(path.join(dir, name), content)
57
+ }
58
+ } catch {
59
+ // Read-only filesystems are legitimate; the caller falls back to a native `import()`.
60
+ return
61
+ }
62
+ const helperUrl = url.pathToFileURL(path.join(dir, 'resolve.mjs')).href
63
+ return (await import(/* @vite-ignore */ helperUrl)).default
64
+ }
65
+
66
+ /**
67
+ * Create or reuse a native ESM resolver anchored in the config project's package scope.
68
+ * @param baseUrl Config file URL; absent, non-file or unscoped URLs cannot supply a resolver.
69
+ * @returns The project resolver, or undefined when no package scope exists or its helper cannot be written.
70
+ */
71
+ export async function createResolve(baseUrl: string | undefined) {
72
+ const scope = resolveScope(baseUrl)
73
+ if (!scope) return
74
+ return await (cache[scope] ??= _createResolve(scope))
75
+ }