@atscript/core 0.2.17 → 0.2.19

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/dist/index.cjs CHANGED
@@ -123,6 +123,22 @@ var SemanticNode = class {
123
123
  this.tokens.set(semantic, token);
124
124
  return this;
125
125
  }
126
+ /**
127
+ * `define` for a node built from others (a merged prop, a copy of one): a definition
128
+ * another node declares stays that node's.
129
+ */ carryDefinition(node) {
130
+ var _node;
131
+ this.definition = node;
132
+ (_node = node).ownerNode ?? (_node.ownerNode = this);
133
+ return this;
134
+ }
135
+ /** `saveToken` for a node built from others: a token another node declares stays that node's. */ carryToken(token, semantic) {
136
+ var _token;
137
+ if (!this.tokens) this.tokens = /* @__PURE__ */ new Map();
138
+ (_token = token).parentNode ?? (_token.parentNode = this);
139
+ this.tokens.set(semantic, token);
140
+ return this;
141
+ }
126
142
  wrap(node, token) {
127
143
  this.define(node);
128
144
  this.saveToken(token, "identifier");
@@ -972,11 +988,13 @@ function _define_property$11(obj, key, value) {
972
988
  }
973
989
  var SemanticStructureNode = class extends SemanticGroup {
974
990
  /**
975
- * Shortcut to set props, used as utility
991
+ * Shortcut to set props, used as utility. A prop another structure declares keeps that
992
+ * structure as its owner: a merged or copied structure carries such props by reference.
976
993
  */ setProps(props) {
977
994
  this.nodes = props;
978
995
  for (const prop of props) {
979
- prop.ownerNode = this;
996
+ var _prop;
997
+ (_prop = prop).ownerNode ?? (_prop.ownerNode = this);
980
998
  this.props.set(prop.id, prop);
981
999
  }
982
1000
  }
@@ -1769,6 +1787,26 @@ function describeUnionMembers(def, doc) {
1769
1787
 
1770
1788
  //#endregion
1771
1789
  //#region packages/core/src/config/load-config.ts
1790
+ /** Numbers the bundled copies of this process (see `bundleTsConfig`). */ let bundleSeq = 0;
1791
+ /** The name of a bundled copy of a `.ts` config (see `bundleTsConfig`): its process id. */ const BUNDLED_COPY = /^atscript\.config\.[\w-]+\.(\d+)\.\d+\.[cm]js$/u;
1792
+ /** Whether process `pid` is gone (a live process of another user counts as alive). */ function isGone(pid) {
1793
+ try {
1794
+ process.kill(pid, 0);
1795
+ return false;
1796
+ } catch (error) {
1797
+ return error.code === "ESRCH";
1798
+ }
1799
+ }
1800
+ /**
1801
+ * Removes the bundled copies in `dir` of processes that are gone (killed while they loaded the
1802
+ * config, before they removed their copy); the copies of live processes are theirs.
1803
+ */ async function removeLeftoverCopies(dir) {
1804
+ const names = await (0, node_fs_promises.readdir)(dir).catch(() => []);
1805
+ await Promise.all(names.map(async (name) => {
1806
+ const pid = Number(BUNDLED_COPY.exec(name)?.[1]);
1807
+ if (pid && pid !== process.pid && isGone(pid)) await (0, node_fs_promises.rm)(node_path.default.join(dir, name), { force: true }).catch(() => {});
1808
+ }));
1809
+ }
1772
1810
  async function bundleTsConfig(configFile, forceFormat) {
1773
1811
  const dirnameVarName = "injected_original_dirname";
1774
1812
  const filenameVarName = "injected_original_filename";
@@ -1801,11 +1839,13 @@ async function bundleTsConfig(configFile, forceFormat) {
1801
1839
  }]
1802
1840
  });
1803
1841
  const outputDir = node_path.default.dirname(configFile);
1842
+ const name = `atscript.config.[hash].${process.pid}.${bundleSeq++}`;
1843
+ await removeLeftoverCopies(outputDir);
1804
1844
  const fileName = (await bundle.write({
1805
1845
  dir: outputDir,
1806
1846
  format: forceFormat || "esm",
1807
1847
  sourcemap: "inline",
1808
- entryFileNames: forceFormat === "cjs" ? "atscript.config.[hash].cjs" : "atscript.config.[hash].mjs"
1848
+ entryFileNames: forceFormat === "cjs" ? `${name}.cjs` : `${name}.mjs`
1809
1849
  })).output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName;
1810
1850
  return node_path.default.join(outputDir, fileName);
1811
1851
  }
@@ -1850,10 +1890,6 @@ async function loadTsConfig(configFile, forceFormat) {
1850
1890
  /* @vite-ignore */
1851
1891
  (0, node_url.pathToFileURL)(file).href
1852
1892
  )).default;
1853
- } catch (error) {
1854
- const message = error instanceof Error ? error.message : String(error);
1855
- console.error(`Could not load config file ${configFile}: ${message}`);
1856
- return {};
1857
1893
  } finally {
1858
1894
  node_fs.default.unlink(file, () => {});
1859
1895
  }
@@ -1870,7 +1906,7 @@ async function loadConfig(configPath, forceFormat) {
1870
1906
  else throw new Error(`Unsupported config format. Expected: \`${SUPPORTED_CONFIG_FORMATS.join(",")}\` but got \`${ext}\``);
1871
1907
  } catch (error) {
1872
1908
  console.error(error);
1873
- throw new Error("Error happened while loading config.");
1909
+ throw new Error("Error happened while loading config.", { cause: error });
1874
1910
  }
1875
1911
  }
1876
1912
 
@@ -9131,11 +9167,11 @@ var AtscriptDoc = class AtscriptDoc {
9131
9167
  const cloned = new SemanticPropNode();
9132
9168
  copiedFrom.set(cloned, prop);
9133
9169
  const idToken = prop.token("identifier");
9134
- if (idToken) cloned.saveToken(idToken, "identifier");
9135
- if (newDef) cloned.define(newDef);
9170
+ if (idToken) cloned.carryToken(idToken, "identifier");
9171
+ if (newDef) cloned.carryDefinition(newDef);
9136
9172
  cloned.annotations = group.own.length === 0 ? prop.annotations : this.mergeNodesAnnotations(prop.annotations, group.own, true);
9137
9173
  const optionalToken = prop.token("optional");
9138
- if (optionalToken) cloned.saveToken(optionalToken, "optional");
9174
+ if (optionalToken) cloned.carryToken(optionalToken, "optional");
9139
9175
  newProps.push(cloned);
9140
9176
  changed = true;
9141
9177
  }
@@ -10229,8 +10265,8 @@ var AtscriptDoc = class AtscriptDoc {
10229
10265
  if (isPrimitive(def)) def = createSyntheticRef(def.key);
10230
10266
  }
10231
10267
  const prop = new SemanticPropNode();
10232
- prop.saveToken(l.token("identifier"), "identifier");
10233
- prop.define(def);
10268
+ prop.carryToken(l.token("identifier"), "identifier");
10269
+ prop.carryDefinition(def);
10234
10270
  prop.annotations = this.mergeNodesAnnotations(l.annotations, r.annotations);
10235
10271
  keepOptional(prop, l, r);
10236
10272
  declaringDocs.set(prop, declaringDocs.get(l) ?? leftDoc);
@@ -10511,7 +10547,7 @@ const zeroRange = {
10511
10547
  * accepts a value without `u`, as 0.1.110 did).
10512
10548
  */ function keepOptional(prop, ...members) {
10513
10549
  const token = members[0]?.token("optional");
10514
- if (token && members.every((m) => m.token("optional"))) prop.saveToken(token, "optional");
10550
+ if (token && members.every((m) => m.token("optional"))) prop.carryToken(token, "optional");
10515
10551
  }
10516
10552
  /** The declarations whose type-level annotations are being evaluated (see `intersectionAnnotations`). */ const evaluatingMembers = /* @__PURE__ */ new Set();
10517
10553
  /** Why each `never` a merge built could not merge its members (see `neverReasonIn`). */ const neverReasons = /* @__PURE__ */ new WeakMap();
@@ -11397,23 +11433,48 @@ var PluginManager = class {
11397
11433
  }
11398
11434
  if (raw?.annotations) this._docConfig.annotations = { ...raw.annotations };
11399
11435
  this._docConfig.unknownAnnotation = raw?.unknownAnnotation;
11400
- this._docConfig.rootDir = this.root ?? (raw?.rootDir && (0, node_path.isAbsolute)(raw.rootDir) ? raw.rootDir : void 0);
11436
+ this._docConfig.rootDir = this.root ?? (this.cfg.rootDir && node_path.default.isAbsolute(this.cfg.rootDir) ? this.cfg.rootDir : void 0);
11401
11437
  }
11402
11438
  return this._docConfig;
11403
11439
  }
11404
- async config(config = this.cfg) {
11440
+ /**
11441
+ * The config merged with the defaults and every plugin's `config` hook. Its `rootDir` (also the
11442
+ * one the hooks receive) is the project root, absolute: the host's, else the config's `rootDir`
11443
+ * resolved against the working directory (as `build()` resolves a config without a file).
11444
+ */ config(config = this.cfg) {
11405
11445
  if (!this._config) {
11406
- config = (0, defu.defu)(config, getDefaultAtscriptConfig());
11407
- const seen = /* @__PURE__ */ new Set();
11408
- for (const plugin of this.plugins) {
11409
- if (seen.has(plugin.name)) continue;
11410
- seen.add(plugin.name);
11411
- config = (0, defu.defu)(await plugin.config?.(config), config);
11412
- }
11413
- this._config = config;
11446
+ const merging = this.mergeConfig(config);
11447
+ this._config = merging;
11448
+ merging.catch(() => {
11449
+ if (this._config === merging) this._config = void 0;
11450
+ });
11414
11451
  }
11415
11452
  return this._config;
11416
11453
  }
11454
+ async mergeConfig(config) {
11455
+ const rootDir = this.root ?? node_path.default.resolve(config.rootDir ?? ".");
11456
+ let merged = {
11457
+ ...(0, defu.defu)(config, getDefaultAtscriptConfig()),
11458
+ rootDir
11459
+ };
11460
+ const seen = /* @__PURE__ */ new Set();
11461
+ for (const plugin of this.plugins) {
11462
+ if (seen.has(plugin.name)) continue;
11463
+ seen.add(plugin.name);
11464
+ merged = (0, defu.defu)(await plugin.config?.(merged), merged);
11465
+ }
11466
+ return {
11467
+ ...merged,
11468
+ rootDir
11469
+ };
11470
+ }
11471
+ /**
11472
+ * Starts a build: the plugins' `config` hooks (once per manager), then their `buildStart`
11473
+ * hooks in order, each awaited — before the host discovers or reads any `.as` file.
11474
+ */ async buildStart() {
11475
+ const config = await this.config();
11476
+ for (const plugin of this.plugins) if (plugin.buildStart) await plugin.buildStart(config);
11477
+ }
11417
11478
  async resolve(id) {
11418
11479
  let newId = id;
11419
11480
  for (const plugin of this.plugins) if (plugin.resolve) newId = await plugin.resolve(newId) ?? newId;
@@ -11451,7 +11512,7 @@ var PluginManager = class {
11451
11512
  constructor(cfg, root) {
11452
11513
  _define_property$2(this, "cfg", void 0);
11453
11514
  _define_property$2(this, "root", void 0);
11454
- _define_property$2(this, "_config", void 0);
11515
+ /** The merged config: the plugins' `config` hooks run once per manager (again after a failure). */ _define_property$2(this, "_config", void 0);
11455
11516
  _define_property$2(this, "name", void 0);
11456
11517
  _define_property$2(this, "_docConfig", void 0);
11457
11518
  this.cfg = cfg;
@@ -11598,29 +11659,37 @@ var AtscriptRepo = class {
11598
11659
  }
11599
11660
  return annotations;
11600
11661
  }
11601
- async loadPluginManagerFor(id) {
11662
+ /**
11663
+ * The plugin manager for document `id`, its plugins' `config` hooks run (before the document
11664
+ * is resolved or loaded): the shared config's, or that of the config file `id` is under.
11665
+ */ async loadPluginManagerFor(id) {
11602
11666
  if (this.sharedConfig) {
11603
- if (!this.sharedPluginManager) this.sharedPluginManager = {
11604
- manager: new PluginManager(this.sharedConfig, node_path.default.resolve(this.root, this.sharedConfig.rootDir ?? ".")),
11605
- dependants: /* @__PURE__ */ new Set()
11606
- };
11607
- return this.sharedPluginManager;
11667
+ if (!this.sharedPluginManagerReady) {
11668
+ const shared = {
11669
+ manager: new PluginManager(this.sharedConfig, node_path.default.resolve(this.root, this.sharedConfig.rootDir ?? ".")),
11670
+ dependants: /* @__PURE__ */ new Set()
11671
+ };
11672
+ const ready = shared.manager.getDocConfig().then(() => shared);
11673
+ this.sharedPluginManager = shared;
11674
+ this.sharedPluginManagerReady = ready;
11675
+ ready.catch(() => {
11676
+ if (this.sharedPluginManagerReady === ready) this.sharedPluginManagerReady = void 0;
11677
+ });
11678
+ }
11679
+ return this.sharedPluginManagerReady;
11608
11680
  }
11609
11681
  const configFile = await resolveConfigFile(id, this.root);
11610
11682
  if (configFile) {
11611
- if (!this.configFiles.has(configFile)) {
11612
- const rawConfigPromise = loadConfig(configFile, this.configFormat);
11613
- this.configFiles.set(configFile, rawConfigPromise);
11683
+ let managers = this.configFiles.get(configFile);
11684
+ if (!managers) {
11685
+ const loading = this.loadConfigFile(configFile);
11686
+ managers = loading;
11687
+ this.configFiles.set(configFile, loading);
11688
+ loading.catch(() => {
11689
+ if (this.configFiles.get(configFile) === loading) this.configFiles.delete(configFile);
11690
+ });
11614
11691
  }
11615
- const rawConfig = await this.configFiles.get(configFile);
11616
- if (!rawConfig.rootDir) rawConfig.rootDir = node_path.default.dirname(configFile);
11617
- const manager = new PluginManager(rawConfig, node_path.default.resolve(node_path.default.dirname(configFile), rawConfig.rootDir));
11618
- await manager.getDocConfig();
11619
- return {
11620
- file: configFile,
11621
- manager,
11622
- dependants: /* @__PURE__ */ new Set()
11623
- };
11692
+ return managers;
11624
11693
  } else {
11625
11694
  const manager = new PluginManager({ rootDir: process.cwd() }, process.cwd());
11626
11695
  await manager.getDocConfig();
@@ -11630,14 +11699,28 @@ var AtscriptRepo = class {
11630
11699
  };
11631
11700
  }
11632
11701
  }
11702
+ /** Loads `configFile` and runs its plugins' `config` hooks (see `configFiles`). */ async loadConfigFile(configFile) {
11703
+ const rawConfig = await loadConfig(configFile, this.configFormat);
11704
+ if (!rawConfig.rootDir) rawConfig.rootDir = node_path.default.dirname(configFile);
11705
+ const manager = new PluginManager(rawConfig, node_path.default.resolve(node_path.default.dirname(configFile), rawConfig.rootDir));
11706
+ await manager.getDocConfig();
11707
+ return {
11708
+ file: configFile,
11709
+ manager,
11710
+ dependants: /* @__PURE__ */ new Set()
11711
+ };
11712
+ }
11633
11713
  async resolveConfig(id) {
11634
11714
  let config = this.configs.get(id);
11635
11715
  if (!config) {
11636
- config = this.loadPluginManagerFor(id);
11637
- config.then((c) => {
11716
+ const loading = this.loadPluginManagerFor(id);
11717
+ config = loading;
11718
+ loading.then((c) => {
11638
11719
  c.dependants.add(id);
11720
+ }, () => {
11721
+ if (this.configs.get(id) === loading) this.configs.delete(id);
11639
11722
  });
11640
- this.configs.set(id, config);
11723
+ this.configs.set(id, loading);
11641
11724
  }
11642
11725
  return config;
11643
11726
  }
@@ -11762,11 +11845,13 @@ var AtscriptRepo = class {
11762
11845
  * .as Documents cache
11763
11846
  */ _define_property$1(this, "atscripts", void 0);
11764
11847
  _define_property$1(this, "sharedPluginManager", void 0);
11848
+ /** The shared plugin manager once its plugins' `config` hooks ran (see `loadPluginManagerFor`). */ _define_property$1(this, "sharedPluginManagerReady", void 0);
11765
11849
  /**
11766
11850
  * Maps resolved file:// URIs back to bare specifiers (for LSP auto-import).
11767
11851
  */ _define_property$1(this, "resolvedToBare", void 0);
11768
11852
  /**
11769
- * cache for raw content of config files
11853
+ * The plugin manager of each config file (by path), shared by every document under it: its
11854
+ * plugins' `config` hooks run once per load of the file. Dropping an entry loads the file again.
11770
11855
  */ _define_property$1(this, "configFiles", void 0);
11771
11856
  this.root = root;
11772
11857
  this.sharedConfig = sharedConfig;
@@ -11813,9 +11898,11 @@ function _define_property(obj, key, value) {
11813
11898
  }
11814
11899
  /** Upper bound on concurrent file operations — macOS defaults `ulimit -n` to 256. */ const WRITE_CONCURRENCY = 32;
11815
11900
  async function build(config) {
11816
- const rootDir = config.rootDir ? config.rootDir.startsWith("/") ? config.rootDir : path.default.join(process.cwd(), config.rootDir) : process.cwd();
11901
+ const rootDir = config.rootDir ? path.default.isAbsolute(config.rootDir) ? config.rootDir : path.default.join(process.cwd(), config.rootDir) : process.cwd();
11817
11902
  config.rootDir = rootDir;
11818
11903
  const repo = new AtscriptRepo(rootDir, config);
11904
+ const { manager } = await repo.loadPluginManagerFor(`file://${rootDir}`);
11905
+ await manager.buildStart();
11819
11906
  const entries = [];
11820
11907
  if (config.entries && config.entries.length > 0) for (const entry of config.entries) entries.push(path.default.join(rootDir, entry));
11821
11908
  else {
package/dist/index.d.ts CHANGED
@@ -166,14 +166,17 @@ declare class AtscriptRepo {
166
166
  */
167
167
  protected readonly atscripts: Map<string, Promise<AtscriptDoc>>;
168
168
  sharedPluginManager: TPluginManagers | undefined;
169
+ /** The shared plugin manager once its plugins' `config` hooks ran (see `loadPluginManagerFor`). */
170
+ private sharedPluginManagerReady;
169
171
  /**
170
172
  * Maps resolved file:// URIs back to bare specifiers (for LSP auto-import).
171
173
  */
172
174
  readonly resolvedToBare: Map<string, string>;
173
175
  /**
174
- * cache for raw content of config files
176
+ * The plugin manager of each config file (by path), shared by every document under it: its
177
+ * plugins' `config` hooks run once per load of the file. Dropping an entry loads the file again.
175
178
  */
176
- protected configFiles: Map<string, Promise<Partial<TAtscriptConfigInput & TAtscriptConfigOutput>>>;
179
+ protected configFiles: Map<string, Promise<TPluginManagers>>;
177
180
  getSharedPluginManager(): PluginManager | undefined;
178
181
  getPrimitivesTags(): Promise<Set<string> | undefined>;
179
182
  getUsedAnnotations(): Promise<Record<string, {
@@ -191,7 +194,13 @@ declare class AtscriptRepo {
191
194
  type: string;
192
195
  }>;
193
196
  } | undefined>>;
197
+ /**
198
+ * The plugin manager for document `id`, its plugins' `config` hooks run (before the document
199
+ * is resolved or loaded): the shared config's, or that of the config file `id` is under.
200
+ */
194
201
  loadPluginManagerFor(id: string): Promise<TPluginManagers>;
202
+ /** Loads `configFile` and runs its plugins' `config` hooks (see `configFiles`). */
203
+ protected loadConfigFile(configFile: string): Promise<TPluginManagers>;
195
204
  resolveConfig(id: string): Promise<TPluginManagers>;
196
205
  openDocument(id: string, text?: string): Promise<AtscriptDoc>;
197
206
  /**
@@ -279,6 +288,21 @@ interface TAtscriptRenderOptions {
279
288
  interface TAtscriptPlugin {
280
289
  name: string;
281
290
  config?: (config: TAtscriptConfig) => Promise<TAtscriptConfig | undefined> | TAtscriptConfig | undefined;
291
+ /**
292
+ * The start of a build: runs after every plugin's `config`, before any `.as` file is
293
+ * discovered or read — the place to write `.as` files (and other files) generated from
294
+ * another source.
295
+ *
296
+ * `config` is the final config; its `rootDir` is absolute. Called by `build()` (the `asc` CLI)
297
+ * and by the bundler plugin (each build, each watch rebuild, the dev server's start), so it may
298
+ * run several times per process, and several runs may overlap (parallel builds, test projects
299
+ * sharing a plugin instance): write each file atomically (a temp file renamed over it), and only
300
+ * when its content changes. The language server never calls it (it reads what a build left on
301
+ * disk).
302
+ */
303
+ buildStart?: (config: TAtscriptConfig & {
304
+ rootDir: string;
305
+ }) => Promise<void> | void;
282
306
  resolve?: (id: string) => Promise<string | undefined> | string | undefined;
283
307
  load?: (id: string) => Promise<string | undefined> | string | undefined;
284
308
  onDocument?: (doc: AtscriptDoc) => Promise<void> | void;
@@ -297,12 +321,26 @@ declare class PluginManager {
297
321
  constructor(cfg: TAtscriptConfig,
298
322
  /** The project root (absolute), the config's `rootDir` resolved. */
299
323
  root?: string | undefined);
300
- private _config;
324
+ /** The merged config: the plugins' `config` hooks run once per manager (again after a failure). */
325
+ private _config?;
301
326
  name: string;
302
327
  protected _docConfig: TAtscriptDocConfig | undefined;
303
328
  get plugins(): TAtscriptPlugin[];
304
329
  getDocConfig(): Promise<TAtscriptDocConfig>;
305
- config(config?: TAtscriptConfig): Promise<TAtscriptConfig>;
330
+ /**
331
+ * The config merged with the defaults and every plugin's `config` hook. Its `rootDir` (also the
332
+ * one the hooks receive) is the project root, absolute: the host's, else the config's `rootDir`
333
+ * resolved against the working directory (as `build()` resolves a config without a file).
334
+ */
335
+ config(config?: TAtscriptConfig): Promise<TAtscriptConfig & {
336
+ rootDir: string;
337
+ }>;
338
+ private mergeConfig;
339
+ /**
340
+ * Starts a build: the plugins' `config` hooks (once per manager), then their `buildStart`
341
+ * hooks in order, each awaited — before the host discovers or reads any `.as` file.
342
+ */
343
+ buildStart(): Promise<void>;
306
344
  resolve(id: string): Promise<string>;
307
345
  load(id: string): Promise<string>;
308
346
  onDocument(doc: AtscriptDoc): Promise<void>;
@@ -404,6 +442,13 @@ declare class SemanticNode {
404
442
  get def(): SemanticNode | undefined;
405
443
  get identifier(): string | undefined;
406
444
  saveToken(token: Token, semantic: TSemanticToken): this;
445
+ /**
446
+ * `define` for a node built from others (a merged prop, a copy of one): a definition
447
+ * another node declares stays that node's.
448
+ */
449
+ carryDefinition(node: SemanticNode): this;
450
+ /** `saveToken` for a node built from others: a token another node declares stays that node's. */
451
+ carryToken(token: Token, semantic: TSemanticToken): this;
407
452
  wrap(node: SemanticNode, token: Token): this;
408
453
  token(s: TSemanticToken): Token | undefined;
409
454
  has(s: TSemanticToken): boolean | undefined;
@@ -2471,7 +2516,8 @@ declare class SemanticStructureNode extends SemanticGroup {
2471
2516
  constructor();
2472
2517
  readonly props: Map<string, SemanticPropNode>;
2473
2518
  /**
2474
- * Shortcut to set props, used as utility
2519
+ * Shortcut to set props, used as utility. A prop another structure declares keeps that
2520
+ * structure as its owner: a merged or copied structure carries such props by reference.
2475
2521
  */
2476
2522
  setProps(props: SemanticPropNode[]): void;
2477
2523
  registerAtDocument(doc: AtscriptDoc): void;
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import path from "path";
2
2
  import { URL } from "url";
3
- import { access, readFile, readdir, realpath } from "node:fs/promises";
4
- import path$1, { isAbsolute } from "node:path";
3
+ import { access, readFile, readdir, realpath, rm } from "node:fs/promises";
4
+ import path$1 from "node:path";
5
5
  import fs from "node:fs";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { rolldown } from "rolldown";
@@ -9,7 +9,7 @@ import { createHash } from "crypto";
9
9
  import { readFileSync, statSync } from "fs";
10
10
  import { Node, printTree } from "@prostojs/parser";
11
11
  import { defu } from "defu";
12
- import { mkdir, readFile as readFile$1, rename, rm, writeFile } from "fs/promises";
12
+ import { mkdir, readFile as readFile$1, rename, rm as rm$1, writeFile } from "fs/promises";
13
13
  import { glob } from "glob";
14
14
 
15
15
  //#region packages/core/src/parser/nodes/semantic-node.ts
@@ -92,6 +92,22 @@ var SemanticNode = class {
92
92
  this.tokens.set(semantic, token);
93
93
  return this;
94
94
  }
95
+ /**
96
+ * `define` for a node built from others (a merged prop, a copy of one): a definition
97
+ * another node declares stays that node's.
98
+ */ carryDefinition(node) {
99
+ var _node;
100
+ this.definition = node;
101
+ (_node = node).ownerNode ?? (_node.ownerNode = this);
102
+ return this;
103
+ }
104
+ /** `saveToken` for a node built from others: a token another node declares stays that node's. */ carryToken(token, semantic) {
105
+ var _token;
106
+ if (!this.tokens) this.tokens = /* @__PURE__ */ new Map();
107
+ (_token = token).parentNode ?? (_token.parentNode = this);
108
+ this.tokens.set(semantic, token);
109
+ return this;
110
+ }
95
111
  wrap(node, token) {
96
112
  this.define(node);
97
113
  this.saveToken(token, "identifier");
@@ -941,11 +957,13 @@ function _define_property$11(obj, key, value) {
941
957
  }
942
958
  var SemanticStructureNode = class extends SemanticGroup {
943
959
  /**
944
- * Shortcut to set props, used as utility
960
+ * Shortcut to set props, used as utility. A prop another structure declares keeps that
961
+ * structure as its owner: a merged or copied structure carries such props by reference.
945
962
  */ setProps(props) {
946
963
  this.nodes = props;
947
964
  for (const prop of props) {
948
- prop.ownerNode = this;
965
+ var _prop;
966
+ (_prop = prop).ownerNode ?? (_prop.ownerNode = this);
949
967
  this.props.set(prop.id, prop);
950
968
  }
951
969
  }
@@ -1738,6 +1756,26 @@ function describeUnionMembers(def, doc) {
1738
1756
 
1739
1757
  //#endregion
1740
1758
  //#region packages/core/src/config/load-config.ts
1759
+ /** Numbers the bundled copies of this process (see `bundleTsConfig`). */ let bundleSeq = 0;
1760
+ /** The name of a bundled copy of a `.ts` config (see `bundleTsConfig`): its process id. */ const BUNDLED_COPY = /^atscript\.config\.[\w-]+\.(\d+)\.\d+\.[cm]js$/u;
1761
+ /** Whether process `pid` is gone (a live process of another user counts as alive). */ function isGone(pid) {
1762
+ try {
1763
+ process.kill(pid, 0);
1764
+ return false;
1765
+ } catch (error) {
1766
+ return error.code === "ESRCH";
1767
+ }
1768
+ }
1769
+ /**
1770
+ * Removes the bundled copies in `dir` of processes that are gone (killed while they loaded the
1771
+ * config, before they removed their copy); the copies of live processes are theirs.
1772
+ */ async function removeLeftoverCopies(dir) {
1773
+ const names = await readdir(dir).catch(() => []);
1774
+ await Promise.all(names.map(async (name) => {
1775
+ const pid = Number(BUNDLED_COPY.exec(name)?.[1]);
1776
+ if (pid && pid !== process.pid && isGone(pid)) await rm(path$1.join(dir, name), { force: true }).catch(() => {});
1777
+ }));
1778
+ }
1741
1779
  async function bundleTsConfig(configFile, forceFormat) {
1742
1780
  const dirnameVarName = "injected_original_dirname";
1743
1781
  const filenameVarName = "injected_original_filename";
@@ -1770,11 +1808,13 @@ async function bundleTsConfig(configFile, forceFormat) {
1770
1808
  }]
1771
1809
  });
1772
1810
  const outputDir = path$1.dirname(configFile);
1811
+ const name = `atscript.config.[hash].${process.pid}.${bundleSeq++}`;
1812
+ await removeLeftoverCopies(outputDir);
1773
1813
  const fileName = (await bundle.write({
1774
1814
  dir: outputDir,
1775
1815
  format: forceFormat || "esm",
1776
1816
  sourcemap: "inline",
1777
- entryFileNames: forceFormat === "cjs" ? "atscript.config.[hash].cjs" : "atscript.config.[hash].mjs"
1817
+ entryFileNames: forceFormat === "cjs" ? `${name}.cjs` : `${name}.mjs`
1778
1818
  })).output.find((chunk) => chunk.type === "chunk" && chunk.isEntry).fileName;
1779
1819
  return path$1.join(outputDir, fileName);
1780
1820
  }
@@ -1819,10 +1859,6 @@ async function loadTsConfig(configFile, forceFormat) {
1819
1859
  /* @vite-ignore */
1820
1860
  pathToFileURL(file).href
1821
1861
  )).default;
1822
- } catch (error) {
1823
- const message = error instanceof Error ? error.message : String(error);
1824
- console.error(`Could not load config file ${configFile}: ${message}`);
1825
- return {};
1826
1862
  } finally {
1827
1863
  fs.unlink(file, () => {});
1828
1864
  }
@@ -1839,7 +1875,7 @@ async function loadConfig(configPath, forceFormat) {
1839
1875
  else throw new Error(`Unsupported config format. Expected: \`${SUPPORTED_CONFIG_FORMATS.join(",")}\` but got \`${ext}\``);
1840
1876
  } catch (error) {
1841
1877
  console.error(error);
1842
- throw new Error("Error happened while loading config.");
1878
+ throw new Error("Error happened while loading config.", { cause: error });
1843
1879
  }
1844
1880
  }
1845
1881
 
@@ -9100,11 +9136,11 @@ var AtscriptDoc = class AtscriptDoc {
9100
9136
  const cloned = new SemanticPropNode();
9101
9137
  copiedFrom.set(cloned, prop);
9102
9138
  const idToken = prop.token("identifier");
9103
- if (idToken) cloned.saveToken(idToken, "identifier");
9104
- if (newDef) cloned.define(newDef);
9139
+ if (idToken) cloned.carryToken(idToken, "identifier");
9140
+ if (newDef) cloned.carryDefinition(newDef);
9105
9141
  cloned.annotations = group.own.length === 0 ? prop.annotations : this.mergeNodesAnnotations(prop.annotations, group.own, true);
9106
9142
  const optionalToken = prop.token("optional");
9107
- if (optionalToken) cloned.saveToken(optionalToken, "optional");
9143
+ if (optionalToken) cloned.carryToken(optionalToken, "optional");
9108
9144
  newProps.push(cloned);
9109
9145
  changed = true;
9110
9146
  }
@@ -10198,8 +10234,8 @@ var AtscriptDoc = class AtscriptDoc {
10198
10234
  if (isPrimitive(def)) def = createSyntheticRef(def.key);
10199
10235
  }
10200
10236
  const prop = new SemanticPropNode();
10201
- prop.saveToken(l.token("identifier"), "identifier");
10202
- prop.define(def);
10237
+ prop.carryToken(l.token("identifier"), "identifier");
10238
+ prop.carryDefinition(def);
10203
10239
  prop.annotations = this.mergeNodesAnnotations(l.annotations, r.annotations);
10204
10240
  keepOptional(prop, l, r);
10205
10241
  declaringDocs.set(prop, declaringDocs.get(l) ?? leftDoc);
@@ -10480,7 +10516,7 @@ const zeroRange = {
10480
10516
  * accepts a value without `u`, as 0.1.110 did).
10481
10517
  */ function keepOptional(prop, ...members) {
10482
10518
  const token = members[0]?.token("optional");
10483
- if (token && members.every((m) => m.token("optional"))) prop.saveToken(token, "optional");
10519
+ if (token && members.every((m) => m.token("optional"))) prop.carryToken(token, "optional");
10484
10520
  }
10485
10521
  /** The declarations whose type-level annotations are being evaluated (see `intersectionAnnotations`). */ const evaluatingMembers = /* @__PURE__ */ new Set();
10486
10522
  /** Why each `never` a merge built could not merge its members (see `neverReasonIn`). */ const neverReasons = /* @__PURE__ */ new WeakMap();
@@ -11366,23 +11402,48 @@ var PluginManager = class {
11366
11402
  }
11367
11403
  if (raw?.annotations) this._docConfig.annotations = { ...raw.annotations };
11368
11404
  this._docConfig.unknownAnnotation = raw?.unknownAnnotation;
11369
- this._docConfig.rootDir = this.root ?? (raw?.rootDir && isAbsolute(raw.rootDir) ? raw.rootDir : void 0);
11405
+ this._docConfig.rootDir = this.root ?? (this.cfg.rootDir && path$1.isAbsolute(this.cfg.rootDir) ? this.cfg.rootDir : void 0);
11370
11406
  }
11371
11407
  return this._docConfig;
11372
11408
  }
11373
- async config(config = this.cfg) {
11409
+ /**
11410
+ * The config merged with the defaults and every plugin's `config` hook. Its `rootDir` (also the
11411
+ * one the hooks receive) is the project root, absolute: the host's, else the config's `rootDir`
11412
+ * resolved against the working directory (as `build()` resolves a config without a file).
11413
+ */ config(config = this.cfg) {
11374
11414
  if (!this._config) {
11375
- config = defu(config, getDefaultAtscriptConfig());
11376
- const seen = /* @__PURE__ */ new Set();
11377
- for (const plugin of this.plugins) {
11378
- if (seen.has(plugin.name)) continue;
11379
- seen.add(plugin.name);
11380
- config = defu(await plugin.config?.(config), config);
11381
- }
11382
- this._config = config;
11415
+ const merging = this.mergeConfig(config);
11416
+ this._config = merging;
11417
+ merging.catch(() => {
11418
+ if (this._config === merging) this._config = void 0;
11419
+ });
11383
11420
  }
11384
11421
  return this._config;
11385
11422
  }
11423
+ async mergeConfig(config) {
11424
+ const rootDir = this.root ?? path$1.resolve(config.rootDir ?? ".");
11425
+ let merged = {
11426
+ ...defu(config, getDefaultAtscriptConfig()),
11427
+ rootDir
11428
+ };
11429
+ const seen = /* @__PURE__ */ new Set();
11430
+ for (const plugin of this.plugins) {
11431
+ if (seen.has(plugin.name)) continue;
11432
+ seen.add(plugin.name);
11433
+ merged = defu(await plugin.config?.(merged), merged);
11434
+ }
11435
+ return {
11436
+ ...merged,
11437
+ rootDir
11438
+ };
11439
+ }
11440
+ /**
11441
+ * Starts a build: the plugins' `config` hooks (once per manager), then their `buildStart`
11442
+ * hooks in order, each awaited — before the host discovers or reads any `.as` file.
11443
+ */ async buildStart() {
11444
+ const config = await this.config();
11445
+ for (const plugin of this.plugins) if (plugin.buildStart) await plugin.buildStart(config);
11446
+ }
11386
11447
  async resolve(id) {
11387
11448
  let newId = id;
11388
11449
  for (const plugin of this.plugins) if (plugin.resolve) newId = await plugin.resolve(newId) ?? newId;
@@ -11420,7 +11481,7 @@ var PluginManager = class {
11420
11481
  constructor(cfg, root) {
11421
11482
  _define_property$2(this, "cfg", void 0);
11422
11483
  _define_property$2(this, "root", void 0);
11423
- _define_property$2(this, "_config", void 0);
11484
+ /** The merged config: the plugins' `config` hooks run once per manager (again after a failure). */ _define_property$2(this, "_config", void 0);
11424
11485
  _define_property$2(this, "name", void 0);
11425
11486
  _define_property$2(this, "_docConfig", void 0);
11426
11487
  this.cfg = cfg;
@@ -11567,29 +11628,37 @@ var AtscriptRepo = class {
11567
11628
  }
11568
11629
  return annotations;
11569
11630
  }
11570
- async loadPluginManagerFor(id) {
11631
+ /**
11632
+ * The plugin manager for document `id`, its plugins' `config` hooks run (before the document
11633
+ * is resolved or loaded): the shared config's, or that of the config file `id` is under.
11634
+ */ async loadPluginManagerFor(id) {
11571
11635
  if (this.sharedConfig) {
11572
- if (!this.sharedPluginManager) this.sharedPluginManager = {
11573
- manager: new PluginManager(this.sharedConfig, path$1.resolve(this.root, this.sharedConfig.rootDir ?? ".")),
11574
- dependants: /* @__PURE__ */ new Set()
11575
- };
11576
- return this.sharedPluginManager;
11636
+ if (!this.sharedPluginManagerReady) {
11637
+ const shared = {
11638
+ manager: new PluginManager(this.sharedConfig, path$1.resolve(this.root, this.sharedConfig.rootDir ?? ".")),
11639
+ dependants: /* @__PURE__ */ new Set()
11640
+ };
11641
+ const ready = shared.manager.getDocConfig().then(() => shared);
11642
+ this.sharedPluginManager = shared;
11643
+ this.sharedPluginManagerReady = ready;
11644
+ ready.catch(() => {
11645
+ if (this.sharedPluginManagerReady === ready) this.sharedPluginManagerReady = void 0;
11646
+ });
11647
+ }
11648
+ return this.sharedPluginManagerReady;
11577
11649
  }
11578
11650
  const configFile = await resolveConfigFile(id, this.root);
11579
11651
  if (configFile) {
11580
- if (!this.configFiles.has(configFile)) {
11581
- const rawConfigPromise = loadConfig(configFile, this.configFormat);
11582
- this.configFiles.set(configFile, rawConfigPromise);
11652
+ let managers = this.configFiles.get(configFile);
11653
+ if (!managers) {
11654
+ const loading = this.loadConfigFile(configFile);
11655
+ managers = loading;
11656
+ this.configFiles.set(configFile, loading);
11657
+ loading.catch(() => {
11658
+ if (this.configFiles.get(configFile) === loading) this.configFiles.delete(configFile);
11659
+ });
11583
11660
  }
11584
- const rawConfig = await this.configFiles.get(configFile);
11585
- if (!rawConfig.rootDir) rawConfig.rootDir = path$1.dirname(configFile);
11586
- const manager = new PluginManager(rawConfig, path$1.resolve(path$1.dirname(configFile), rawConfig.rootDir));
11587
- await manager.getDocConfig();
11588
- return {
11589
- file: configFile,
11590
- manager,
11591
- dependants: /* @__PURE__ */ new Set()
11592
- };
11661
+ return managers;
11593
11662
  } else {
11594
11663
  const manager = new PluginManager({ rootDir: process.cwd() }, process.cwd());
11595
11664
  await manager.getDocConfig();
@@ -11599,14 +11668,28 @@ var AtscriptRepo = class {
11599
11668
  };
11600
11669
  }
11601
11670
  }
11671
+ /** Loads `configFile` and runs its plugins' `config` hooks (see `configFiles`). */ async loadConfigFile(configFile) {
11672
+ const rawConfig = await loadConfig(configFile, this.configFormat);
11673
+ if (!rawConfig.rootDir) rawConfig.rootDir = path$1.dirname(configFile);
11674
+ const manager = new PluginManager(rawConfig, path$1.resolve(path$1.dirname(configFile), rawConfig.rootDir));
11675
+ await manager.getDocConfig();
11676
+ return {
11677
+ file: configFile,
11678
+ manager,
11679
+ dependants: /* @__PURE__ */ new Set()
11680
+ };
11681
+ }
11602
11682
  async resolveConfig(id) {
11603
11683
  let config = this.configs.get(id);
11604
11684
  if (!config) {
11605
- config = this.loadPluginManagerFor(id);
11606
- config.then((c) => {
11685
+ const loading = this.loadPluginManagerFor(id);
11686
+ config = loading;
11687
+ loading.then((c) => {
11607
11688
  c.dependants.add(id);
11689
+ }, () => {
11690
+ if (this.configs.get(id) === loading) this.configs.delete(id);
11608
11691
  });
11609
- this.configs.set(id, config);
11692
+ this.configs.set(id, loading);
11610
11693
  }
11611
11694
  return config;
11612
11695
  }
@@ -11731,11 +11814,13 @@ var AtscriptRepo = class {
11731
11814
  * .as Documents cache
11732
11815
  */ _define_property$1(this, "atscripts", void 0);
11733
11816
  _define_property$1(this, "sharedPluginManager", void 0);
11817
+ /** The shared plugin manager once its plugins' `config` hooks ran (see `loadPluginManagerFor`). */ _define_property$1(this, "sharedPluginManagerReady", void 0);
11734
11818
  /**
11735
11819
  * Maps resolved file:// URIs back to bare specifiers (for LSP auto-import).
11736
11820
  */ _define_property$1(this, "resolvedToBare", void 0);
11737
11821
  /**
11738
- * cache for raw content of config files
11822
+ * The plugin manager of each config file (by path), shared by every document under it: its
11823
+ * plugins' `config` hooks run once per load of the file. Dropping an entry loads the file again.
11739
11824
  */ _define_property$1(this, "configFiles", void 0);
11740
11825
  this.root = root;
11741
11826
  this.sharedConfig = sharedConfig;
@@ -11782,9 +11867,11 @@ function _define_property(obj, key, value) {
11782
11867
  }
11783
11868
  /** Upper bound on concurrent file operations — macOS defaults `ulimit -n` to 256. */ const WRITE_CONCURRENCY = 32;
11784
11869
  async function build(config) {
11785
- const rootDir = config.rootDir ? config.rootDir.startsWith("/") ? config.rootDir : path.join(process.cwd(), config.rootDir) : process.cwd();
11870
+ const rootDir = config.rootDir ? path.isAbsolute(config.rootDir) ? config.rootDir : path.join(process.cwd(), config.rootDir) : process.cwd();
11786
11871
  config.rootDir = rootDir;
11787
11872
  const repo = new AtscriptRepo(rootDir, config);
11873
+ const { manager } = await repo.loadPluginManagerFor(`file://${rootDir}`);
11874
+ await manager.buildStart();
11788
11875
  const entries = [];
11789
11876
  if (config.entries && config.entries.length > 0) for (const entry of config.entries) entries.push(path.join(rootDir, entry));
11790
11877
  else {
@@ -11874,7 +11961,7 @@ let tmpSeq = 0;
11874
11961
  await rename(tmp, target);
11875
11962
  } catch (error) {
11876
11963
  try {
11877
- await rm(tmp, { force: true });
11964
+ await rm$1(tmp, { force: true });
11878
11965
  } catch {}
11879
11966
  throw error;
11880
11967
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/core",
3
- "version": "0.2.17",
3
+ "version": "0.2.19",
4
4
  "description": "Core library for Atscript parsing and file generation.",
5
5
  "keywords": [
6
6
  "annotations",