@ttsc/unplugin 0.19.3 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,271 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { pathIdentityKey } from "./transform";
5
+
6
+ /**
7
+ * How often each registered missing watch input is stat-polled, in
8
+ * milliseconds.
9
+ *
10
+ * Polling is the only watch primitive that covers the whole class: the dev
11
+ * server's chokidar watcher ignores every `node_modules` directory, which is
12
+ * exactly where superseding resolution candidates usually live, and `fs.watch`
13
+ * cannot observe a path whose parent directories do not exist yet. One `stat`
14
+ * every half second per missing path is negligible against a dev server's
15
+ * baseline.
16
+ */
17
+ const MISSING_INPUT_POLL_INTERVAL = 500;
18
+
19
+ /** One module node inside a Vite module graph; opaque to this module. */
20
+ type ViteModuleNodeLike = object;
21
+
22
+ /**
23
+ * The module-graph surface this module touches, shared by Vite's mixed module
24
+ * graph and the per-environment graphs of the environment API.
25
+ */
26
+ interface ViteModuleGraphLike {
27
+ fileToModulesMap?: Map<string, Set<ViteModuleNodeLike>>;
28
+ getModulesByFile?(file: string): Set<ViteModuleNodeLike> | undefined;
29
+ invalidateModule?(node: ViteModuleNodeLike): void;
30
+ }
31
+
32
+ /** A channel that can deliver a full-reload event to connected clients. */
33
+ interface ViteHotChannelLike {
34
+ send?(payload: { path?: string; type: "full-reload" }): void;
35
+ }
36
+
37
+ /** One dev-server environment (client, ssr, or a custom one). */
38
+ interface ViteEnvironmentLike {
39
+ hot?: ViteHotChannelLike;
40
+ moduleGraph?: ViteModuleGraphLike;
41
+ }
42
+
43
+ /**
44
+ * Minimal structural view of the Vite dev server. Declared locally instead of
45
+ * importing `vite` so the published type declarations never require Vite to be
46
+ * installed, and so one shape spans the mixed module graph (Vite 5), the
47
+ * environment API (Vite 6+), and whichever of `ws`/`hot` a major still
48
+ * carries.
49
+ */
50
+ export interface ViteDevServerLike {
51
+ environments?: Record<string, ViteEnvironmentLike>;
52
+ hot?: ViteHotChannelLike;
53
+ moduleGraph?: ViteModuleGraphLike;
54
+ ws?: ViteHotChannelLike;
55
+ }
56
+
57
+ /**
58
+ * Filesystem watch for derived watch inputs that do not exist while a Vite dev
59
+ * server is running.
60
+ *
61
+ * Vite serve treats every transform-context `addWatchFile()` registration as an
62
+ * added import: `TransformPluginContext.addWatchFile` stores the path in
63
+ * `_addedImports`, and `vite:import-analysis` resolves each entry like a real
64
+ * import of the transformed module. A missing path — a superseding resolution
65
+ * candidate or a plugin-reported dependency that is not generated yet — then
66
+ * fails that resolve and turns the importer's first request into a 500, even
67
+ * though the transform itself succeeded.
68
+ *
69
+ * This registry is the serve-only replacement for those registrations. Each
70
+ * missing path is stat-polled; when it is created, every importer that
71
+ * registered it is invalidated in the server's module graphs and one
72
+ * full-reload is sent, so the next request retransforms the importer against
73
+ * the new resolution winner. The project transform cache re-validates through
74
+ * its external-input hashes (a recorded `missing` marker differs from a content
75
+ * hash), so the retransform recompiles instead of replaying.
76
+ */
77
+ export interface ViteServeMissingInputWatch {
78
+ /** Adopt the dev server whose module graphs creation events invalidate. */
79
+ attach(server: ViteDevServerLike): void;
80
+ /** Stop every poll; safe to call repeatedly. */
81
+ dispose(): void;
82
+ /**
83
+ * Report whether a dev server has ever been attached. This is not a liveness
84
+ * predicate — the reference intentionally survives the server's close (see
85
+ * {@link dispose}) — so route decisions must also gate on the resolved
86
+ * config's `command`, as the adapter does.
87
+ */
88
+ serving(): boolean;
89
+ /** Register one missing watch input derived for `importer`. */
90
+ watch(input: string, importer: string): void;
91
+ }
92
+
93
+ /** Poll bookkeeping for one registered missing path. */
94
+ interface IMissingInputEntry {
95
+ importers: Set<string>;
96
+ listener: (current: fs.Stats) => void;
97
+ spelling: string;
98
+ }
99
+
100
+ /** Create an empty missing-input watch for one plugin instance. */
101
+ export function createViteServeMissingInputWatch(): ViteServeMissingInputWatch {
102
+ const entries = new Map<string, IMissingInputEntry>();
103
+ let server: ViteDevServerLike | undefined;
104
+
105
+ const unwatch = (identity: string, entry: IMissingInputEntry): void => {
106
+ fs.unwatchFile(entry.spelling, entry.listener);
107
+ entries.delete(identity);
108
+ };
109
+
110
+ return {
111
+ attach(next) {
112
+ server = next;
113
+ },
114
+ dispose() {
115
+ for (const [identity, entry] of entries) {
116
+ unwatch(identity, entry);
117
+ }
118
+ // The server reference deliberately survives: `vite.restartServer`
119
+ // configures the replacement server (attach) before it closes the old
120
+ // one (whose buildEnd runs this dispose), so unsetting it here would
121
+ // detach the freshly attached replacement and revive the 500 this
122
+ // module exists to prevent. A same-instance `vite build` after a serve
123
+ // is instead excluded by the adapter's `config.command` gate.
124
+ },
125
+ serving() {
126
+ return server !== undefined;
127
+ },
128
+ watch(input, importer) {
129
+ const spelling = path.resolve(input);
130
+ const identity = pathIdentityKey(spelling);
131
+ const existing = entries.get(identity);
132
+ if (existing !== undefined) {
133
+ existing.importers.add(path.resolve(importer));
134
+ return;
135
+ }
136
+ const entry: IMissingInputEntry = {
137
+ importers: new Set([path.resolve(importer)]),
138
+ listener: (current) => {
139
+ // `fs.watchFile` reports a missing path as zeroed stats (and fires
140
+ // once with them right after registration); only a poll that
141
+ // observes a real file is a creation event.
142
+ if (current.mtimeMs === 0 && !fs.existsSync(entry.spelling)) {
143
+ return;
144
+ }
145
+ unwatch(identity, entry);
146
+ if (server === undefined) {
147
+ return;
148
+ }
149
+ invalidateImporters(server, entry.importers);
150
+ sendFullReload(server);
151
+ },
152
+ spelling,
153
+ };
154
+ entries.set(identity, entry);
155
+ const watcher = fs.watchFile(
156
+ spelling,
157
+ { interval: MISSING_INPUT_POLL_INTERVAL },
158
+ entry.listener,
159
+ );
160
+ // A poller must never keep the dev-server process alive on its own.
161
+ watcher.unref?.();
162
+ // `fs.watchFile` snapshots the path's stats at registration and fires
163
+ // only on a subsequent change, so a file created between the adapter's
164
+ // existence check and this registration would count as "unchanged" and
165
+ // never fire. One deferred recheck closes that window; routing through
166
+ // the listener keeps a single finalization path.
167
+ const recheck = setTimeout(() => {
168
+ if (entries.get(identity) !== entry) {
169
+ return;
170
+ }
171
+ try {
172
+ entry.listener(fs.statSync(entry.spelling));
173
+ } catch {
174
+ // Still missing (or deleted again): the ordinary poll stays armed.
175
+ }
176
+ }, MISSING_INPUT_POLL_INTERVAL);
177
+ recheck.unref?.();
178
+ },
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Invalidate every module-graph node of the registered importers so the next
184
+ * request retransforms them. Importers keep their original absolute spelling so
185
+ * the module graph's exact-key lookup can hit; graph lookups still go through
186
+ * {@link selectModulesByFile} because module-graph file keys are
187
+ * slash-normalized and, on case-insensitive filesystems, may not match the
188
+ * compiler's spelling byte for byte.
189
+ */
190
+ function invalidateImporters(
191
+ server: ViteDevServerLike,
192
+ importers: ReadonlySet<string>,
193
+ ): void {
194
+ for (const graph of selectModuleGraphs(server)) {
195
+ for (const importer of importers) {
196
+ for (const node of selectModulesByFile(graph, importer)) {
197
+ try {
198
+ graph.invalidateModule?.(node);
199
+ } catch {
200
+ // A graph shape this structural view mispredicts must not crash the
201
+ // poll; the full-reload below still forces a refetch, and the
202
+ // transform cache's external-input hashes force the recompile.
203
+ }
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Enumerate the server's module graphs: one per environment under the
211
+ * environment API (Vite 6+), otherwise the mixed module graph (Vite 5).
212
+ */
213
+ function selectModuleGraphs(server: ViteDevServerLike): ViteModuleGraphLike[] {
214
+ const graphs: ViteModuleGraphLike[] = [];
215
+ for (const environment of Object.values(server.environments ?? {})) {
216
+ if (environment?.moduleGraph !== undefined) {
217
+ graphs.push(environment.moduleGraph);
218
+ }
219
+ }
220
+ if (graphs.length === 0 && server.moduleGraph !== undefined) {
221
+ graphs.push(server.moduleGraph);
222
+ }
223
+ return graphs;
224
+ }
225
+
226
+ /**
227
+ * Look up the module nodes registered for one importer spelling: the fast
228
+ * slash-normalized `getModulesByFile` lookup first, then an identity scan of
229
+ * `fileToModulesMap` for spellings that differ only by separator or case.
230
+ */
231
+ function selectModulesByFile(
232
+ graph: ViteModuleGraphLike,
233
+ importer: string,
234
+ ): ViteModuleNodeLike[] {
235
+ const direct = graph.getModulesByFile?.(importer.replace(/\\/g, "/"));
236
+ if (direct !== undefined && direct.size !== 0) {
237
+ return [...direct];
238
+ }
239
+ const identity = pathIdentityKey(importer);
240
+ const output: ViteModuleNodeLike[] = [];
241
+ for (const [file, nodes] of graph.fileToModulesMap ?? []) {
242
+ if (typeof file === "string" && pathIdentityKey(file) === identity) {
243
+ output.push(...nodes);
244
+ }
245
+ }
246
+ return output;
247
+ }
248
+
249
+ /**
250
+ * Deliver one full-reload so connected clients refetch the invalidated
251
+ * importers. The channels differ across Vite majors (`ws`, deprecated `hot`,
252
+ * per-environment `hot`); the first one that accepts the payload wins.
253
+ */
254
+ function sendFullReload(server: ViteDevServerLike): void {
255
+ for (const channel of [
256
+ server.ws,
257
+ server.hot,
258
+ server.environments?.client?.hot,
259
+ ]) {
260
+ if (channel?.send === undefined) {
261
+ continue;
262
+ }
263
+ try {
264
+ channel.send({ path: "*", type: "full-reload" });
265
+ return;
266
+ } catch {
267
+ // Try the next channel; an unsupported payload on one major must not
268
+ // suppress delivery through another.
269
+ }
270
+ }
271
+ }