unplugin-atscript 0.1.109 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -35,6 +35,10 @@ let _atscript_typescript = require("@atscript/typescript");
35
35
  let unplugin = require("unplugin");
36
36
 
37
37
  //#region packages/unplugin/src/index.ts
38
+ /** `true` when Vite is loading the module for a server (SSR) build / environment. */ function isServerLoad(ctx, options) {
39
+ if (options?.ssr === true) return true;
40
+ return ctx?.environment?.config?.consumer === "server";
41
+ }
38
42
  const RE_DTS = /\.d\.[cm]?ts$/;
39
43
  const RUNTIME_ENTRY = "@atscript/typescript/utils";
40
44
  /**
@@ -65,17 +69,228 @@ function isResolvableFrom(specifier, from) {
65
69
  return false;
66
70
  }
67
71
  }
68
- const unpluginFactory = (opts) => {
72
+ /** The modules of `files` in `graph`. */ function modulesOf(graph, files) {
73
+ const out = [];
74
+ for (const file of files) out.push(...graph.getModulesByFile(file) ?? []);
75
+ return out;
76
+ }
77
+ /**
78
+ * Hard-invalidates (drops the transform of) the modules of `files` in every module graph of
79
+ * `server`: Vite reuses an importer's transform when one of its imports changed (soft
80
+ * invalidation), and the next import re-runs `load` only for a module invalidated this way.
81
+ */ function invalidateFiles(server, files) {
82
+ const graphs = server.environments ? Object.values(server.environments).map((env) => env.moduleGraph) : [server.moduleGraph];
83
+ const timestamp = Date.now();
84
+ for (const graph of graphs) for (const mod of modulesOf(graph, files)) graph.invalidateModule(mod, /* @__PURE__ */ new Set(), timestamp, false, false);
85
+ }
86
+ /** The import statements of generated code (`codes`): what the module graph is made of. */ function importLines(codes) {
87
+ return [...codes].map((code) => code.split("\n").filter((line) => line.startsWith("import ")).join("\n")).join("\n---\n");
88
+ }
89
+ /** The diagnostics `load` logs for `doc` (errors and warnings), as a key (see `logged`). */ function loggedOf(doc) {
90
+ return doc.getDiagMessages().filter((m) => m.severity === 1 || m.severity === 2).map((m) => `${m.severity}:${m.message}`).join("\n");
91
+ }
92
+ /** Whether `doc` has mutating `annotate` blocks. */ function hasBlocks(doc) {
93
+ return !!doc && (0, _atscript_core.hasMutatingAnnotates)(doc);
94
+ }
95
+ /**
96
+ * The files of the modules declaring the types the mutating `annotate` blocks of `doc` annotate
97
+ * (other than its own) — through plain aliases (see `blockTargetDocuments`).
98
+ */ function annotatedModules(doc) {
99
+ const out = /* @__PURE__ */ new Set();
100
+ for (const target of doc ? (0, _atscript_core.blockTargetDocuments)(doc) : []) if (target.id.startsWith("file://")) out.add((0, _atscript_core.fileUriToPath)(target.id));
101
+ return out;
102
+ }
103
+ const unpluginFactory = (opts, meta) => {
69
104
  const explicitRoot = opts?.root ? path.default.resolve(opts.root) : void 0;
70
105
  let detectedRoot;
106
+ /**
107
+ * A one-shot build (Vite's `build` command without `--watch`; Rollup / Rolldown not watching):
108
+ * its renders check the generated modules' loads (`loadCheck`). `undefined` until the bundler
109
+ * says, and for the bundlers that do not.
110
+ */ let building;
111
+ const detects = [
112
+ "vite",
113
+ "rollup",
114
+ "rolldown"
115
+ ].includes(meta?.framework ?? "");
71
116
  const getRoot = () => explicitRoot ?? detectedRoot ?? process.cwd();
72
117
  const strict = opts?.strict ?? true;
73
118
  let repo;
74
119
  let configPromise;
120
+ /** The documents of the `.as` modules loaded, by file. */ const loaded = /* @__PURE__ */ new Map();
121
+ /**
122
+ * What `load` returned for each `.as` module (by file), by render format: its generated code,
123
+ * or the error it threw (see `outcome`).
124
+ */ const served = /* @__PURE__ */ new Map();
125
+ /**
126
+ * The diagnostics each served module's `load` logged (errors and warnings): a module whose
127
+ * diagnostics change (derived from other documents) is loaded again to log them — also when
128
+ * its generated code (or the error it throws: the first one) stays the same (see `loggedOf`).
129
+ */ const logged = /* @__PURE__ */ new Map();
130
+ /**
131
+ * The `.as` modules (by file) importing each `.as` file (by file), as their import specifiers
132
+ * name it — also when it does not exist (a deleted file, one not created yet).
133
+ */ const importers = /* @__PURE__ */ new Map();
134
+ /** The `.as` files each loaded `.as` module imports (see `importers`). */ const importsOf = /* @__PURE__ */ new Map();
135
+ /**
136
+ * The other `.as` modules whose generated code changed with a changed `.as` file (by file,
137
+ * see `watchChange`), for the hot update that follows.
138
+ */ const affected = /* @__PURE__ */ new Map();
139
+ /** The changed `.as` files whose hot update is a full page reload. */ const reload = /* @__PURE__ */ new Set();
140
+ /** The Vite dev server (Vite only). */ let viteServer;
75
141
  const getConfig = () => configPromise ?? (configPromise = (async () => {
76
142
  const p = await (0, _atscript_core.resolveConfigFile)(getRoot());
77
143
  return p ? (0, _atscript_core.loadConfig)(p) : {};
78
144
  })());
145
+ /** Records the `.as` files `doc` (loaded from `file`) imports (see `importers`). */ const recordImports = (file, doc) => {
146
+ for (const imported of importsOf.get(file) ?? []) importers.get(imported)?.delete(file);
147
+ const files = /* @__PURE__ */ new Set();
148
+ for (const id of doc.imports.keys()) if (id.startsWith("file://")) files.add((0, _atscript_core.fileUriToPath)(id));
149
+ for (const imported of files) {
150
+ let set = importers.get(imported);
151
+ if (!set) {
152
+ set = /* @__PURE__ */ new Set();
153
+ importers.set(imported, set);
154
+ }
155
+ set.add(file);
156
+ }
157
+ importsOf.set(file, files);
158
+ };
159
+ /**
160
+ * What `load` returns for `doc` in render `format`: its generated code, or (`error:`) the
161
+ * first error it throws in strict mode. Logs the diagnostics when `report`.
162
+ */ const outcome = async (doc, format, report) => {
163
+ let error = "";
164
+ for (const m of [...doc.getDiagMessages()].reverse()) if (m.severity === 1) {
165
+ if (report) console.log(doc.renderDiagMessage(m, true, true));
166
+ if (strict && !error) error = m.message;
167
+ } else if (m.severity === 2 && report) console.log(doc.renderDiagMessage(m, false, true));
168
+ if (error) return {
169
+ error,
170
+ code: `error:${error}`
171
+ };
172
+ const options = { loadCheck: opts?.loadCheck ?? building };
173
+ let out = await doc.render(format, options);
174
+ if (!out?.[0]?.content && (format === _atscript_typescript.JS_COMPILED_FORMAT || format === _atscript_typescript.JS_INTERPRETED_FORMAT)) out = await doc.render("js", options);
175
+ return { code: out?.[0]?.content || "" };
176
+ };
177
+ /** The repo's document of `uri` as it is now (`undefined`: it does not open). */ const currentDoc = async (uri) => {
178
+ try {
179
+ const doc = await repo.openDocument(uri);
180
+ await repo.checkImports(doc);
181
+ return doc;
182
+ } catch {
183
+ return;
184
+ }
185
+ };
186
+ /**
187
+ * The `.as` modules (by file) importing `id`'s, directly or not, also through an import of it
188
+ * that did not resolve: evaluated again with it in a hot update.
189
+ */ const dependantsOf = (id) => {
190
+ const files = /* @__PURE__ */ new Set();
191
+ const add = (doc) => {
192
+ for (const d of doc?.transitive("dependants") ?? []) files.add((0, _atscript_core.fileUriToPath)(d.id));
193
+ };
194
+ add(loaded.get(id));
195
+ for (const file of importers.get(id) ?? []) {
196
+ files.add(file);
197
+ add(loaded.get(file));
198
+ }
199
+ files.delete(id);
200
+ return files;
201
+ };
202
+ const candidatesOf = (id) => {
203
+ const files = dependantsOf(id);
204
+ const uri = `file://${id}`;
205
+ for (const [file, ids] of reads) if (ids.has(uri)) files.add(file);
206
+ files.delete(id);
207
+ return files;
208
+ };
209
+ /**
210
+ * The documents (by id) each loaded `.as` module's `load` result was derived from: those its
211
+ * resolutions read (see `recordDocumentReads`) and those it imports.
212
+ */ const reads = /* @__PURE__ */ new Map();
213
+ /** Records `read` (and the documents `doc` imports) as what `file`'s `load` result read. */ const recordReads = (file, doc, read, merge) => {
214
+ const ids = merge ? reads.get(file) ?? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set();
215
+ for (const d of read) ids.add(d.id);
216
+ for (const id of doc.imports.keys()) ids.add(id);
217
+ reads.set(file, ids);
218
+ };
219
+ /**
220
+ * `candidates` (files) whose `load` result changes with document `uri` changed to `text`:
221
+ * the document is updated in place (its importers keep referring to it), and the candidates
222
+ * whose last `load` read it (see `reads`) are rendered again in every format they were loaded
223
+ * in — all of them when its generated imports changed (the import cycles they are in may
224
+ * change), or when a candidate rendered again has new imports. Its importers are parsed
225
+ * and checked again first (their diagnostics are those of its imports as they are now), from
226
+ * the repo's documents (from disk when the repo dropped one: deleted, created again) — never
227
+ * from a closed document; the checks share what they checked (each document's imports once).
228
+ */ const changedModules = async (uri, text, candidates) => {
229
+ const changedFile = (0, _atscript_core.fileUriToPath)(uri);
230
+ const before = served.get(changedFile);
231
+ const beforeImports = before ? importLines(before.values()) : void 0;
232
+ const checked = /* @__PURE__ */ new Set();
233
+ const changedDoc = await repo.openDocument(uri, text);
234
+ await repo.checkImports(changedDoc, checked);
235
+ let all = beforeImports === void 0;
236
+ if (!all) {
237
+ const after = [];
238
+ for (const format of before.keys()) after.push((await outcome(changedDoc, format, false)).code);
239
+ all = importLines(after) !== beforeImports;
240
+ }
241
+ const importing = importers.get(changedFile) ?? /* @__PURE__ */ new Set();
242
+ const changed = /* @__PURE__ */ new Set();
243
+ const docs = /* @__PURE__ */ new Map();
244
+ for (const file of candidates) if (!loaded.has(file) || !served.has(file)) changed.add(file);
245
+ else if (importing.has(file)) try {
246
+ const id = loaded.get(file).id;
247
+ const current = await repo.openDocument(id);
248
+ current.clearMessages();
249
+ docs.set(file, current);
250
+ } catch {
251
+ changed.add(file);
252
+ }
253
+ for (const doc of docs.values()) {
254
+ checked.delete(doc.id);
255
+ await repo.checkImports(doc, checked);
256
+ }
257
+ const rendered = /* @__PURE__ */ new Set();
258
+ const render = async (file) => {
259
+ rendered.add(file);
260
+ const doc = docs.get(file) ?? loaded.get(file);
261
+ if (!docs.has(file)) doc.clearMessages();
262
+ loaded.set(file, doc);
263
+ const formats = served.get(file);
264
+ const recording = (0, _atscript_core.recordDocumentReads)();
265
+ const codes = [];
266
+ try {
267
+ for (const format of formats.keys()) codes.push((await outcome(doc, format, false)).code);
268
+ } finally {
269
+ recordReads(file, doc, recording.stop(), false);
270
+ }
271
+ if (codes.some((code, i) => code !== [...formats.values()][i]) || loggedOf(doc) !== logged.get(file)) {
272
+ changed.add(file);
273
+ if (!all && importLines(codes) !== importLines(formats.values())) all = true;
274
+ }
275
+ };
276
+ const pending = () => [...candidates].filter((file) => !rendered.has(file) && !changed.has(file) && (all || importing.has(file) || !reads.has(file) || reads.get(file).has(uri)));
277
+ for (let queue = pending(); queue.length > 0; queue = pending()) for (const file of queue) await render(file);
278
+ for (const file of staleWarnings(new Set([...rendered, ...changed]))) changed.add(file);
279
+ return changed;
280
+ };
281
+ /**
282
+ * The served modules (but `skip`) whose mutating blocks annotate another module's type and
283
+ * whose diagnostics changed: the warning of a block not reachable from the files using the type
284
+ * derives from documents they need not import (those files, see `blockDependencies`), so it is
285
+ * computed again.
286
+ */ const staleWarnings = (skip) => {
287
+ const out = [];
288
+ for (const [file, doc] of loaded) if (!skip.has(file) && served.has(file) && annotatedModules(doc).size > 0) {
289
+ doc.clearMessages();
290
+ if (loggedOf(doc) !== logged.get(file)) out.push(file);
291
+ }
292
+ return out;
293
+ };
79
294
  return {
80
295
  name: "unplugin-atscript",
81
296
  vite: {
@@ -86,6 +301,26 @@ const unpluginFactory = (opts) => {
86
301
  },
87
302
  configResolved(config) {
88
303
  detectedRoot = config.root;
304
+ building = config.command === "build" && !config.build?.watch;
305
+ },
306
+ configureServer(server) {
307
+ viteServer = server;
308
+ },
309
+ hotUpdate(options) {
310
+ if (reload.has(options.file)) {
311
+ this.environment.hot?.send({ type: "full-reload" });
312
+ return [];
313
+ }
314
+ const files = affected.get(options.file);
315
+ return files && files.size > 0 ? [...new Set([...options.modules, ...modulesOf(this.environment.moduleGraph, files)])] : void 0;
316
+ },
317
+ handleHotUpdate(ctx) {
318
+ if (!ctx.server.environments && reload.has(ctx.file)) {
319
+ ctx.server.ws?.send({ type: "full-reload" });
320
+ return [];
321
+ }
322
+ const files = affected.get(ctx.file);
323
+ return ctx.server.environments || !files || files.size === 0 ? void 0 : [...new Set([...ctx.modules, ...modulesOf(ctx.server.moduleGraph, files)])];
89
324
  }
90
325
  },
91
326
  resolveId(id, importer) {
@@ -96,7 +331,10 @@ const unpluginFactory = (opts) => {
96
331
  return resolved;
97
332
  }
98
333
  },
99
- async load(id) {
334
+ buildStart() {
335
+ if (detects) building ?? (building = this.meta?.watchMode === false);
336
+ },
337
+ async load(id, options) {
100
338
  const isDts = id.endsWith(".as.d.ts");
101
339
  const sourceId = isDts ? id.slice(0, -5) : id;
102
340
  if (sourceId.endsWith(".as")) {
@@ -106,33 +344,83 @@ const unpluginFactory = (opts) => {
106
344
  repo = new _atscript_core.AtscriptRepo(getRoot(), config);
107
345
  }
108
346
  const code = (await (0, fs_promises.readFile)(sourceId, "utf8")).toString();
109
- const doc = await repo.openDocument(`file://${sourceId}`, code);
110
- await repo.checkDoc(doc);
347
+ const recording = isDts ? void 0 : (0, _atscript_core.recordDocumentReads)();
348
+ let doc;
349
+ let result;
350
+ let format = "js";
351
+ try {
352
+ doc = await repo.openDocument(`file://${sourceId}`, code);
353
+ await repo.checkDoc(doc);
354
+ if (!isDts) {
355
+ const compile = opts?.compileValidators;
356
+ format = compile === void 0 ? "js" : compile === true || compile === "ssr" && isServerLoad(this, options) ? _atscript_typescript.JS_COMPILED_FORMAT : _atscript_typescript.JS_INTERPRETED_FORMAT;
357
+ result = await outcome(doc, format, true);
358
+ }
359
+ } finally {
360
+ const read = recording?.stop();
361
+ if (read && doc) recordReads(sourceId, doc, read, served.has(sourceId));
362
+ }
111
363
  addTransitiveWatchFiles(this, doc);
112
- const messages = doc.getDiagMessages().reverse();
113
- let error = "";
114
- for (const m of messages) if (m.severity === 1) {
115
- console.log(doc.renderDiagMessage(m, true, true));
116
- if (strict && !error) error = m.message;
117
- } else if (m.severity === 2) console.log(doc.renderDiagMessage(m, false, true));
118
- if (error) throw new Error(error);
119
- if (isDts) return {
120
- code: ((await doc.render("dts"))?.[0]?.content || "").replace(/^\/{3}\s*<reference\s+path=[^\n]*\n/m, ""),
121
- map: null
122
- };
123
- const out = await doc.render("js");
124
- const hasMutatingAnnotates = doc.nodes.some((n) => (0, _atscript_core.isAnnotate)(n) && n.isMutating);
364
+ if (isDts) {
365
+ const { error, code: content } = await outcome(doc, "dts", true);
366
+ if (error) throw new Error(error);
367
+ return {
368
+ code: content.replace(/^\/{3}\s*<reference\s+path=[^\n]*\n/m, ""),
369
+ map: null
370
+ };
371
+ }
372
+ loaded.set(sourceId, doc);
373
+ recordImports(sourceId, doc);
374
+ let formats = served.get(sourceId);
375
+ if (!formats) {
376
+ formats = /* @__PURE__ */ new Map();
377
+ served.set(sourceId, formats);
378
+ }
379
+ formats.set(format, result.code);
380
+ logged.set(sourceId, loggedOf(doc));
381
+ if (result.error) throw new Error(result.error);
382
+ const sideEffects = hasBlocks(doc) || (0, _atscript_typescript.importCycle)(doc);
125
383
  return {
126
- code: out?.[0]?.content || "",
384
+ code: result.code,
127
385
  moduleType: "js",
128
386
  map: null,
129
- moduleSideEffects: hasMutatingAnnotates ? void 0 : false
387
+ moduleSideEffects: sideEffects ? void 0 : false
130
388
  };
131
389
  }
132
390
  },
133
- watchChange(id) {
391
+ async watchChange(id, change) {
134
392
  if (!repo || !id.endsWith(".as")) return;
135
- repo.closeDocument(`file://${id}`);
393
+ const uri = `file://${id}`;
394
+ const candidates = candidatesOf(id);
395
+ const evaluated = new Set([id, ...dependantsOf(id)]);
396
+ const blocksOutside = () => [...evaluated].some((f) => [...annotatedModules(loaded.get(f))].some((t) => !evaluated.has(t)));
397
+ const blocksBefore = hasBlocks(loaded.get(id)) || blocksOutside();
398
+ const text = viteServer && change?.event === "update" ? await (0, fs_promises.readFile)(id, "utf8").catch(() => void 0) : void 0;
399
+ let files = candidates;
400
+ if (text === void 0) {
401
+ repo.closeDocument(uri);
402
+ files = new Set([...candidates, id]);
403
+ if (change?.event === "create") try {
404
+ await repo.checkImports(await repo.openDocument(uri), /* @__PURE__ */ new Set());
405
+ } catch {
406
+ repo.closeDocument(uri);
407
+ }
408
+ for (const file of staleWarnings(files)) files.add(file);
409
+ } else try {
410
+ files = await changedModules(uri, text, candidates);
411
+ } catch {
412
+ repo.closeDocument(uri);
413
+ }
414
+ if (blocksBefore || hasBlocks(await currentDoc(uri)) || blocksOutside()) {
415
+ files = new Set([
416
+ ...files,
417
+ ...served.keys(),
418
+ id
419
+ ]);
420
+ reload.add(id);
421
+ } else reload.delete(id);
422
+ affected.set(id, files);
423
+ if (viteServer && files.size > 0) invalidateFiles(viteServer, files);
136
424
  }
137
425
  };
138
426
  };
package/dist/index.d.ts CHANGED
@@ -21,6 +21,31 @@ interface atscriptPluginOptions {
21
21
  * config-provided plugins (`@db.*`, `@ui.*`, …) are reported as unknown.
22
22
  */
23
23
  root?: string;
24
+ /**
25
+ * Overrides `tsPlugin({ compileValidators })` of the atscript config for the modules
26
+ * this plugin renders:
27
+ * - `true` — compiled validator checks for every type.
28
+ * - `false` — none, not even for types annotated with `@emit.compiledValidator`
29
+ * (forced interpreted output, e.g. for bundles shipped to browsers).
30
+ * - `'ssr'` — `true` for server builds (Vite's SSR / server environments), `false` for
31
+ * client bundles (one Vite config for both). Bundlers that do not report a server build
32
+ * (everything but Vite) are treated as client builds.
33
+ *
34
+ * Unset: the atscript config decides (default: only `@emit.compiledValidator` types).
35
+ */
36
+ compileValidators?: boolean | 'ssr';
37
+ /**
38
+ * The build's load check: a production build loads every generated module (each import cycle
39
+ * from each of its modules) and fails when one does not load — an internal code generation
40
+ * error, never a half-built module at runtime.
41
+ * - `true` — checked in every build of this plugin (also in watch mode and on the dev server).
42
+ * - `false` — never checked.
43
+ *
44
+ * Unset: checked in one-shot Vite, Rollup and Rolldown builds; not in watch builds
45
+ * (`vite build --watch`, `rollup -w`, `rolldown --watch`), on the dev server or in HMR; not in
46
+ * other bundlers (esbuild, webpack, Rspack, Farm: they do not tell a build from a watch).
47
+ */
48
+ loadCheck?: boolean;
24
49
  }
25
50
  declare const unpluginFactory: UnpluginFactory<atscriptPluginOptions | undefined>;
26
51
  declare const unplugin: _unplugin.UnpluginInstance<atscriptPluginOptions | undefined, boolean>;