@ttsc/unplugin 0.30.2 → 0.30.4

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.
@@ -2,136 +2,774 @@
2
2
 
3
3
  var fs = require('node:fs');
4
4
  var path = require('node:path');
5
+ var pathIdentity = require('ttsc/path-identity');
5
6
  var transform = require('./transform.js');
6
7
 
7
8
  /**
8
- * How often each registered Vite-unsafe input is predicate-polled, in
9
- * milliseconds.
9
+ * A bounded recursive filesystem observer shared by all served modules.
10
10
  *
11
- * Polling is the only watch primitive that covers the whole class: the dev
12
- * server's chokidar watcher ignores every `node_modules` directory, which is
13
- * exactly where superseding resolution candidates usually live, and `fs.watch`
14
- * cannot observe a path whose parent directories do not exist yet. One `stat`
15
- * every half second per unavailable path is negligible against a dev server's
16
- * baseline. Rich inputs replay only the predicates the compiler recorded.
11
+ * Vite resolves transform-context addWatchFile as a runtime import, including
12
+ * type-only .server files and non-module plugin assets. Use a separate watcher
13
+ * for compiler inputs, including node_modules, which Vite's watcher ignores.
14
+ * Ordinary files use events after their initial subscription is observed.
15
+ * Missing spellings and directory predicates use the recursive observer for
16
+ * their nearest available scope. Inputs a native scope cannot safely cover
17
+ * share one bounded fallback poll; linked files also share topology checks
18
+ * because retargeting a junction need not emit events on its old descendants.
17
19
  */
18
- const MISSING_INPUT_POLL_INTERVAL = 500;
19
- /** Create an empty missing-input watch for one plugin instance. */
20
- function createViteServeMissingInputWatch() {
20
+ function createViteServeInputWatch(operations = {}) {
21
21
  const entries = new Map();
22
- let poller;
22
+ const aliases = new Map();
23
+ const renameAliases = new Map();
24
+ const importerInputs = new Map();
25
+ const pending = new Set();
26
+ const polled = new Set();
27
+ const links = new Map();
28
+ const scopes = new Map();
29
+ const componentLinks = new Map();
30
+ const missingComponents = new Set();
31
+ const changes = new Map();
23
32
  let server;
24
- const stopPollingIfEmpty = () => {
25
- if (entries.size !== 0 || poller === undefined) {
26
- return;
33
+ let projectRoot;
34
+ let changeSequence = 0;
35
+ let historyFloor = 0;
36
+ let linkIterator;
37
+ let pollIterator;
38
+ let poller;
39
+ let flushTimer;
40
+ const open = operations.watch ?? openRecursiveWatch;
41
+ const openPoller = operations.poll ?? openWatchPoller;
42
+ const platform = operations.platform ?? process.platform;
43
+ const createCaseIdentities = () => pathIdentity.createFilesystemPathIdentityContext({
44
+ ...(operations.caseSensitive === undefined
45
+ ? {}
46
+ : { caseSensitive: operations.caseSensitive }),
47
+ platform,
48
+ throwOnRealpathError: false,
49
+ });
50
+ let caseIdentities = createCaseIdentities();
51
+ const directoryCaseSensitivity = new Map();
52
+ let pathIdentityMemosDirty = false;
53
+ /** Drop path facts after topology or ownership changes make them stale. */
54
+ const resetPathIdentityMemos = () => {
55
+ caseIdentities = createCaseIdentities();
56
+ directoryCaseSensitivity.clear();
57
+ pathIdentityMemosDirty = false;
58
+ };
59
+ /** Lexical event key under the nearest existing directory's case policy. */
60
+ const watchPathKey = (file) => {
61
+ const absolute = path.resolve(file);
62
+ if (platform !== "win32" && platform !== "darwin") {
63
+ return absolute;
64
+ }
65
+ let current = path.dirname(absolute);
66
+ const traversed = [];
67
+ let sensitive;
68
+ for (;;) {
69
+ const cacheKey = platform === "win32" ? current.toLowerCase() : current;
70
+ sensitive = directoryCaseSensitivity.get(cacheKey);
71
+ if (sensitive !== undefined)
72
+ break;
73
+ traversed.push(cacheKey);
74
+ try {
75
+ if (fs.statSync(current).isDirectory()) {
76
+ sensitive = caseIdentities.caseSensitive(current);
77
+ break;
78
+ }
79
+ }
80
+ catch {
81
+ // A missing suffix inherits the nearest existing ancestor's policy.
82
+ }
83
+ const parent = path.dirname(current);
84
+ if (parent === current) {
85
+ // The shared identity resolver uses the platform default when even the
86
+ // volume root cannot answer the read-only case-sensitivity probe.
87
+ sensitive = caseIdentities.caseSensitive(current);
88
+ break;
89
+ }
90
+ current = parent;
91
+ }
92
+ for (const directory of traversed) {
93
+ directoryCaseSensitivity.set(directory, sensitive);
94
+ }
95
+ return sensitive ? absolute : absolute.toLowerCase();
96
+ };
97
+ const unbindAlias = (alias, entry) => {
98
+ const indexed = aliases.get(alias);
99
+ indexed?.delete(entry);
100
+ if (indexed?.size === 0)
101
+ aliases.delete(alias);
102
+ };
103
+ const closeScope = (scope) => {
104
+ scopes.delete(watchPathKey(scope.root));
105
+ try {
106
+ scope.watcher?.close();
107
+ }
108
+ catch {
109
+ // The generation no longer trusts this scope, so cleanup is best effort.
110
+ }
111
+ scope.watcher = undefined;
112
+ };
113
+ const recordChange = (eventType, file) => {
114
+ const absolute = path.resolve(file);
115
+ const parent = path.dirname(absolute);
116
+ const direct = new Set();
117
+ const parents = new Set();
118
+ if (eventType === "rename") {
119
+ // Keep the active identity context until affected entries are removed.
120
+ // Their alias and scope indexes were built with that context; changing
121
+ // only the resolver here could make later events unable to reach them.
122
+ // `check()` resets the memos atomically if this topology change removes
123
+ // an entry, while unrelated renames leave still-valid indexes intact.
124
+ componentLinks.clear();
125
+ missingComponents.clear();
126
+ }
127
+ changeSequence += 1;
128
+ direct.add(watchPathKey(absolute));
129
+ parents.add(watchPathKey(parent));
130
+ for (const key of direct) {
131
+ componentLinks.delete(key);
132
+ missingComponents.delete(key);
133
+ changes.set(key, changeSequence);
27
134
  }
28
- clearInterval(poller);
29
- poller = undefined;
135
+ for (const key of parents)
136
+ changes.set(key, changeSequence);
137
+ if (changes.size > MAX_CHANGE_HISTORY) {
138
+ changes.clear();
139
+ historyFloor = changeSequence;
140
+ }
141
+ return { direct, parent: parents };
30
142
  };
31
- const poll = () => {
143
+ const remove = (entry) => {
144
+ entries.delete(entry.file);
145
+ pending.delete(entry);
146
+ polled.delete(entry);
147
+ for (const alias of entry.aliases)
148
+ unbindAlias(alias, entry);
149
+ entry.aliases.clear();
150
+ for (const alias of entry.renameAliases) {
151
+ const indexed = renameAliases.get(alias);
152
+ indexed?.delete(entry);
153
+ if (indexed?.size === 0)
154
+ renameAliases.delete(alias);
155
+ }
156
+ entry.renameAliases.clear();
157
+ for (const scope of entry.scopes) {
158
+ scope.entries.delete(entry);
159
+ if (scope.entries.size === 0 && !scope.pinned)
160
+ closeScope(scope);
161
+ }
162
+ entry.scopes.clear();
163
+ for (const file of entry.links) {
164
+ const link = links.get(file);
165
+ link?.inputs.delete(entry);
166
+ if (link?.inputs.size === 0)
167
+ links.delete(file);
168
+ }
169
+ entry.links.clear();
170
+ // Component resolution is only an observation-time optimization. Entries
171
+ // can introduce arbitrary missing ancestors, so discard the shared memo
172
+ // when one leaves rather than retaining its path components indefinitely.
173
+ componentLinks.clear();
174
+ missingComponents.clear();
175
+ if (links.size === 0)
176
+ linkIterator = undefined;
177
+ if (polled.size === 0)
178
+ pollIterator = undefined;
179
+ pathIdentityMemosDirty = true;
180
+ };
181
+ const check = (selected) => {
32
182
  const importers = new Set();
33
- for (const [identity, entry] of entries) {
34
- if (!viteServeInputWatchConditionChanged(entry)) {
183
+ for (const entry of selected) {
184
+ if (entries.get(entry.file) !== entry)
35
185
  continue;
186
+ let baseline;
187
+ for (const [key, condition] of entry.conditions) {
188
+ const state = condition.evidence?.state;
189
+ let changed;
190
+ if (state?.codec === "predicates") {
191
+ changed =
192
+ transform.validateGraphInputObservation(entry.file, state.observation)
193
+ .length !== 0;
194
+ }
195
+ else {
196
+ baseline ??= transform.captureWatchInputBaseline(entry.file);
197
+ changed =
198
+ baseline === undefined ||
199
+ (condition.evidence?.state !== undefined
200
+ ? !transform.watchInputEvidenceMatchesBaseline(condition.evidence, baseline)
201
+ : JSON.stringify(condition.baseline) !==
202
+ JSON.stringify(baseline));
203
+ }
204
+ if (!changed)
205
+ continue;
206
+ for (const importer of condition.importers)
207
+ importers.add(importer);
208
+ entry.conditions.delete(key);
209
+ }
210
+ if (entry.conditions.size === 0) {
211
+ remove(entry);
36
212
  }
37
- entries.delete(identity);
38
- for (const importer of entry.importers) {
39
- importers.add(importer);
213
+ }
214
+ if (pathIdentityMemosDirty)
215
+ resetPathIdentityMemos();
216
+ updatePoller();
217
+ if (server !== undefined && importers.size !== 0) {
218
+ invalidateImporters(server, importers);
219
+ sendFullReload(server);
220
+ }
221
+ };
222
+ const enqueue = (eventType, file) => {
223
+ const absolute = path.resolve(file);
224
+ const eventKeys = recordChange(eventType, absolute);
225
+ for (const key of eventKeys.direct) {
226
+ for (const entry of aliases.get(key) ?? []) {
227
+ entry.changedAt = changeSequence;
228
+ pending.add(entry);
40
229
  }
41
230
  }
42
- stopPollingIfEmpty();
43
- if (server === undefined || importers.size === 0) {
231
+ for (const key of eventKeys.parent) {
232
+ for (const entry of aliases.get(key) ?? []) {
233
+ entry.changedAt = changeSequence;
234
+ pending.add(entry);
235
+ }
236
+ }
237
+ if (eventType === "rename") {
238
+ const exact = new Set();
239
+ for (const key of eventKeys.direct) {
240
+ for (const entry of renameAliases.get(key) ?? [])
241
+ exact.add(entry);
242
+ }
243
+ // Linux may report only the destination spelling of a directory rename.
244
+ // That spelling cannot be indexed before the move. Fall back to the
245
+ // renamed entry's parent only when no exact old spelling matched; the
246
+ // baseline check below still invalidates solely inputs that really moved.
247
+ const selected = exact;
248
+ if (selected.size === 0) {
249
+ for (const key of eventKeys.parent) {
250
+ for (const entry of renameAliases.get(key) ?? [])
251
+ selected.add(entry);
252
+ }
253
+ }
254
+ for (const entry of selected) {
255
+ entry.changedAt = changeSequence;
256
+ pending.add(entry);
257
+ }
258
+ }
259
+ if (pending.size === 0 || flushTimer !== undefined)
44
260
  return;
261
+ flushTimer = setTimeout(() => {
262
+ flushTimer = undefined;
263
+ const selected = [...pending];
264
+ pending.clear();
265
+ check(selected);
266
+ }, 0);
267
+ flushTimer.unref();
268
+ };
269
+ const bindAlias = (entry, alias) => {
270
+ alias = watchPathKey(alias);
271
+ if (entry.aliases.has(alias))
272
+ return;
273
+ entry.aliases.add(alias);
274
+ let indexed = aliases.get(alias);
275
+ if (indexed === undefined) {
276
+ indexed = new Set();
277
+ aliases.set(alias, indexed);
278
+ }
279
+ indexed.add(entry);
280
+ };
281
+ const bindRenameAncestors = (entry, file) => {
282
+ let current = path.dirname(path.resolve(file));
283
+ for (;;) {
284
+ const key = watchPathKey(current);
285
+ if (!entry.renameAliases.has(key)) {
286
+ entry.renameAliases.add(key);
287
+ let indexed = renameAliases.get(key);
288
+ if (indexed === undefined) {
289
+ indexed = new Set();
290
+ renameAliases.set(key, indexed);
291
+ }
292
+ indexed.add(entry);
293
+ }
294
+ const parent = path.dirname(current);
295
+ if (parent === current)
296
+ return;
297
+ current = parent;
298
+ }
299
+ };
300
+ const ensureScope = (root, external, pinned = false) => {
301
+ root = path.resolve(root);
302
+ const key = watchPathKey(root);
303
+ let scope = scopes.get(key);
304
+ if (scope === undefined) {
305
+ if (external &&
306
+ [...scopes.values()].filter((candidate) => !candidate.pinned).length >=
307
+ MAX_EXTERNAL_WATCH_SCOPES)
308
+ return undefined;
309
+ // Opening a scope is itself an observation boundary. Advance the same
310
+ // sequence returned by begin() so an external scope first discovered
311
+ // after compilation cannot claim it was already live at that token when
312
+ // no filesystem event happened in between.
313
+ changeSequence += 1;
314
+ scope = {
315
+ entries: new Set(),
316
+ failed: false,
317
+ pinned,
318
+ root,
319
+ startedAt: changeSequence,
320
+ };
321
+ scopes.set(key, scope);
322
+ try {
323
+ const owned = scope;
324
+ scope.watcher = open(root, (eventType, file) => {
325
+ if (scopes.get(key) !== owned)
326
+ return;
327
+ if (file === null) {
328
+ resetPathIdentityMemos();
329
+ changeSequence += 1;
330
+ historyFloor = changeSequence;
331
+ changes.clear();
332
+ for (const candidate of owned.entries) {
333
+ candidate.changedAt = changeSequence;
334
+ pending.add(candidate);
335
+ }
336
+ scheduleFlush();
337
+ return;
338
+ }
339
+ enqueue(eventType, path.isAbsolute(file) ? file : path.resolve(root, file));
340
+ }, () => {
341
+ if (scopes.get(key) !== owned)
342
+ return;
343
+ owned.failed = true;
344
+ try {
345
+ owned.watcher?.close();
346
+ }
347
+ catch {
348
+ // The fallback owns validation now; a failed native handle is no
349
+ // longer useful, and cleanup must not replace that recovery.
350
+ }
351
+ owned.watcher = undefined;
352
+ for (const entry of owned.entries)
353
+ requirePolling(entry);
354
+ updatePoller();
355
+ });
356
+ if (scope.failed) {
357
+ // An injected or platform watcher may report failure synchronously
358
+ // during construction, before its handle can be assigned above.
359
+ try {
360
+ scope.watcher?.close();
361
+ }
362
+ catch { }
363
+ scope.watcher = undefined;
364
+ }
365
+ }
366
+ catch {
367
+ scope.failed = true;
368
+ }
369
+ }
370
+ else if (pinned) {
371
+ scope.pinned = true;
372
+ }
373
+ return scope;
374
+ };
375
+ const bindScope = (root, entry, external) => {
376
+ const scope = ensureScope(root, external);
377
+ if (scope === undefined)
378
+ return false;
379
+ scope.entries.add(entry);
380
+ entry.scopes.add(scope);
381
+ return !scope.failed;
382
+ };
383
+ function requirePolling(entry) {
384
+ entry.fallback = true;
385
+ if (polled.size === 0)
386
+ pollIterator = undefined;
387
+ polled.add(entry);
388
+ }
389
+ const scheduleFlush = () => {
390
+ if (pending.size === 0 || flushTimer !== undefined)
391
+ return;
392
+ flushTimer = setTimeout(() => {
393
+ flushTimer = undefined;
394
+ const selected = [...pending];
395
+ pending.clear();
396
+ check(selected);
397
+ }, 0);
398
+ flushTimer.unref();
399
+ };
400
+ function updatePoller() {
401
+ const needed = links.size !== 0 || polled.size !== 0;
402
+ if (!needed) {
403
+ poller?.close();
404
+ poller = undefined;
405
+ return;
406
+ }
407
+ if (poller !== undefined)
408
+ return;
409
+ poller = openPoller(() => {
410
+ const selected = new Set();
411
+ for (let count = 0; count < MAX_FALLBACK_PROBES_PER_TICK && polled.size !== 0; count += 1) {
412
+ pollIterator ??= polled.values();
413
+ let next = pollIterator.next();
414
+ if (next.done) {
415
+ pollIterator = polled.values();
416
+ next = pollIterator.next();
417
+ }
418
+ if (next.done)
419
+ break;
420
+ selected.add(next.value);
421
+ }
422
+ // Files reached through one linked directory share one topology check.
423
+ // Content edits remain event-driven; retargeting a junction does not
424
+ // reliably emit an event on its previously watched descendants. Reconcile
425
+ // a fixed-size slice as a safety net; ordinary retargets arrive at once
426
+ // through the project-root observer, while even an enormous dependency
427
+ // graph has constant idle CPU cost.
428
+ for (let count = 0; count < MAX_LINK_PROBES_PER_TICK && links.size !== 0; count += 1) {
429
+ linkIterator ??= links.entries();
430
+ let next = linkIterator.next();
431
+ if (next.done) {
432
+ linkIterator = links.entries();
433
+ next = linkIterator.next();
434
+ }
435
+ if (next.done)
436
+ break;
437
+ const [file, link] = next.value;
438
+ const target = realpath(file);
439
+ if (target !== link.target) {
440
+ link.target = target;
441
+ for (const entry of link.inputs) {
442
+ selected.add(entry);
443
+ }
444
+ }
445
+ }
446
+ check(selected);
447
+ });
448
+ }
449
+ const observe = (entry) => {
450
+ bindAlias(entry, entry.file);
451
+ bindRenameAncestors(entry, entry.file);
452
+ const root = projectRoot;
453
+ if (root !== undefined && containsPath(root, entry.file)) {
454
+ if (!bindScope(root, entry, false))
455
+ requirePolling(entry);
456
+ }
457
+ else {
458
+ const external = nearestExistingDirectory(entry.file);
459
+ if (external === undefined || !bindScope(external, entry, true))
460
+ requirePolling(entry);
461
+ }
462
+ const target = realpath(entry.file);
463
+ if (hasMultipleLinks(entry.file))
464
+ requirePolling(entry);
465
+ if (target !== undefined) {
466
+ bindAlias(entry, target);
467
+ bindRenameAncestors(entry, target);
468
+ if (!sameSpelling(entry.file, target)) {
469
+ let link = links.get(entry.file);
470
+ if (link === undefined) {
471
+ link = { target, inputs: new Set() };
472
+ if (links.size === 0)
473
+ linkIterator = undefined;
474
+ links.set(entry.file, link);
475
+ }
476
+ link.inputs.add(entry);
477
+ entry.links.add(entry.file);
478
+ if (root === undefined || !containsPath(root, target)) {
479
+ const targetRoot = nearestExistingDirectory(target);
480
+ if (targetRoot === undefined || !bindScope(targetRoot, entry, true))
481
+ requirePolling(entry);
482
+ }
483
+ }
484
+ }
485
+ if (root !== undefined) {
486
+ for (const linkedFile of linkedComponents(entry.file, root, componentLinks, missingComponents, watchPathKey)) {
487
+ bindAlias(entry, linkedFile);
488
+ let link = links.get(linkedFile);
489
+ if (link === undefined) {
490
+ link = { target: realpath(linkedFile), inputs: new Set() };
491
+ if (links.size === 0)
492
+ linkIterator = undefined;
493
+ links.set(linkedFile, link);
494
+ }
495
+ link.inputs.add(entry);
496
+ entry.links.add(linkedFile);
497
+ if (link.target === undefined)
498
+ requirePolling(entry);
499
+ else if (!containsPath(root, link.target) &&
500
+ !bindScope(link.target, entry, true))
501
+ requirePolling(entry);
502
+ }
45
503
  }
46
- invalidateImporters(server, importers);
47
- sendFullReload(server);
48
504
  };
49
505
  return {
50
506
  attach(next) {
51
507
  server = next;
508
+ projectRoot = path.resolve(next.config?.root ?? process.cwd());
509
+ ensureScope(projectRoot, false, true);
52
510
  },
53
- dispose() {
511
+ begin() {
512
+ return changeSequence;
513
+ },
514
+ async dispose() {
54
515
  entries.clear();
55
- if (poller !== undefined) {
56
- clearInterval(poller);
57
- poller = undefined;
58
- }
59
- // The server reference deliberately survives: `vite.restartServer`
60
- // configures the replacement server (attach) before it closes the old
61
- // one (whose buildEnd runs this dispose), so unsetting it here would
62
- // detach the freshly attached replacement and revive the 500 this
63
- // module exists to prevent. A same-instance `vite build` after a serve
64
- // is instead excluded by the adapter's `config.command` gate.
516
+ aliases.clear();
517
+ renameAliases.clear();
518
+ importerInputs.clear();
519
+ pending.clear();
520
+ polled.clear();
521
+ links.clear();
522
+ componentLinks.clear();
523
+ missingComponents.clear();
524
+ changes.clear();
525
+ linkIterator = undefined;
526
+ pollIterator = undefined;
527
+ poller?.close();
528
+ if (flushTimer !== undefined)
529
+ clearTimeout(flushTimer);
530
+ poller = undefined;
531
+ flushTimer = undefined;
532
+ for (const scope of [...scopes.values()])
533
+ closeScope(scope);
534
+ resetPathIdentityMemos();
535
+ // Retain the attached server across overlapping Vite restart containers.
65
536
  },
66
- serving() {
67
- return server !== undefined;
537
+ forget(importer) {
538
+ importer = path.resolve(importer);
539
+ const previous = importerInputs.get(importer);
540
+ if (previous === undefined)
541
+ return;
542
+ importerInputs.delete(importer);
543
+ for (const [file, key] of previous) {
544
+ const entry = entries.get(file);
545
+ const condition = entry?.conditions.get(key);
546
+ condition?.importers.delete(importer);
547
+ if (condition?.importers.size === 0)
548
+ entry?.conditions.delete(key);
549
+ if (entry?.conditions.size === 0)
550
+ remove(entry);
551
+ }
552
+ if (pathIdentityMemosDirty)
553
+ resetPathIdentityMemos();
554
+ updatePoller();
68
555
  },
69
- watch(input, importer, condition) {
70
- const spelling = path.resolve(input);
71
- const identity = viteServeMissingInputWatchKey(spelling, condition);
72
- const existing = entries.get(identity);
73
- if (existing !== undefined) {
74
- existing.importers.add(path.resolve(importer));
556
+ replace(importer, inputs, failed = false, startedAt) {
557
+ if (server === undefined)
75
558
  return;
559
+ importer = path.resolve(importer);
560
+ const previous = importerInputs.get(importer) ?? new Map();
561
+ if (failed) {
562
+ // An exception can omit the dependency whose deletion caused it.
563
+ // Keep the last successful spellings until a successful delivery can
564
+ // replace them, observing their current failed state for recovery.
565
+ const reported = new Set(inputs.map((input) => path.resolve(input.file)));
566
+ inputs = [
567
+ ...inputs,
568
+ ...[...previous.keys()]
569
+ .filter((file) => !reported.has(file))
570
+ .map((file) => ({ file })),
571
+ ];
572
+ }
573
+ const current = new Map();
574
+ const added = new Set();
575
+ const touched = new Set();
576
+ for (const input of inputs) {
577
+ const file = path.resolve(input.file);
578
+ const evidence = input.evidence;
579
+ const key = JSON.stringify(evidence ?? null);
580
+ current.set(file, key);
581
+ let entry = entries.get(file);
582
+ if (entry === undefined) {
583
+ entry = {
584
+ aliases: new Set(),
585
+ changedAt: 0,
586
+ file,
587
+ conditions: new Map(),
588
+ fallback: false,
589
+ links: new Set(),
590
+ renameAliases: new Set(),
591
+ scopes: new Set(),
592
+ };
593
+ entries.set(file, entry);
594
+ added.add(entry);
595
+ observe(entry);
596
+ }
597
+ touched.add(entry);
598
+ let condition = entry.conditions.get(key);
599
+ if (condition === undefined) {
600
+ condition = {
601
+ evidence,
602
+ baseline: evidence?.state === undefined
603
+ ? transform.captureWatchInputBaseline(file)
604
+ : undefined,
605
+ importers: new Set(),
606
+ };
607
+ entry.conditions.set(key, condition);
608
+ }
609
+ condition.importers.add(importer);
610
+ }
611
+ for (const [file, key] of previous) {
612
+ if (current.get(file) === key)
613
+ continue;
614
+ const entry = entries.get(file);
615
+ const condition = entry?.conditions.get(key);
616
+ condition?.importers.delete(importer);
617
+ if (condition?.importers.size === 0)
618
+ entry?.conditions.delete(key);
619
+ if (entry?.conditions.size === 0 && !current.has(file)) {
620
+ remove(entry);
621
+ }
76
622
  }
77
- entries.set(identity, {
78
- condition,
79
- importers: new Set([path.resolve(importer)]),
80
- spelling,
81
- });
82
- if (poller === undefined) {
83
- poller = setInterval(poll, MISSING_INPUT_POLL_INTERVAL);
84
- // A poller must never keep the dev-server process alive on its own.
85
- poller.unref?.();
623
+ if (pathIdentityMemosDirty)
624
+ resetPathIdentityMemos();
625
+ if (current.size === 0)
626
+ importerInputs.delete(importer);
627
+ else
628
+ importerInputs.set(importer, current);
629
+ // Registration and removal can each touch thousands of compiler inputs.
630
+ // Decide the one shared poller's state once per atomic replacement,
631
+ // rather than rescanning the whole graph once per input.
632
+ updatePoller();
633
+ // Watchers are live before this proof. It closes the compile-to-subscribe
634
+ // race without manufacturing one native subscription per input.
635
+ if (touched.size !== 0) {
636
+ if (startedAt === undefined || startedAt < historyFloor) {
637
+ check(touched);
638
+ }
639
+ else {
640
+ const raced = [];
641
+ for (const entry of touched) {
642
+ if (entry.fallback || entry.changedAt > startedAt) {
643
+ raced.push(entry);
644
+ continue;
645
+ }
646
+ const observedAfterCompile = added.has(entry) &&
647
+ (someSet(entry.aliases, (alias) => (changes.get(alias) ?? 0) > startedAt) ||
648
+ someSet(entry.renameAliases, (alias) => (changes.get(alias) ?? 0) > startedAt));
649
+ if (someSet(entry.scopes, (scope) => scope.failed ||
650
+ scope.startedAt > startedAt ||
651
+ observedAfterCompile)) {
652
+ raced.push(entry);
653
+ }
654
+ }
655
+ if (raced.length !== 0)
656
+ check(raced);
657
+ }
86
658
  }
87
659
  },
88
660
  };
89
661
  }
90
- /** Key a private poll by predicate and exact lexical spelling. */
91
- function viteServeMissingInputWatchKey(input, condition) {
92
- // Missing aliases can share a physical parent now and later retarget or
93
- // diverge. Neither predicate may let one lexical spelling answer for another.
94
- const predicate = typeof condition === "string"
95
- ? condition
96
- : `predicates:${JSON.stringify([
97
- condition.accessibleEntries === undefined
98
- ? null
99
- : [
100
- condition.accessibleEntries.directories,
101
- condition.accessibleEntries.files,
102
- ],
103
- condition.directoryExists ?? null,
104
- condition.fileExists ?? null,
105
- condition.readFile === undefined
106
- ? null
107
- : condition.readFile.ok
108
- ? [true, condition.readFile.hash]
109
- : [false],
110
- condition.realpath === undefined
111
- ? null
112
- : condition.realpath.ok
113
- ? [true, condition.realpath.path]
114
- : [false],
115
- condition.stat ?? null,
116
- ])}`;
117
- return `${predicate}:${path.resolve(input)}`;
662
+ const MAX_EXTERNAL_WATCH_SCOPES = 16;
663
+ const MAX_CHANGE_HISTORY = 100_000;
664
+ const MAX_FALLBACK_PROBES_PER_TICK = 64;
665
+ const MAX_LINK_PROBES_PER_TICK = 64;
666
+ /** Test a set without allocating a transient array on the registration path. */
667
+ function someSet(values, predicate) {
668
+ for (const value of values)
669
+ if (predicate(value))
670
+ return true;
671
+ return false;
118
672
  }
119
- /** Whether one registered condition no longer describes its lexical path. */
120
- function viteServeInputWatchConditionChanged(entry) {
121
- if (typeof entry.condition !== "string") {
122
- return (transform.validateGraphInputObservation(entry.spelling, entry.condition).length !==
123
- 0);
124
- }
673
+ function openWatchPoller(listener) {
674
+ const timer = setInterval(listener, 500);
675
+ timer.unref();
676
+ return { close: () => clearInterval(timer) };
677
+ }
678
+ function openRecursiveWatch(root, listener, onError) {
679
+ const watcher = fs.watch(root, { persistent: false, recursive: true }, (eventType, file) => listener(eventType, file === null ? null : String(file)));
680
+ watcher.on("error", onError);
681
+ return { close: () => watcher.close() };
682
+ }
683
+ function containsPath(root, file) {
684
+ const relative = path.relative(path.resolve(root), path.resolve(file));
685
+ return (relative === "" ||
686
+ (relative !== ".." &&
687
+ !relative.startsWith(`..${path.sep}`) &&
688
+ !path.isAbsolute(relative)));
689
+ }
690
+ function nearestExistingDirectory(file) {
691
+ let current = path.resolve(file);
125
692
  try {
126
- if (!fs.existsSync(entry.spelling)) {
127
- return false;
693
+ if (!fs.statSync(current).isDirectory())
694
+ current = path.dirname(current);
695
+ }
696
+ catch {
697
+ current = path.dirname(current);
698
+ }
699
+ for (;;) {
700
+ try {
701
+ if (fs.statSync(current).isDirectory()) {
702
+ return path.dirname(current) === current ? undefined : current;
703
+ }
704
+ }
705
+ catch {
706
+ // Keep climbing to the nearest directory a recursive watch can own.
128
707
  }
129
- return (entry.condition === "exists" || !fs.statSync(entry.spelling).isDirectory());
708
+ const parent = path.dirname(current);
709
+ if (parent === current)
710
+ return undefined;
711
+ current = parent;
712
+ }
713
+ }
714
+ function linkedComponents(file, root, cached, missing, keyOf) {
715
+ const relative = path.relative(root, file);
716
+ if (relative === "" ||
717
+ relative === ".." ||
718
+ relative.startsWith(`..${path.sep}`) ||
719
+ path.isAbsolute(relative))
720
+ return [];
721
+ const output = [];
722
+ let current = path.resolve(root);
723
+ for (const component of relative.split(path.sep).slice(0, -1)) {
724
+ current = path.join(current, component);
725
+ const key = keyOf(current);
726
+ if (missing.has(key))
727
+ break;
728
+ const known = cached.get(key);
729
+ if (known !== undefined) {
730
+ if (known !== null)
731
+ output.push(current);
732
+ continue;
733
+ }
734
+ try {
735
+ if (fs.lstatSync(current).isSymbolicLink()) {
736
+ cached.set(key, realpath(current) ?? current);
737
+ output.push(current);
738
+ }
739
+ else {
740
+ cached.set(key, null);
741
+ }
742
+ }
743
+ catch {
744
+ missing.add(key);
745
+ break;
746
+ }
747
+ }
748
+ return output;
749
+ }
750
+ function realpath(file) {
751
+ try {
752
+ return fs.realpathSync.native(file);
753
+ }
754
+ catch {
755
+ return undefined;
756
+ }
757
+ }
758
+ /** Whether writes can reach this input through an unobserved hardlink alias. */
759
+ function hasMultipleLinks(file) {
760
+ try {
761
+ const stats = fs.statSync(file);
762
+ return stats.isFile() && stats.nlink > 1;
130
763
  }
131
764
  catch {
132
765
  return false;
133
766
  }
134
767
  }
768
+ function sameSpelling(left, right) {
769
+ return process.platform === "win32"
770
+ ? path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase()
771
+ : path.resolve(left) === path.resolve(right);
772
+ }
135
773
  /**
136
774
  * Invalidate every module-graph node of the registered importers so the next
137
775
  * request retransforms them. Importers keep their original absolute spelling so
@@ -216,6 +854,5 @@ function sendFullReload(server) {
216
854
  }
217
855
  }
218
856
 
219
- exports.createViteServeMissingInputWatch = createViteServeMissingInputWatch;
220
- exports.viteServeMissingInputWatchKey = viteServeMissingInputWatchKey;
857
+ exports.createViteServeInputWatch = createViteServeInputWatch;
221
858
  //# sourceMappingURL=viteServe.js.map