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