@stencil/unplugin 5.0.0-beta.8 → 5.0.0-rc.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.mjs CHANGED
@@ -1,113 +1,10 @@
1
- import { existsSync, readFileSync, readdirSync } from "node:fs";
2
- import { dirname, extname, join, resolve } from "node:path";
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, extname, join, normalize, resolve } from "node:path";
3
3
  import { createFilter } from "@rollup/pluginutils";
4
- import { cmpMetaToDocsComponent, generateManifest, getScopeId, scopeCss, transpile, transpileSync } from "@stencil/core/compiler";
4
+ import { buildHydrateCss, cmpMetaToDocsComponent, foldBuildFlags, generateComponentTypesFile, generateManifest, getScopeId, parseCssOnlyComponents, scopeCss, transpile, transpileSync, ts, validateHydrated } from "@stencil/core/compiler";
5
5
  import { createUnplugin } from "unplugin";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { isPackageExists } from "local-pkg";
8
- import ts from "typescript";
9
- //#region src/config.ts
10
- /**
11
- * Stencil config auto-detection for @stencil/unplugin.
12
- *
13
- * Searches for a `stencil.config.ts` (or `.js` variant) in the project root,
14
- * loads it via jiti (so TypeScript is handled without a separate compile step),
15
- * and extracts the subset of flags that are meaningful at transpile time.
16
- *
17
- * `stencilConfigToOverrides` converts that subset to a `BuildOverrides` object
18
- * ready to pass to `transpileSync`.
19
- */
20
- const STENCIL_CONFIG_KEYS = /* @__PURE__ */ new Set([
21
- "namespace",
22
- "srcDir",
23
- "outputTargets",
24
- "plugins",
25
- "signalBacking",
26
- "compat"
27
- ]);
28
- const looksLikeConfig = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.keys(v).some((k) => STENCIL_CONFIG_KEYS.has(k));
29
- const CONFIG_CANDIDATES = [
30
- "stencil.config.ts",
31
- "stencil.config.mts",
32
- "stencil.config.js",
33
- "stencil.config.mjs"
34
- ];
35
- /**
36
- * Attempt to load the project's `stencil.config.ts` and return the
37
- * transpile-relevant fields. Returns `null` if no config file is found or
38
- * if loading fails for any reason.
39
- * @param cwd - project root to search in (usually `process.cwd()`)
40
- * @returns a subset of the Stencil config, or `null` if none is found
41
- */
42
- async function loadStencilConfig(cwd) {
43
- for (const filename of CONFIG_CANDIDATES) {
44
- const configPath = join(cwd, filename);
45
- if (!existsSync(configPath)) continue;
46
- try {
47
- const { createJiti } = await import("jiti");
48
- const mod = await createJiti(import.meta.url).import(configPath);
49
- const raw = mod["config"] ?? (looksLikeConfig(mod["default"]) ? mod["default"] : null);
50
- if (!raw || typeof raw !== "object") return null;
51
- return extractSubset(raw);
52
- } catch {
53
- return null;
54
- }
55
- }
56
- return null;
57
- }
58
- function extractSubset(c) {
59
- const result = {};
60
- if (c["signalBacking"] === true) result.signalBacking = true;
61
- const compat = c["compat"];
62
- if (compat && typeof compat === "object") {
63
- const co = compat;
64
- const ldp = co["lightDomPatches"];
65
- const lifecycleDOMEvents = co["lifecycleDOMEvents"];
66
- const initializeNextTick = co["initializeNextTick"];
67
- if (ldp !== void 0 || lifecycleDOMEvents !== void 0 || initializeNextTick !== void 0) {
68
- result.compat = {};
69
- if (typeof ldp === "boolean") result.compat.lightDomPatches = ldp;
70
- else if (ldp && typeof ldp === "object") result.compat.lightDomPatches = ldp;
71
- if (lifecycleDOMEvents === true) result.compat.lifecycleDOMEvents = true;
72
- if (initializeNextTick === true) result.compat.initializeNextTick = true;
73
- }
74
- }
75
- return result;
76
- }
77
- /**
78
- * Convert a {@link StencilConfigSubset} to a {@link BuildOverrides} object.
79
- * The caller is responsible for merging this with any explicit
80
- * `transpileOptions.buildOverrides` (which should take precedence).
81
- * @param config - the Stencil config subset to convert
82
- * @returns a `BuildOverrides` object suitable for passing to `transpileSync`
83
- */
84
- function stencilConfigToOverrides(config) {
85
- const o = {};
86
- if (config.signalBacking) {
87
- o.signalBacking = true;
88
- o.vdomSignals = true;
89
- }
90
- const compat = config.compat;
91
- if (!compat) return o;
92
- if (compat.lifecycleDOMEvents) o.lifecycleDOMEvents = true;
93
- if (compat.initializeNextTick) o.initializeNextTick = true;
94
- const ldp = compat.lightDomPatches;
95
- if (ldp === false) {
96
- o.lightDomPatches = false;
97
- o.slotChildNodes = false;
98
- o.slotCloneNode = false;
99
- o.slotDomMutations = false;
100
- o.slotTextContent = false;
101
- } else if (typeof ldp === "object") {
102
- o.lightDomPatches = true;
103
- o.slotChildNodes = !!ldp.childNodes;
104
- o.slotCloneNode = !!ldp.cloneNode;
105
- o.slotDomMutations = !!ldp.domMutations;
106
- o.slotTextContent = !!ldp.textContent;
107
- }
108
- return o;
109
- }
110
- //#endregion
111
8
  //#region src/css.ts
112
9
  /**
113
10
  * CSS pipeline for Stencil component stylesheets.
@@ -218,17 +115,47 @@ async function runLightningCss(css, filePath, minify) {
218
115
  }).code.toString();
219
116
  }
220
117
  /**
221
- * Loads a Stencil CSS virtual module.
118
+ * Runs a `.css`/`.scss`/`.sass`/`.less` file through Stencil's preprocessor chain:
119
+ * 1. Preprocessor: Sass/SCSS (`sass`) or Less (`less`) if installed
120
+ * 2. PostCSS with `postcss.config.*` if `postcss` + `postcss-load-config` are installed
121
+ * 3. lightningcss if installed — syntax lowering, vendor prefixes, minification in prod
122
+ * Each step is skipped silently if the relevant peer dep is not installed.
222
123
  *
223
- * Processing order:
224
- * 1. Read raw file
225
- * 2. Preprocessor: Sass/SCSS (`sass`) or Less (`less`) if installed
226
- * 3. PostCSS with `postcss.config.*` if `postcss` + `postcss-load-config` are installed
227
- * 4. lightningcss if installed — syntax lowering, vendor prefixes, minification in prod
228
- * 5. Scoped selector rewrite for `encapsulation: 'scoped'`
124
+ * Shared by `loadStencilCss` (per-component `?tag=` styles) and `global-css.ts`
125
+ * (including the files that feed `@import "stencil-component-globals"`/`"stencil-css-components"`)
229
126
  *
230
- * Each step is skipped silently if the relevant peer dep is not installed.
231
- * Returns `export default "css string"` so bundlers treat the import as a JS module.
127
+ * @param filePath - absolute path to the source file, with its real extension
128
+ * @param isDev - `true` in dev mode (disables minification)
129
+ * @returns the processed CSS and any extra files it depends on (e.g. Sass `@use`/`@import`), or
130
+ * `null` if the file doesn't exist
131
+ */
132
+ async function processCssFile(filePath, isDev) {
133
+ if (!existsSync(filePath)) return null;
134
+ const ext = extname(filePath).slice(1);
135
+ let css = readFileSync(filePath, "utf-8");
136
+ let deps = [];
137
+ if (PKG.sass && (ext === "scss" || ext === "sass")) {
138
+ const r = await compileSass(css, filePath, ext === "sass");
139
+ css = r.css;
140
+ deps = r.deps;
141
+ } else if (PKG.less && ext === "less") {
142
+ const r = await compileLess(css, filePath);
143
+ css = r.css;
144
+ deps = r.deps;
145
+ }
146
+ if (PKG.postcss) css = await runPostCss(css, filePath);
147
+ if (PKG.lightningcss) css = await runLightningCss(css, filePath, !isDev);
148
+ return {
149
+ css,
150
+ deps
151
+ };
152
+ }
153
+ /**
154
+ * Loads a Stencil CSS virtual module.
155
+ *
156
+ * Runs the file through {@link processCssFile}, then applies the scoped-selector rewrite for
157
+ * `encapsulation: 'scoped'`. Returns `export default "css string"` so bundlers treat the import
158
+ * as a JS module.
232
159
  * @param id - virtual module id produced by `resolveStencilCss`
233
160
  * @param isDev - `true` in dev mode (disables minification)
234
161
  * @returns ESM string export of the processed CSS, or `null` if not a Stencil CSS virtual module
@@ -242,135 +169,806 @@ async function loadStencilCss(id, isDev = true) {
242
169
  const params = new URLSearchParams(query);
243
170
  const tag = params.get("tag") ?? "";
244
171
  const encapsulation = params.get("encapsulation") ?? "none";
245
- const ext = decodeURIComponent(params.get("__ext") ?? "css");
246
- const filePath = `${stem}.${ext}`;
247
- if (!existsSync(filePath)) return {
172
+ const result = await processCssFile(`${stem}.${decodeURIComponent(params.get("__ext") ?? "css")}`, isDev);
173
+ if (!result) return {
248
174
  code: "export default () => \"\"",
249
175
  deps: []
250
176
  };
251
- let css = readFileSync(filePath, "utf-8");
252
- let deps = [];
253
- if (PKG.sass && (ext === "scss" || ext === "sass")) {
254
- const r = await compileSass(css, filePath, ext === "sass");
255
- css = r.css;
256
- deps = r.deps;
257
- } else if (PKG.less && ext === "less") {
258
- const r = await compileLess(css, filePath);
259
- css = r.css;
260
- deps = r.deps;
177
+ let { css } = result;
178
+ if (encapsulation === "scoped" && tag) css = scopeCss(css, getScopeId(tag), false);
179
+ return {
180
+ code: `export default () => ${JSON.stringify(css)};`,
181
+ deps: result.deps
182
+ };
183
+ }
184
+ /**
185
+ * Compiles a Sass/Less stylesheet to plain CSS for doc extraction. Unlike {@link processCssFile},
186
+ * this skips PostCSS and lightningcss - to leave JSDoc-style comments alone.
187
+ *
188
+ * @param filePath - absolute path to the source stylesheet
189
+ * @returns plain CSS text, or `null` if the file doesn't exist
190
+ */
191
+ async function compileCssForDocs(filePath) {
192
+ if (!existsSync(filePath)) return null;
193
+ const ext = extname(filePath).slice(1);
194
+ const css = readFileSync(filePath, "utf-8");
195
+ if (PKG.sass && (ext === "scss" || ext === "sass")) return (await compileSass(css, filePath, ext === "sass")).css;
196
+ if (PKG.less && ext === "less") return (await compileLess(css, filePath)).css;
197
+ return css;
198
+ }
199
+ /**
200
+ * Populates `cmp.styleDocs` from `cmp.styles` - the CSS custom-property docs a bundler plugin
201
+ * needs to assemble a custom-elements-manifest entry for a component's stylesheet(s).
202
+ *
203
+ * @param cmp - component metadata from `transpile`/`transpileSync`, mutated in place
204
+ * @param componentPath - absolute path to the component's `.tsx`/`.ts` file, used to build a
205
+ * synthetic `file` for `transpileSync`
206
+ */
207
+ async function collectStyleDocsForComponent(cmp, componentPath) {
208
+ const cssBase = componentPath.replace(/\.\w+$/, ".css");
209
+ for (const style of cmp.styles ?? []) {
210
+ const cssTexts = [];
211
+ if (style.styleStr) cssTexts.push(style.styleStr);
212
+ for (const external of style.externalStyles ?? []) {
213
+ if (!external.absolutePath) continue;
214
+ const css = await compileCssForDocs(external.absolutePath);
215
+ if (css) cssTexts.push(css);
216
+ }
217
+ for (const css of cssTexts) {
218
+ const params = new URLSearchParams({
219
+ tag: cmp.tagName,
220
+ mode: style.modeName,
221
+ encapsulation: cmp.encapsulation ?? "none"
222
+ });
223
+ const result = transpileSync(css, {
224
+ file: `${cssBase}?${params}`,
225
+ docs: true
226
+ });
227
+ if (result.styleDocs?.length) {
228
+ cmp.styleDocs ??= [];
229
+ cmp.styleDocs.push(...result.styleDocs);
230
+ }
231
+ }
232
+ }
233
+ }
234
+ //#endregion
235
+ //#region src/resolve-types.ts
236
+ /**
237
+ * Resolves imported type references in CEM docs components.
238
+ *
239
+ * `transpileSync` uses a single-file TypeScript host, so imported types (e.g.
240
+ * `ButtonVariant` from `'../types'`) can't be followed — `complexType.resolved`
241
+ * ends up as `"any"`. This module creates a minimal ts.Program per referenced
242
+ * types file (cached) and substitutes the actual expanded type text back into
243
+ * the component's doc data before it enters the registry.
244
+ */
245
+ const TYPE_FORMAT_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.InTypeAlias | ts.TypeFormatFlags.InElementType;
246
+ const typesFileCache = /* @__PURE__ */ new Map();
247
+ function resolveTypesFilePath(specifier, fromDir) {
248
+ const base = resolve(fromDir, specifier);
249
+ if (existsSync(base)) return base;
250
+ for (const ext of [
251
+ ".ts",
252
+ ".tsx",
253
+ ".d.ts"
254
+ ]) {
255
+ const candidate = base + ext;
256
+ if (existsSync(candidate)) return candidate;
257
+ }
258
+ if (base.endsWith(".js")) {
259
+ const stem = base.slice(0, -3);
260
+ for (const ext of [".ts", ".tsx"]) {
261
+ const candidate = stem + ext;
262
+ if (existsSync(candidate)) return candidate;
263
+ }
264
+ }
265
+ }
266
+ function getTypesFileEntry(absPath) {
267
+ const cached = typesFileCache.get(absPath);
268
+ if (cached) return cached;
269
+ const options = {
270
+ ...ts.getDefaultCompilerOptions(),
271
+ noEmit: true,
272
+ module: ts.ModuleKind.ESNext,
273
+ moduleResolution: ts.ModuleResolutionKind.Bundler
274
+ };
275
+ const program = ts.createProgram([absPath], options);
276
+ const checker = program.getTypeChecker();
277
+ const sourceFile = program.getSourceFile(absPath);
278
+ const exportTypes = /* @__PURE__ */ new Map();
279
+ if (sourceFile) {
280
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
281
+ if (moduleSymbol) for (const symbol of checker.getExportsOfModule(moduleSymbol)) exportTypes.set(symbol.name, checker.getDeclaredTypeOfSymbol(symbol));
282
+ }
283
+ const entry = {
284
+ checker,
285
+ exportTypes
286
+ };
287
+ typesFileCache.set(absPath, entry);
288
+ return entry;
289
+ }
290
+ function expandTypeName(typeName, references, fromDir) {
291
+ const ref = references[typeName];
292
+ if (!ref || ref.location !== "import" || !ref.path) return void 0;
293
+ const absPath = resolveTypesFilePath(ref.path, fromDir);
294
+ if (!absPath) return void 0;
295
+ const { checker, exportTypes } = getTypesFileEntry(absPath);
296
+ const type = exportTypes.get(typeName);
297
+ if (!type) return void 0;
298
+ return checker.typeToString(type, void 0, TYPE_FORMAT_FLAGS);
299
+ }
300
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
301
+ function patchType(original, references, fromDir) {
302
+ if (!references) return original;
303
+ let result = original;
304
+ for (const typeName of Object.keys(references)) {
305
+ const expanded = expandTypeName(typeName, references, fromDir);
306
+ if (!expanded || expanded === typeName) continue;
307
+ result = result.replace(new RegExp(`\\b${escapeRegExp(typeName)}\\b`, "g"), expanded.includes("|") || expanded.includes("&") ? `(${expanded})` : expanded);
308
+ }
309
+ return result;
310
+ }
311
+ const hasReferences = (references) => !!references && Object.keys(references).length > 0;
312
+ /**
313
+ * Patches `prop.type` and `event.detail` in-place for any imported/inherited
314
+ * types that weren't fully resolved by Stencil's compiler.
315
+ *
316
+ * Under-resolved types don't always show up as the literal string `"any"` -
317
+ * a prop inherited from a same-project base class (merged via a single-file
318
+ * mini `ts.Program`, which can't follow cross-file imports) can resolve to
319
+ * the type's own unexpanded name instead (e.g. `"Validator"`), since that's
320
+ * what a TypeScript checker falls back to for a type it can't bind. Either
321
+ * way, a `location: 'import'` reference on the prop means there's something
322
+ * worth trying to expand here.
323
+ * @param component The CEM docs component to patch
324
+ * @param componentAbsPath The absolute path to the component's source file (used to resolve relative imports)
325
+ */
326
+ function resolveImportedTypes(component, componentAbsPath) {
327
+ const dir = dirname(componentAbsPath);
328
+ for (const prop of component.props) {
329
+ if (!prop.complexType || !hasReferences(prop.complexType.references)) continue;
330
+ const patched = patchType(prop.complexType.original, prop.complexType.references, dir);
331
+ if (patched !== prop.complexType.original) prop.type = patched;
332
+ }
333
+ for (const event of component.events) {
334
+ if (!event.complexType || !hasReferences(event.complexType.references)) continue;
335
+ const patched = patchType(event.complexType.original, event.complexType.references, dir);
336
+ if (patched !== event.complexType.original) event.detail = patched;
337
+ }
338
+ }
339
+ //#endregion
340
+ //#region src/project-scan.ts
341
+ /**
342
+ * The project-wide component scan behind the docs/CEM and the virtual global-stylesheet imports.
343
+ *
344
+ * The registries are module-level on purpose: `getStencilCEM()` is public API called from outside
345
+ * any plugin instance (e.g. a Storybook preset running in Node.js).
346
+ */
347
+ const docsRegistry = /* @__PURE__ */ new Map();
348
+ const componentGlobalStyles = [];
349
+ const cssOnlyComponentFiles = /* @__PURE__ */ new Set();
350
+ const cssOnlyTagsByFile = /* @__PURE__ */ new Map();
351
+ const componentMetaRegistry = /* @__PURE__ */ new Map();
352
+ const cssOnlyMetaRegistry = /* @__PURE__ */ new Map();
353
+ const tagsBySourceFile = /* @__PURE__ */ new Map();
354
+ /**
355
+ * A snapshot of the whole docs registry's content, used to detect whether a CSS-only
356
+ * component's docs changed after a re-scan. A `.css` file's tag(s) aren't known until after parsing
357
+ * - and it may define more than one; compares the whole registry rather than one entry.
358
+ * Cheap in practice: only runs on file save
359
+ *
360
+ * @returns a string that changes whenever any registry entry's content does
361
+ */
362
+ const getRegistrySnapshot = () => JSON.stringify([...docsRegistry.entries()].sort(([a], [b]) => a.localeCompare(b)));
363
+ /**
364
+ * Returns the current CEM. Only populated when `docs: true` is set.
365
+ * @returns the current CEM, or an empty CEM if `docs: true` was not set.
366
+ */
367
+ function getStencilCEM() {
368
+ return generateManifest({ components: [...docsRegistry.values()] });
369
+ }
370
+ const COMPONENT_DECORATOR_RE = /(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/;
371
+ const isTsSourceFile = (abs) => (abs.endsWith(".tsx") || abs.endsWith(".ts")) && !abs.endsWith(".d.ts");
372
+ const isCssFile = (abs) => abs.endsWith(".css");
373
+ /**
374
+ * Recursively collect file paths matching `matches` under `dir`, pruning
375
+ * `node_modules` and hidden directories (`.git`, `.vite`, etc.) as it goes.
376
+ *
377
+ * `readdirSync(dir, { recursive: true })` can't prune during traversal - it
378
+ * walks everything first and only lets the caller filter the flat result
379
+ * afterward, which is disastrous under a symlink-heavy `node_modules` (e.g.
380
+ * pnpm's `.pnpm` store, which flattens every dependency in the workspace) -
381
+ * it can take minutes just to list, blocking `buildStart` the whole time.
382
+ *
383
+ * @param dir the directory to walk
384
+ * @param matches predicate applied to each file's absolute path
385
+ * @param out accumulator array of absolute file paths, mutated in place
386
+ */
387
+ function collectFiles(dir, matches, out) {
388
+ let entries;
389
+ try {
390
+ entries = readdirSync(dir, { withFileTypes: true });
391
+ } catch {
392
+ return;
393
+ }
394
+ for (const entry of entries) {
395
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
396
+ const abs = join(dir, entry.name);
397
+ if (entry.isDirectory()) collectFiles(abs, matches, out);
398
+ else if (entry.isFile() && matches(abs)) out.push(abs);
399
+ }
400
+ }
401
+ /**
402
+ * Parse a single `.css` file for CSS-only components (pure-CSS custom-element definitions
403
+ * marked with a `@component` JSDoc tag - see `@stencil/core/compiler`'s `parseCssOnlyComponents`)
404
+ * and register each one in the docs registry with `cssOnly: true` - replacing whatever the file
405
+ * registered before, so a component whose definition was removed (or whose file was deleted)
406
+ * stops being emitted.
407
+ * @param file absolute path to the `.css` file
408
+ */
409
+ async function scanCssOnlyDocsFile(file) {
410
+ const abs = normalize(file);
411
+ let code = "";
412
+ try {
413
+ code = readFileSync(abs, "utf-8");
414
+ } catch {}
415
+ const { components } = code.includes("@component") ? await parseCssOnlyComponents(abs, code) : { components: [] };
416
+ for (const tag of cssOnlyTagsByFile.get(abs) ?? []) {
417
+ docsRegistry.delete(tag);
418
+ cssOnlyMetaRegistry.delete(tag);
419
+ }
420
+ if (components.length > 0) {
421
+ cssOnlyComponentFiles.add(abs);
422
+ cssOnlyTagsByFile.set(abs, components.map((c) => c.tagName));
423
+ } else {
424
+ cssOnlyComponentFiles.delete(abs);
425
+ cssOnlyTagsByFile.delete(abs);
426
+ }
427
+ for (const item of components) {
428
+ docsRegistry.set(item.tagName, {
429
+ ...cmpMetaToDocsComponent(item, abs),
430
+ cssOnly: true
431
+ });
432
+ cssOnlyMetaRegistry.set(item.tagName, item);
433
+ }
434
+ }
435
+ /**
436
+ * @param file a stylesheet path, in either separator form
437
+ * @returns whether it currently defines CSS-only components
438
+ */
439
+ const isCssOnlyComponentFile = (file) => cssOnlyComponentFiles.has(normalize(file));
440
+ /**
441
+ * Re-scan a changed stylesheet that defines (or used to define) CSS-only components - that changes
442
+ * which ones exist, not just their CSS.
443
+ * @param file the changed file
444
+ */
445
+ async function rescanIfCssOnlyComponent(file) {
446
+ if (!isCssFile(file)) return;
447
+ const abs = normalize(file);
448
+ let code = "";
449
+ try {
450
+ code = readFileSync(abs, "utf-8");
451
+ } catch {}
452
+ if (code.includes("@component") || cssOnlyComponentFiles.has(abs)) await scanCssOnlyDocsFile(abs);
453
+ }
454
+ /**
455
+ * Scan a changed directory for `.css` files not yet known as CSS-only components - a watcher
456
+ * may report a file added to a watched directory as the directory itself.
457
+ * @param dir the changed path - ignored unless it's a directory
458
+ */
459
+ async function rescanNewCssOnlyComponents(dir) {
460
+ try {
461
+ if (!statSync(dir).isDirectory()) return;
462
+ } catch {
463
+ return;
464
+ }
465
+ const cssFiles = [];
466
+ collectFiles(dir, isCssFile, cssFiles);
467
+ await Promise.all(cssFiles.filter((f) => !cssOnlyComponentFiles.has(f)).map(scanCssOnlyDocsFile));
468
+ }
469
+ /**
470
+ * Re-derives one component's docs from its `.tsx` / `.ts` source and merges the result into the
471
+ * docs registry.
472
+ *
473
+ * @param tag the custom-element tag name to refresh
474
+ * @param filePath absolute path to the component's `.tsx`/`.ts` source
475
+ * @returns `true` if the registry entry's content actually changed
476
+ */
477
+ async function refreshComponentDocs(tag, filePath) {
478
+ const prevSnapshot = JSON.stringify(docsRegistry.get(tag));
479
+ try {
480
+ const code = readFileSync(filePath, "utf-8");
481
+ const result = await transpile(code, {
482
+ file: filePath,
483
+ componentExport: "customelement"
484
+ });
485
+ for (const item of result.data ?? []) {
486
+ if (!item.tagName) continue;
487
+ await collectStyleDocsForComponent(item, filePath);
488
+ const component = cmpMetaToDocsComponent(item, filePath);
489
+ resolveImportedTypes(component, filePath);
490
+ docsRegistry.set(item.tagName, component);
491
+ }
492
+ } catch {
493
+ return false;
494
+ }
495
+ return JSON.stringify(docsRegistry.get(tag)) !== prevSnapshot;
496
+ }
497
+ /**
498
+ * Re-derive a changed (or added, or deleted) `.tsx`/`.ts` file's compiler metadata - replacing
499
+ * whatever it defined before, so a removed or renamed component stops being typed.
500
+ * @param file absolute path to the source file
501
+ * @returns whether the file defines, or used to define, any component
502
+ */
503
+ async function refreshComponentMeta(file) {
504
+ const abs = normalize(file);
505
+ let code = "";
506
+ try {
507
+ code = readFileSync(abs, "utf-8");
508
+ } catch {}
509
+ const previous = tagsBySourceFile.get(abs) ?? [];
510
+ let items = [];
511
+ if (COMPONENT_DECORATOR_RE.test(code)) try {
512
+ items = ((await transpile(code, {
513
+ file: abs,
514
+ componentExport: "customelement"
515
+ })).data ?? []).filter((item) => item.tagName);
516
+ } catch {
517
+ return previous.length > 0;
518
+ }
519
+ for (const tag of previous) componentMetaRegistry.delete(tag);
520
+ for (const item of items) componentMetaRegistry.set(item.tagName, item);
521
+ if (items.length > 0) tagsBySourceFile.set(abs, items.map((item) => item.tagName));
522
+ else tagsBySourceFile.delete(abs);
523
+ return previous.length > 0 || items.length > 0;
524
+ }
525
+ /**
526
+ * Scan the project for component source files (`.tsx`/`.ts`) and CSS-only components
527
+ * (`.css`), pre-populating the docs registry, `componentGlobalStyles`, and
528
+ * `cssOnlyComponentFiles` - the project-wide data the virtual global-stylesheet imports need
529
+ * (see `global-css.ts`), gathered eagerly so it doesn't depend on module-graph visitation order.
530
+ * @param filter A function to filter which `.tsx`/`.ts` files should be included - not applied
531
+ * to `.css` files, since the default `include` (`/\.tsx?$/`) would otherwise exclude all of them.
532
+ * @param collectStyleDocs Whether to also collect CSS custom-property docs for each component's
533
+ * stylesheet(s) - the extra parse cost only pays off when `options.docs` is set.
534
+ * @returns A promise that resolves when the scan is complete.
535
+ */
536
+ async function scanDocs(filter, collectStyleDocs) {
537
+ componentGlobalStyles.length = 0;
538
+ for (const tags of cssOnlyTagsByFile.values()) for (const tag of tags) docsRegistry.delete(tag);
539
+ cssOnlyTagsByFile.clear();
540
+ cssOnlyComponentFiles.clear();
541
+ componentMetaRegistry.clear();
542
+ cssOnlyMetaRegistry.clear();
543
+ tagsBySourceFile.clear();
544
+ const cwd = process.cwd();
545
+ const allFiles = [];
546
+ collectFiles(cwd, (abs) => isTsSourceFile(abs) || isCssFile(abs), allFiles);
547
+ const tsxFiles = allFiles.filter((abs) => isTsSourceFile(abs) && filter(abs));
548
+ const cssFiles = allFiles.filter(isCssFile);
549
+ await Promise.all([...tsxFiles.map(async (abs) => {
550
+ let code;
551
+ try {
552
+ code = readFileSync(abs, "utf-8");
553
+ } catch {
554
+ return;
555
+ }
556
+ if (!COMPONENT_DECORATOR_RE.test(code)) return;
557
+ const result = await transpile(code, {
558
+ file: abs,
559
+ componentExport: "customelement"
560
+ });
561
+ for (const item of result.data ?? []) {
562
+ if (!item.tagName) continue;
563
+ if (collectStyleDocs) await collectStyleDocsForComponent(item, abs);
564
+ const component = cmpMetaToDocsComponent(item, abs);
565
+ resolveImportedTypes(component, abs);
566
+ docsRegistry.set(item.tagName, component);
567
+ componentMetaRegistry.set(item.tagName, item);
568
+ tagsBySourceFile.set(normalize(abs), [...tagsBySourceFile.get(normalize(abs)) ?? [], item.tagName]);
569
+ if (item.globalStyles?.length) componentGlobalStyles.push(...item.globalStyles);
570
+ }
571
+ }), ...cssFiles.map(scanCssOnlyDocsFile)]);
572
+ }
573
+ //#endregion
574
+ //#region src/component-types.ts
575
+ /**
576
+ * `components.d.ts` - the typings `stencil build` writes to `srcDir`, generated here from the
577
+ * project scan with core's own generator, so a project whose dev loop never runs the Stencil
578
+ * compiler (Storybook, a Vite app authoring components from source) still gets them, kept current
579
+ * as sources change. Same generator, same inputs, same order: if `stencil build --watch` runs
580
+ * alongside, both write identical content.
581
+ */
582
+ const byTagName = (a, b) => a.tagName.localeCompare(b.tagName);
583
+ /**
584
+ * Write `<srcDir>/components.d.ts` from the current registries, unless its content is unchanged -
585
+ * so an editor's TS server, or a `stencil build --watch`, isn't disturbed for nothing.
586
+ * @param config `srcDir` (absolute) plus the other fields that affect the output
587
+ * @returns whether the file was (re)written
588
+ */
589
+ function writeComponentTypes(config) {
590
+ const filePath = join(config.srcDir, "components.d.ts");
591
+ const content = generateComponentTypesFile([...[...componentMetaRegistry.values()].sort(byTagName), ...[...cssOnlyMetaRegistry.values()].sort(byTagName)], config);
592
+ let existing;
593
+ try {
594
+ existing = readFileSync(filePath, "utf-8");
595
+ } catch {}
596
+ if (existing === content) return false;
597
+ writeFileSync(filePath, content);
598
+ return true;
599
+ }
600
+ //#endregion
601
+ //#region src/config.ts
602
+ /**
603
+ * Stencil config auto-detection for @stencil/unplugin.
604
+ *
605
+ * Searches for a `stencil.config.ts` (or `.js` variant) in the project root,
606
+ * loads it via jiti (so TypeScript is handled without a separate compile step),
607
+ * and extracts the subset of flags that are meaningful at transpile time.
608
+ *
609
+ * `stencilConfigToOverrides` converts that subset to a `BuildOverrides` object
610
+ * ready to pass to `transpileSync`.
611
+ */
612
+ const STENCIL_CONFIG_KEYS = /* @__PURE__ */ new Set([
613
+ "namespace",
614
+ "srcDir",
615
+ "outputTargets",
616
+ "plugins",
617
+ "signalBacking",
618
+ "compat",
619
+ "srcDir"
620
+ ]);
621
+ const looksLikeConfig = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.keys(v).some((k) => STENCIL_CONFIG_KEYS.has(k));
622
+ const CONFIG_CANDIDATES = [
623
+ "stencil.config.ts",
624
+ "stencil.config.mts",
625
+ "stencil.config.js",
626
+ "stencil.config.mjs"
627
+ ];
628
+ /**
629
+ * Attempt to load the project's `stencil.config.ts` and return the
630
+ * transpile-relevant fields. Returns `null` if no config file is found or
631
+ * if loading fails for any reason.
632
+ * @param cwd - project root to search in (usually `process.cwd()`)
633
+ * @returns a subset of the Stencil config, or `null` if none is found
634
+ */
635
+ async function loadStencilConfig(cwd) {
636
+ for (const filename of CONFIG_CANDIDATES) {
637
+ const configPath = join(cwd, filename);
638
+ if (!existsSync(configPath)) continue;
639
+ try {
640
+ const { createJiti } = await import("jiti");
641
+ const mod = await createJiti(import.meta.url).import(configPath);
642
+ const raw = mod["config"] ?? (looksLikeConfig(mod["default"]) ? mod["default"] : null);
643
+ if (!raw || typeof raw !== "object") return null;
644
+ return extractSubset(raw);
645
+ } catch {
646
+ return null;
647
+ }
648
+ }
649
+ return null;
650
+ }
651
+ function extractSubset(c) {
652
+ const result = {};
653
+ if (c["signalBacking"] === true) result.signalBacking = true;
654
+ if (typeof c["srcDir"] === "string") result.srcDir = c["srcDir"];
655
+ if ("hydratedFlag" in c) result.hydratedFlag = c["hydratedFlag"];
656
+ const compat = c["compat"];
657
+ if (compat && typeof compat === "object") {
658
+ const co = compat;
659
+ const ldp = co["lightDomPatches"];
660
+ const lifecycleDOMEvents = co["lifecycleDOMEvents"];
661
+ const initializeNextTick = co["initializeNextTick"];
662
+ if (ldp !== void 0 || lifecycleDOMEvents !== void 0 || initializeNextTick !== void 0) {
663
+ result.compat = {};
664
+ if (typeof ldp === "boolean") result.compat.lightDomPatches = ldp;
665
+ else if (ldp && typeof ldp === "object") result.compat.lightDomPatches = ldp;
666
+ if (lifecycleDOMEvents === true) result.compat.lifecycleDOMEvents = true;
667
+ if (initializeNextTick === true) result.compat.initializeNextTick = true;
668
+ }
669
+ }
670
+ return result;
671
+ }
672
+ /**
673
+ * Whether the bundler is running under a test runner. Mirrors core's `_isTesting` check
674
+ * (`validate-config.ts`), which the transpile path never reaches, so `Build.isTesting` can
675
+ * be set through the build overrides instead.
676
+ *
677
+ * @param env the environment to check
678
+ * @returns `true` under Vitest, Playwright, or `NODE_ENV=test`
679
+ */
680
+ function isTestEnvironment(env = process.env) {
681
+ return !!(env.VITEST || env.PLAYWRIGHT_TEST || env.TEST_WORKER_INDEX || env.TEST_PARALLEL_INDEX || env.NODE_ENV === "test");
682
+ }
683
+ /**
684
+ * Convert a {@link StencilConfigSubset} to a {@link BuildOverrides} object.
685
+ * The caller is responsible for merging this with any explicit
686
+ * `transpileOptions.buildOverrides` (which should take precedence).
687
+ * @param config - the Stencil config subset to convert
688
+ * @returns a `BuildOverrides` object suitable for passing to `transpileSync`
689
+ */
690
+ function stencilConfigToOverrides(config) {
691
+ const o = {};
692
+ if (config.signalBacking) {
693
+ o.signalBacking = true;
694
+ o.vdomSignals = true;
695
+ }
696
+ const compat = config.compat;
697
+ if (!compat) return o;
698
+ if (compat.lifecycleDOMEvents) o.lifecycleDOMEvents = true;
699
+ if (compat.initializeNextTick) o.initializeNextTick = true;
700
+ const ldp = compat.lightDomPatches;
701
+ if (ldp === false) {
702
+ o.lightDomPatches = false;
703
+ o.slotChildNodes = false;
704
+ o.slotCloneNode = false;
705
+ o.slotDomMutations = false;
706
+ o.slotTextContent = false;
707
+ } else if (typeof ldp === "object") {
708
+ o.lightDomPatches = true;
709
+ o.slotChildNodes = !!ldp.childNodes;
710
+ o.slotCloneNode = !!ldp.cloneNode;
711
+ o.slotDomMutations = !!ldp.domMutations;
712
+ o.slotTextContent = !!ldp.textContent;
261
713
  }
262
- if (PKG.postcss) css = await runPostCss(css, filePath);
263
- if (PKG.lightningcss) css = await runLightningCss(css, filePath, !isDev);
264
- if (encapsulation === "scoped" && tag) css = scopeCss(css, getScopeId(tag), false);
265
- return {
266
- code: `export default () => ${JSON.stringify(css)};`,
267
- deps
268
- };
714
+ return o;
269
715
  }
270
716
  //#endregion
271
- //#region src/resolve-types.ts
717
+ //#region src/global-css.ts
272
718
  /**
273
- * Resolves imported type references in CEM docs components.
719
+ * Stencil's three virtual global-stylesheet imports - `@import "stencil-hydrate"`,
720
+ * `"stencil-component-globals"` and `"stencil-css-components"` - as real stylesheets.
274
721
  *
275
- * `transpileSync` uses a single-file TypeScript host, so imported types (e.g.
276
- * `ButtonVariant` from `'../types'`) can't be followed — `complexType.resolved`
277
- * ends up as `"any"`. This module creates a minimal ts.Program per referenced
278
- * types file (cached) and substitutes the actual expanded type text back into
279
- * the component's doc data before it enters the registry.
722
+ * Their CSS, gathered by the project-wide scan (see `scanDocs` in `plugin.ts`), is written to
723
+ * `<dir>/<name>.css` and each specifier resolves to that file, so the bundler handles it like any
724
+ * other stylesheet: wherever it's imported from (partials, Sass, Less) and with whatever
725
+ * `@import` modifiers. Vite doesn't consult plugins when resolving CSS `@import`, so there it's
726
+ * reached through an alias ({@link virtualGlobalStylesheetAlias}); other bundlers go through
727
+ * `resolveId`.
280
728
  */
281
- const TYPE_FORMAT_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.InTypeAlias | ts.TypeFormatFlags.InElementType;
282
- const typesFileCache = /* @__PURE__ */ new Map();
283
- function resolveTypesFilePath(specifier, fromDir) {
284
- const base = resolve(fromDir, specifier);
285
- if (existsSync(base)) return base;
286
- for (const ext of [
287
- ".ts",
288
- ".tsx",
289
- ".d.ts"
290
- ]) {
291
- const candidate = base + ext;
292
- if (existsSync(candidate)) return candidate;
729
+ const VIRTUAL_GLOBAL_IMPORTS = [
730
+ "stencil-hydrate",
731
+ "stencil-component-globals",
732
+ "stencil-css-components"
733
+ ];
734
+ const VIRTUAL_GLOBAL_ID_RE = new RegExp(`^(${VIRTUAL_GLOBAL_IMPORTS.join("|")})$`);
735
+ /** Matches a mention of any virtual global-stylesheet import name. */
736
+ const VIRTUAL_GLOBAL_IMPORT_RE = new RegExp(`\\b(?:${VIRTUAL_GLOBAL_IMPORTS.join("|")})\\b`);
737
+ const VIRTUAL_GLOBAL_SUFFIX_RE = new RegExp(`(?:^|[\\\\/])(${VIRTUAL_GLOBAL_IMPORTS.join("|")})$`);
738
+ /**
739
+ * The virtual import a specifier refers to - either exactly, or with a directory prefix, which
740
+ * callers should only accept when no such file exists (see {@link VIRTUAL_GLOBAL_SUFFIX_RE}).
741
+ * @param id a module specifier
742
+ * @returns the virtual import's name, if the specifier ends in one
743
+ */
744
+ const getVirtualGlobalImportName = (id) => VIRTUAL_GLOBAL_SUFFIX_RE.exec(id)?.[1];
745
+ /**
746
+ * @param dir the directory {@link writeVirtualGlobalStylesheets} writes to
747
+ * @param name a virtual global-stylesheet import
748
+ * @returns the path of its generated stylesheet
749
+ */
750
+ const virtualGlobalStylesheetPath = (dir, name) => join(dir, `${name}.css`);
751
+ /**
752
+ * A Vite alias sending each virtual import to its generated stylesheet in `dir`.
753
+ * @param dir the directory {@link writeVirtualGlobalStylesheets} writes to
754
+ * @returns the alias entry
755
+ */
756
+ const virtualGlobalStylesheetAlias = (dir) => ({
757
+ find: VIRTUAL_GLOBAL_ID_RE,
758
+ replacement: virtualGlobalStylesheetPath(dir, "$1")
759
+ });
760
+ /**
761
+ * A webpack-style alias map (`name$` = exact match) sending each virtual import to its generated
762
+ * stylesheet in `dir` - for bundlers whose CSS `@import` resolution skips plugins (rspack).
763
+ * @param dir the directory {@link writeVirtualGlobalStylesheets} writes to
764
+ * @returns the alias map
765
+ */
766
+ const virtualGlobalStylesheetAliasMap = (dir) => Object.fromEntries(VIRTUAL_GLOBAL_IMPORTS.map((name) => [`${name}$`, virtualGlobalStylesheetPath(dir, name)]));
767
+ /**
768
+ * Tags `stencil-hydrate` hides until hydrated. CSS-only components never hydrate, so including
769
+ * them would hide them for good.
770
+ * @param components every component in the docs registry
771
+ * @returns the real (JS-backed) components' tag names
772
+ */
773
+ const getHydrateTagNames = (components) => new Set([...components].filter((c) => !c.cssOnly).map((c) => c.tag));
774
+ const processedFileCache = /* @__PURE__ */ new Map();
775
+ const latestMtime = (filePaths) => {
776
+ let latest = 0;
777
+ for (const filePath of filePaths) try {
778
+ latest = Math.max(latest, statSync(filePath).mtimeMs);
779
+ } catch {
780
+ return NaN;
293
781
  }
294
- if (base.endsWith(".js")) {
295
- const stem = base.slice(0, -3);
296
- for (const ext of [".ts", ".tsx"]) {
297
- const candidate = stem + ext;
298
- if (existsSync(candidate)) return candidate;
782
+ return latest;
783
+ };
784
+ async function collectFileParts(filePaths, isDev) {
785
+ const parts = [];
786
+ const deps = [];
787
+ for (const filePath of filePaths) {
788
+ deps.push(filePath);
789
+ let processed = processedFileCache.get(filePath);
790
+ if (!processed || processed.mtimeMs !== latestMtime([filePath, ...processed.deps])) {
791
+ const result = await processCssFile(filePath, isDev);
792
+ if (!result) continue;
793
+ processed = {
794
+ ...result,
795
+ mtimeMs: latestMtime([filePath, ...result.deps])
796
+ };
797
+ processedFileCache.set(filePath, processed);
299
798
  }
799
+ parts.push(processed.css);
800
+ deps.push(...processed.deps);
300
801
  }
802
+ return {
803
+ css: parts.join("\n"),
804
+ deps
805
+ };
301
806
  }
302
- function getTypesFileEntry(absPath) {
303
- const cached = typesFileCache.get(absPath);
304
- if (cached) return cached;
305
- const options = {
306
- ...ts.getDefaultCompilerOptions(),
307
- noEmit: true,
308
- module: ts.ModuleKind.ESNext,
309
- moduleResolution: ts.ModuleResolutionKind.Bundler
807
+ async function collectComponentGlobalStyles(entries, isDev) {
808
+ const inline = [];
809
+ const filePaths = [];
810
+ for (const gs of entries) if (gs.styleStr) inline.push(gs.styleStr);
811
+ else if (gs.absolutePath) filePaths.push(gs.absolutePath);
812
+ const { css: fileCss, deps } = await collectFileParts(filePaths, isDev);
813
+ return {
814
+ css: [...inline, fileCss].filter(Boolean).join("\n"),
815
+ deps
310
816
  };
311
- const program = ts.createProgram([absPath], options);
312
- const checker = program.getTypeChecker();
313
- const sourceFile = program.getSourceFile(absPath);
314
- const exportTypes = /* @__PURE__ */ new Map();
315
- if (sourceFile) {
316
- const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
317
- if (moduleSymbol) for (const symbol of checker.getExportsOfModule(moduleSymbol)) exportTypes.set(symbol.name, checker.getDeclaredTypeOfSymbol(symbol));
817
+ }
818
+ /**
819
+ * Write each virtual import's CSS to `<dir>/<name>.css` - all three, even when empty, so they
820
+ * always resolve. Files whose content is unchanged are left alone, so they don't trigger HMR.
821
+ * @param dir the directory to write to
822
+ * @param data project-wide data collected by `scanDocs`
823
+ * @param isDev `true` in dev mode (disables minification in the ingredient preprocessing chain)
824
+ * @returns the paths of files that were (re)written, and every ingredient file the CSS came from
825
+ * (register these as watch files)
826
+ */
827
+ async function writeVirtualGlobalStylesheets(dir, data, isDev) {
828
+ const globals = await collectComponentGlobalStyles(data.componentGlobalStyles, isDev);
829
+ const cssOnly = await collectFileParts(data.cssOnlyComponentFiles, isDev);
830
+ const contents = {
831
+ "stencil-hydrate": buildHydrateCss(data.hydratedFlag, [...data.tagNames]),
832
+ "stencil-component-globals": globals.css,
833
+ "stencil-css-components": cssOnly.css
834
+ };
835
+ mkdirSync(dir, { recursive: true });
836
+ const written = [];
837
+ for (const name of VIRTUAL_GLOBAL_IMPORTS) {
838
+ const filePath = virtualGlobalStylesheetPath(dir, name);
839
+ let existing;
840
+ try {
841
+ existing = readFileSync(filePath, "utf-8");
842
+ } catch {}
843
+ if (existing !== contents[name]) {
844
+ writeFileSync(filePath, contents[name]);
845
+ written.push(filePath);
846
+ }
318
847
  }
319
- const entry = {
320
- checker,
321
- exportTypes
848
+ return {
849
+ written,
850
+ deps: [...globals.deps, ...cssOnly.deps]
322
851
  };
323
- typesFileCache.set(absPath, entry);
324
- return entry;
325
- }
326
- function expandTypeName(typeName, references, fromDir) {
327
- const ref = references[typeName];
328
- if (!ref || ref.location !== "import" || !ref.path) return void 0;
329
- const absPath = resolveTypesFilePath(ref.path, fromDir);
330
- if (!absPath) return void 0;
331
- const { checker, exportTypes } = getTypesFileEntry(absPath);
332
- const type = exportTypes.get(typeName);
333
- if (!type) return void 0;
334
- return checker.typeToString(type, void 0, TYPE_FORMAT_FLAGS);
335
852
  }
336
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
337
- function patchType(original, references, fromDir) {
338
- if (!references) return original;
339
- let result = original;
340
- for (const typeName of Object.keys(references)) {
341
- const expanded = expandTypeName(typeName, references, fromDir);
342
- if (!expanded || expanded === typeName) continue;
343
- result = result.replace(new RegExp(`\\b${escapeRegExp(typeName)}\\b`, "g"), expanded.includes("|") || expanded.includes("&") ? `(${expanded})` : expanded);
853
+ const STYLE_FILE_RE = /\.(css|scss|sass|less|styl|stylus|pcss)$/;
854
+ const mentionsVirtualGlobalImport = (abs) => {
855
+ try {
856
+ return VIRTUAL_GLOBAL_IMPORT_RE.test(readFileSync(abs, "utf-8"));
857
+ } catch {
858
+ return false;
344
859
  }
345
- return result;
860
+ };
861
+ /**
862
+ * Cheap text check of every stylesheet under `root` for a virtual global-stylesheet import -
863
+ * gates the full project scan the generated stylesheets need.
864
+ * @param root the project root
865
+ * @returns whether any stylesheet mentions one
866
+ */
867
+ function projectUsesVirtualGlobalImports(root) {
868
+ const styleFiles = [];
869
+ collectFiles(root, (abs) => STYLE_FILE_RE.test(abs), styleFiles);
870
+ return styleFiles.some(mentionsVirtualGlobalImport);
346
871
  }
347
- const hasReferences = (references) => !!references && Object.keys(references).length > 0;
348
872
  /**
349
- * Patches `prop.type` and `event.detail` in-place for any imported/inherited
350
- * types that weren't fully resolved by Stencil's compiler.
351
- *
352
- * Under-resolved types don't always show up as the literal string `"any"` -
353
- * a prop inherited from a same-project base class (merged via a single-file
354
- * mini `ts.Program`, which can't follow cross-file imports) can resolve to
355
- * the type's own unexpanded name instead (e.g. `"Validator"`), since that's
356
- * what a TypeScript checker falls back to for a type it can't bind. Either
357
- * way, a `location: 'import'` reference on the prop means there's something
358
- * worth trying to expand here.
359
- * @param component The CEM docs component to patch
360
- * @param componentAbsPath The absolute path to the component's source file (used to resolve relative imports)
873
+ * One plugin instance's generated virtual global stylesheets: where they live, and generating
874
+ * them on first use - so projects that never use them don't pay for the project scan - then
875
+ * regenerating them as sources change.
876
+ * @param prepare loads whatever the stylesheets are built from (config, project scan)
877
+ * @param isDev whether this is a dev build (unminified, and a separate output dir)
878
+ * @returns the stylesheets' controls, one per plugin hook that needs them
361
879
  */
362
- function resolveImportedTypes(component, componentAbsPath) {
363
- const dir = dirname(componentAbsPath);
364
- for (const prop of component.props) {
365
- if (!prop.complexType || !hasReferences(prop.complexType.references)) continue;
366
- const patched = patchType(prop.complexType.original, prop.complexType.references, dir);
367
- if (patched !== prop.complexType.original) prop.type = patched;
368
- }
369
- for (const event of component.events) {
370
- if (!event.complexType || !hasReferences(event.complexType.references)) continue;
371
- const patched = patchType(event.complexType.original, event.complexType.references, dir);
372
- if (patched !== event.complexType.original) event.detail = patched;
373
- }
880
+ function createVirtualGlobalCss(prepare, isDev) {
881
+ let dir = "";
882
+ let written = null;
883
+ let deps = [];
884
+ const write = async () => {
885
+ const result = await writeVirtualGlobalStylesheets(dir, await prepare(), isDev());
886
+ deps = result.deps;
887
+ return result;
888
+ };
889
+ const ensure = () => written ??= write();
890
+ const rewrite = async () => {
891
+ await written;
892
+ written = write();
893
+ return written;
894
+ };
895
+ const refresh = () => written ? rewrite() : ensure();
896
+ const useDefaultDir = (root) => {
897
+ dir ||= resolve(root, "node_modules", ".stencil", "virtual-css", isDev() ? "serve" : "build");
898
+ };
899
+ const isPath = (id) => !!dir && dirname(id) === dir;
900
+ return {
901
+ get dir() {
902
+ return dir;
903
+ },
904
+ /** @returns whether they've been generated yet, i.e. something uses them */
905
+ get started() {
906
+ return !!written;
907
+ },
908
+ /** @returns the ingredient files the last generation drew from */
909
+ get deps() {
910
+ return deps;
911
+ },
912
+ setDir(value) {
913
+ dir = value;
914
+ },
915
+ /** Use the default dir under `root`, unless one's already been set. */
916
+ useDefaultDir,
917
+ isPath,
918
+ refresh,
919
+ /**
920
+ * @param id a module specifier
921
+ * @param importer the importing file
922
+ * @returns the generated stylesheet it refers to, if it's a virtual import. A directory-prefixed
923
+ * name (as Less writes `(css)` imports in a partial) only counts when no such file exists.
924
+ */
925
+ async resolveId(id, importer) {
926
+ if (isPath(id)) {
927
+ await ensure();
928
+ return id;
929
+ }
930
+ const name = getVirtualGlobalImportName(id);
931
+ if (!name || name !== id && importer && existsSync(resolve(dirname(importer), id))) return;
932
+ await ensure();
933
+ return virtualGlobalStylesheetPath(dir, name);
934
+ },
935
+ /**
936
+ * Regenerated on every load, so a watch-mode rebuild sees ingredient changes.
937
+ * @param id a generated stylesheet's path
938
+ * @returns its CSS, and the ingredient files to register as watch files
939
+ */
940
+ async load(id) {
941
+ await rewrite();
942
+ return {
943
+ code: readFileSync(id, "utf-8"),
944
+ deps
945
+ };
946
+ },
947
+ /**
948
+ * For bundlers that read the generated files straight from disk before compiling (webpack,
949
+ * rspack) - (re)write them before every compile, once some stylesheet uses them.
950
+ * @param root the project root
951
+ */
952
+ async forCompile(root) {
953
+ if (!written && !projectUsesVirtualGlobalImports(root)) return;
954
+ useDefaultDir(root);
955
+ await refresh();
956
+ },
957
+ /**
958
+ * Vite HMR: generate them once a stylesheet first mentions one, then regenerate on every
959
+ * relevant change.
960
+ * @param file the changed file
961
+ * @returns the generated stylesheets whose content changed
962
+ */
963
+ async hotUpdate(file) {
964
+ if (!written) {
965
+ if (STYLE_FILE_RE.test(file) && mentionsVirtualGlobalImport(file)) await ensure();
966
+ return [];
967
+ }
968
+ if (!/\.(css|tsx?)$/.test(file)) return [];
969
+ return (await rewrite()).written;
970
+ }
971
+ };
374
972
  }
375
973
  //#endregion
376
974
  //#region src/transform.ts
@@ -378,11 +976,12 @@ function resolveImportedTypes(component, componentAbsPath) {
378
976
  * Component transpilation and base-class discovery.
379
977
  *
380
978
  * `transformStencil` is the main entry point: it calls `transpileSync` with
381
- * `componentExport: 'customelement'` so each component self-registers when
382
- * imported. Two code paths come out:
979
+ * `componentExport: 'customelement'` (unless overridden via `transpileOptions`)
980
+ * so each component self-registers when imported. Two code paths come out:
383
981
  *
384
982
  * - **Component** (`@Component` present): full customelement output with
385
- * `defineCustomElement`, optional HMR snippet appended in dev mode.
983
+ * `defineCustomElement` (or, for `componentExport: 'module'`, just the
984
+ * exported class), optional HMR snippet appended in dev mode.
386
985
  * - **Decorated base class** (`@Prop`/`@State`/etc. but no `@Component`):
387
986
  * returned as-is — the compiler's `isStencilBaseClass` check already injects
388
987
  * `extends HTMLElement` via `updateNativeBaseClass`.
@@ -474,12 +1073,13 @@ function resolveSpecifier(specifier, importer) {
474
1073
  * @param configOverrides - pass stencil config option overrides to the transpiler
475
1074
  * @returns transformed output, or `null` if the file is not a Stencil file
476
1075
  */
477
- function transformStencil(code, id, options, dev = false, framework = "", onBaseClass, configOverrides) {
1076
+ async function transformStencil(code, id, options, dev = false, framework = "", onBaseClass, configOverrides) {
478
1077
  if (!id.endsWith(".tsx") && !id.endsWith(".ts")) return null;
479
1078
  if (id.endsWith(".d.ts")) return null;
480
1079
  if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/.test(code)) return null;
481
1080
  const specPage = options.mode === "spec-page";
482
1081
  const jsxOpts = resolveJsxOpts(code, process.cwd());
1082
+ const componentExport = options.transpileOptions?.componentExport ?? "customelement";
483
1083
  const result = transpileSync(code, {
484
1084
  ...jsxOpts,
485
1085
  ...options.transpileOptions,
@@ -489,7 +1089,7 @@ function transformStencil(code, id, options, dev = false, framework = "", onBase
489
1089
  componentMetadata: "compilerstatic",
490
1090
  coreImportPath: "@stencil/core/testing",
491
1091
  style: null
492
- } : { componentExport: "customelement" },
1092
+ } : { componentExport },
493
1093
  styleImportData: "queryparams",
494
1094
  resolveImport: makeResolver(onBaseClass),
495
1095
  buildOverrides: {
@@ -518,9 +1118,10 @@ function transformStencil(code, id, options, dev = false, framework = "", onBase
518
1118
  const className = result.data[0].componentClassName;
519
1119
  let out = result.code;
520
1120
  if (!specPage) {
521
- const namedExport = `\nexport{${className}};`;
522
- out = dev ? result.code + namedExport + buildHmrSnippet(tagName, className, framework) : result.code + namedExport;
1121
+ out = new RegExp(`^export\\s+const\\s+${className}\\b`, "m").test(result.code) ? result.code : `${result.code}\nexport{${className}};`;
1122
+ if (dev) out += buildHmrSnippet(tagName, className, framework);
523
1123
  }
1124
+ if (options.docs) await collectStyleDocsForComponent(result.data[0], id);
524
1125
  const docsComponent = cmpMetaToDocsComponent(result.data[0], id);
525
1126
  return {
526
1127
  code: out,
@@ -546,14 +1147,14 @@ function transpileBaseClass(rawCode, absPath, options) {
546
1147
  return transpileSync(rawCode, {
547
1148
  ...options.transpileOptions,
548
1149
  file: absPath,
549
- componentExport: "customelement",
1150
+ componentExport: options.transpileOptions?.componentExport ?? "customelement",
550
1151
  styleImportData: "queryparams",
551
1152
  transformAsBaseClass: true
552
1153
  }).code;
553
1154
  }
554
1155
  function buildHmrSnippet(tagName, className, framework) {
555
1156
  const tag = JSON.stringify(tagName);
556
- if (framework === "webpack" || framework === "rspack" || framework === "bun") return `\n${className}.__stencil_module__ = import.meta.url;\nvar _sHot = ${framework === "bun" ? "import.meta.hot" : "(typeof module !== 'undefined' && module.hot) || import.meta.webpackHot"};\nif (_sHot) {\n if (_sHot.data && _sHot.data.stencilHmr) {\n var _sCtor = customElements.get(${tag});\n if (_sCtor) Object.getOwnPropertyNames(${className}.prototype).forEach(function(k) {\n if (k !== 'constructor') Object.defineProperty(_sCtor.prototype, k, Object.getOwnPropertyDescriptor(${className}.prototype, k));\n });\n document.querySelectorAll(${tag}).forEach(function(el) { el.connectedCallback && el.connectedCallback(); });\n }\n _sHot.dispose(function(data) { data.stencilHmr = true; });\n _sHot.accept();\n}`;
1157
+ if (framework === "webpack" || framework === "rspack" || framework === "bun") return `\n${className}.__stencil_module__ = import.meta.url;\nvar _sHot = ${framework === "bun" ? "import.meta.hot" : "(typeof module !== 'undefined' && module.hot) || import.meta.webpackHot"};\nif (_sHot) {\n if (_sHot.data && _sHot.data.stencilHmr) {\n var _sCtor = customElements.get(${tag});\n if (_sCtor && _sCtor['s-hmr-apply']) _sCtor['s-hmr-apply'](${className});\n }\n _sHot.dispose(function(data) { data.stencilHmr = true; });\n _sHot.accept();\n}`;
557
1158
  return `\n${className}.__stencil_module__ = import.meta.url;\nif (import.meta.hot && !import.meta.url.includes('s-hmr=')) {\n import.meta.hot.accept(() => {});\n import.meta.hot.on('stencil:hmr', function({ tagName }) {\n if (tagName === ${tag}) {\n var v = Date.now().toString(36);\n document.querySelectorAll(${tag}).forEach(function(el) { el['s-hmr'] && el['s-hmr'](v); });\n }\n });\n}`;
558
1159
  }
559
1160
  function makeResolver(onBaseClass) {
@@ -573,7 +1174,7 @@ function makeResolver(onBaseClass) {
573
1174
  /**
574
1175
  * Unplugin factory for @stencil/unplugin.
575
1176
  *
576
- * Wires together four concerns into a single plugin that works across Vite,
1177
+ * Wires together 6 concerns into a single plugin that works across Vite,
577
1178
  * Rollup, webpack, rspack, and bun:
578
1179
  *
579
1180
  * 1. **Component transform** - `transform` drives `transpileSync` on every
@@ -602,83 +1203,34 @@ function makeResolver(onBaseClass) {
602
1203
  * redirects every bare `@stencil/core` import to `@stencil/core/testing` via
603
1204
  * `resolveId`, so the whole test file - not just compiler output - resolves
604
1205
  * to a single platform instance.
605
- */
606
- const STENCIL_DOCS_ID = "@stencil/unplugin/docs";
607
- const VIRTUAL_DOCS_PREFIX = "\0stencil-docs:";
608
- const docsRegistry = /* @__PURE__ */ new Map();
609
- /**
610
- * Returns the current CEM. Only populated when `docs: true` is set.
611
- * @returns the current CEM, or an empty CEM if `docs: true` was not set.
612
- */
613
- function getStencilCEM() {
614
- return generateManifest({ components: [...docsRegistry.values()] });
615
- }
616
- /**
617
- * Recursively collect `.tsx`/`.ts` file paths under `dir`, pruning
618
- * `node_modules` and hidden directories (`.git`, `.vite`, etc.) as it goes.
619
1206
  *
620
- * `readdirSync(dir, { recursive: true })` can't prune during traversal - it
621
- * walks everything first and only lets the caller filter the flat result
622
- * afterward, which is disastrous under a symlink-heavy `node_modules` (e.g.
623
- * pnpm's `.pnpm` store, which flattens every dependency in the workspace) -
624
- * it can take minutes just to list, blocking `buildStart` the whole time.
1207
+ * 6. **Virtual global-stylesheet imports** - `@import "stencil-component-globals"`/
1208
+ * `"stencil-hydrate"`/`"stencil-css-components"` resolve to generated stylesheets (see
1209
+ * `global-css.ts`) via `resolveId`, or under Vite - which doesn't consult plugins for CSS
1210
+ * `@import` - via an alias. The bundler then treats them like any other CSS. `load` registers
1211
+ * their ingredient files (e.g. a component's `globalStyleUrl`) for watch mode;
1212
+ * `handleHotUpdate` regenerates them for Vite HMR.
625
1213
  *
626
- * @param dir the directory to walk
627
- * @param out accumulator array of absolute file paths, mutated in place
628
- */
629
- function collectSourceFiles(dir, out) {
630
- let entries;
631
- try {
632
- entries = readdirSync(dir, { withFileTypes: true });
633
- } catch {
634
- return;
635
- }
636
- for (const entry of entries) {
637
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
638
- const abs = join(dir, entry.name);
639
- if (entry.isDirectory()) collectSourceFiles(abs, out);
640
- else if (entry.isFile() && (abs.endsWith(".tsx") || abs.endsWith(".ts")) && !abs.endsWith(".d.ts")) out.push(abs);
641
- }
642
- }
643
- /**
644
- * Scan the project for component source files and pre-populate the docs registry.
645
- * @param filter A function to filter which files should be included.
646
- * @returns A promise that resolves when the scan is complete.
1214
+ * 7. **`components.d.ts`** - with `types: true`, written to `srcDir` from the project scan by
1215
+ * core's own generator (see `component-types.ts`), and rewritten as component sources change.
647
1216
  */
648
- async function scanDocs(filter) {
649
- const cwd = process.cwd();
650
- const allFiles = [];
651
- collectSourceFiles(cwd, allFiles);
652
- const files = allFiles.filter((abs) => filter(abs));
653
- await Promise.all(files.map(async (abs) => {
654
- let code;
655
- try {
656
- code = readFileSync(abs, "utf-8");
657
- } catch {
658
- return;
659
- }
660
- if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/.test(code)) return;
661
- const result = await transpile(code, {
662
- file: abs,
663
- componentExport: "customelement"
664
- });
665
- for (const item of result.data ?? []) {
666
- if (!item.tagName) continue;
667
- const component = cmpMetaToDocsComponent(item, abs);
668
- resolveImportedTypes(component, abs);
669
- docsRegistry.set(item.tagName, component);
670
- }
671
- }));
672
- }
1217
+ const STENCIL_DOCS_ID = "@stencil/unplugin/docs";
1218
+ const VIRTUAL_DOCS_PREFIX = "\0stencil-docs:";
673
1219
  const VIRTUAL_BASE_PREFIX = "\0stencil-base:";
674
1220
  const SIGNALS_IMPORT_RE = /from\s+['"]@stencil\/core\/signals['"]/;
1221
+ const getModuleById = (server, id) => server.moduleGraph.getModuleById?.(id) ?? server.moduleGraph.idToModuleMap?.get(id);
1222
+ const invalidate = (server, mod) => server.moduleGraph.invalidateModule(mod, /* @__PURE__ */ new Set(), Date.now(), true);
1223
+ const toViteFilePath = (filePath) => filePath.replace(/\\/g, "/");
1224
+ const PLUGIN_NAME = "@stencil/unplugin";
675
1225
  const unpluginStencil = createUnplugin((options = {}, meta) => {
676
1226
  const { framework } = meta;
677
1227
  const filter = createFilter(options.include ?? [/\.tsx?$/], options.exclude ?? ["node_modules/**"]);
678
1228
  let isDev = options.dev ?? false;
1229
+ let foldFlags = !isDev && options.mode !== "spec-page";
679
1230
  let projectRoot = process.cwd();
680
1231
  let configOverrides = {};
681
1232
  const fileToTagName = /* @__PURE__ */ new Map();
1233
+ const tagToFile = /* @__PURE__ */ new Map();
682
1234
  const cssFileToTagNames = /* @__PURE__ */ new Map();
683
1235
  const cssRealToVirtualIds = /* @__PURE__ */ new Map();
684
1236
  function trackCssFile(realPath, tag, virtualId) {
@@ -692,22 +1244,178 @@ const unpluginStencil = createUnplugin((options = {}, meta) => {
692
1244
  if (baseClassRegistry.has(absPath)) return;
693
1245
  baseClassRegistry.set(absPath, transpileBaseClass(rawCode, absPath, options));
694
1246
  }
1247
+ let hydratedFlag = null;
1248
+ let typesConfig = null;
1249
+ let projectScanPromise = null;
1250
+ function ensureProjectScanned() {
1251
+ if (!projectScanPromise) projectScanPromise = scanDocs(filter, options.docs === true);
1252
+ return projectScanPromise;
1253
+ }
1254
+ async function loadConfig() {
1255
+ const detected = await loadStencilConfig(projectRoot);
1256
+ const merged = detected ? {
1257
+ ...detected,
1258
+ ...options.stencilConfig,
1259
+ compat: {
1260
+ ...detected.compat,
1261
+ ...options.stencilConfig?.compat
1262
+ }
1263
+ } : options.stencilConfig ?? {};
1264
+ configOverrides = stencilConfigToOverrides(merged);
1265
+ if (isTestEnvironment()) configOverrides.isTesting = true;
1266
+ hydratedFlag = validateHydrated({ hydratedFlag: merged.hydratedFlag });
1267
+ typesConfig = {
1268
+ srcDir: resolve(projectRoot, merged.srcDir ?? "src"),
1269
+ signalBacking: !!merged.signalBacking
1270
+ };
1271
+ }
1272
+ let stencilConfigLoaded = null;
1273
+ const virtualCss = createVirtualGlobalCss(async () => {
1274
+ stencilConfigLoaded ??= loadConfig();
1275
+ await Promise.all([stencilConfigLoaded, ensureProjectScanned()]);
1276
+ return {
1277
+ componentGlobalStyles,
1278
+ cssOnlyComponentFiles,
1279
+ tagNames: getHydrateTagNames(docsRegistry.values()),
1280
+ hydratedFlag
1281
+ };
1282
+ }, () => isDev);
1283
+ /**
1284
+ * webpack/rspack: they read the generated stylesheets straight from disk (`load` never runs for
1285
+ * them), so this (re)writes them before every compile and makes their modules depend on the
1286
+ * ingredient files - otherwise an ingredient edit neither triggers a watch-mode rebuild nor
1287
+ * invalidates the cached stylesheet module. `src/` too, so a newly added CSS-only component
1288
+ * does - not the whole project root, where build output would trigger rebuilds in a loop.
1289
+ * @param compiler the webpack/rspack compiler
1290
+ */
1291
+ function watchVirtualCssForCompiles(compiler) {
1292
+ compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async ({ modifiedFiles, removedFiles }) => {
1293
+ if (!virtualCss.started) return;
1294
+ for (const file of [...modifiedFiles ?? [], ...removedFiles ?? []]) {
1295
+ await rescanIfCssOnlyComponent(file);
1296
+ await rescanNewCssOnlyComponents(file);
1297
+ }
1298
+ });
1299
+ compiler.hooks.beforeCompile.tapPromise(PLUGIN_NAME, () => virtualCss.forCompile(projectRoot));
1300
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
1301
+ const addIngredients = (resource, loaderContext) => {
1302
+ if (!resource || !virtualCss.isPath(resource)) return;
1303
+ for (const dep of virtualCss.deps) loaderContext.addDependency(dep);
1304
+ const srcDir = resolve(projectRoot, "src");
1305
+ if (existsSync(srcDir)) loaderContext.addContextDependency(srcDir);
1306
+ };
1307
+ const hooks = compiler.webpack.NormalModule.getCompilationHooks(compilation);
1308
+ if (hooks.beforeLoaders) hooks.beforeLoaders.tap(PLUGIN_NAME, (_loaders, module, ctx) => addIngredients(module.resource, ctx));
1309
+ else hooks.loader?.tap(PLUGIN_NAME, (ctx) => addIngredients(ctx.resourcePath, ctx));
1310
+ });
1311
+ }
1312
+ /**
1313
+ * `options.types`: bring the registries up to date with a changed file - a component source,
1314
+ * or a stylesheet that defines (or used to define) CSS-only components - then rewrite
1315
+ * `components.d.ts` if its content changed.
1316
+ * @param file the changed, added or deleted file
1317
+ */
1318
+ async function updateComponentTypes(file) {
1319
+ if (!options.types || !typesConfig) return;
1320
+ if (/\.tsx?$/.test(file) && !file.endsWith(".d.ts") && filter(file)) await refreshComponentMeta(file);
1321
+ else {
1322
+ await rescanIfCssOnlyComponent(file);
1323
+ await rescanNewCssOnlyComponents(file);
1324
+ }
1325
+ writeComponentTypes(typesConfig);
1326
+ }
1327
+ /**
1328
+ * Vite HMR: tell the client its docs changed, invalidating the docs virtual module.
1329
+ * @param server the dev server
1330
+ */
1331
+ function notifyDocsChanged(server) {
1332
+ const docsVirtualMod = getModuleById(server, VIRTUAL_DOCS_PREFIX);
1333
+ if (docsVirtualMod) invalidate(server, docsVirtualMod);
1334
+ server.ws.send({
1335
+ type: "custom",
1336
+ event: "stencil:docs-update"
1337
+ });
1338
+ }
1339
+ /**
1340
+ * Vite HMR, `docs` only: refresh docs affected by a changed stylesheet - a CSS-only
1341
+ * component's own file, or a regular component's linked `styleUrl`.
1342
+ * @param file the changed stylesheet
1343
+ * @param server the dev server
1344
+ */
1345
+ async function refreshDocsForStylesheet(file, server) {
1346
+ let code = "";
1347
+ try {
1348
+ code = readFileSync(file, "utf-8");
1349
+ } catch {}
1350
+ try {
1351
+ if (code.includes("@component") || isCssOnlyComponentFile(file)) {
1352
+ const prevSnapshot = JSON.stringify(getRegistrySnapshot());
1353
+ await scanCssOnlyDocsFile(file);
1354
+ if (JSON.stringify(getRegistrySnapshot()) !== prevSnapshot) notifyDocsChanged(server);
1355
+ } else {
1356
+ let anyChanged = false;
1357
+ for (const tag of cssFileToTagNames.get(file) ?? []) {
1358
+ const ownerFile = tagToFile.get(tag);
1359
+ if (ownerFile && await refreshComponentDocs(tag, ownerFile)) anyChanged = true;
1360
+ }
1361
+ if (anyChanged) notifyDocsChanged(server);
1362
+ }
1363
+ } catch {}
1364
+ }
1365
+ /**
1366
+ * Vite HMR: regenerate the virtual global stylesheets and hot-update whatever imports the ones
1367
+ * that changed. Vite doesn't watch them (under node_modules), so they're returned as HMR modules
1368
+ * - the documented pattern for hot-updating an untracked dependency.
1369
+ * @param file the changed file
1370
+ * @param server the dev server
1371
+ * @returns the modules to hot-update
1372
+ */
1373
+ async function hotUpdateVirtualCss(file, server) {
1374
+ if (virtualCss.started && !options.docs) await rescanIfCssOnlyComponent(file);
1375
+ const modules = [];
1376
+ for (const written of await virtualCss.hotUpdate(file)) for (const mod of server.moduleGraph.getModulesByFile?.(toViteFilePath(written)) ?? []) {
1377
+ invalidate(server, mod);
1378
+ modules.push(mod);
1379
+ }
1380
+ return modules;
1381
+ }
1382
+ /**
1383
+ * Vite HMR: send `stencil:hmr` for every component the changed file belongs to.
1384
+ * @param file the changed file
1385
+ * @param server the dev server
1386
+ * @returns whether the file belongs to any component
1387
+ */
1388
+ async function hotUpdateComponents(file, server) {
1389
+ const tsxTag = fileToTagName.get(file);
1390
+ const tagNames = new Set(cssFileToTagNames.get(file));
1391
+ if (tsxTag) tagNames.add(tsxTag);
1392
+ if (tagNames.size === 0) return false;
1393
+ for (const virtualId of cssRealToVirtualIds.get(file) ?? []) {
1394
+ const virtualMod = getModuleById(server, virtualId);
1395
+ if (virtualMod) invalidate(server, virtualMod);
1396
+ }
1397
+ if (options.docs && tsxTag && await refreshComponentDocs(tsxTag, file)) notifyDocsChanged(server);
1398
+ for (const tagName of tagNames) server.ws.send({
1399
+ type: "custom",
1400
+ event: "stencil:hmr",
1401
+ data: { tagName }
1402
+ });
1403
+ return true;
1404
+ }
695
1405
  return {
696
1406
  name: "@stencil/unplugin",
697
1407
  async buildStart() {
698
- const detected = await loadStencilConfig(projectRoot);
699
- configOverrides = stencilConfigToOverrides(detected ? {
700
- ...detected,
701
- ...options.stencilConfig,
702
- compat: {
703
- ...detected.compat,
704
- ...options.stencilConfig?.compat
705
- }
706
- } : options.stencilConfig ?? {});
707
- if (options.docs) await scanDocs(filter);
1408
+ stencilConfigLoaded = loadConfig();
1409
+ await stencilConfigLoaded;
1410
+ if (options.docs || options.types) await ensureProjectScanned();
1411
+ if (options.types && typesConfig) writeComponentTypes(typesConfig);
1412
+ virtualCss.useDefaultDir(projectRoot);
1413
+ if (framework === "vite") await virtualCss.forCompile(projectRoot);
708
1414
  },
709
1415
  async resolveId(id, importer) {
710
1416
  if (id === "@stencil/unplugin/docs") return VIRTUAL_DOCS_PREFIX;
1417
+ const virtualCssPath = await virtualCss.resolveId(id, importer);
1418
+ if (virtualCssPath) return virtualCssPath;
711
1419
  if (options.mode === "spec-page" && id === "@stencil/core") return this.resolve("@stencil/core/testing", importer, { skipSelf: true });
712
1420
  if (!importer) return null;
713
1421
  const css = resolveStencilCss(id, importer);
@@ -721,25 +1429,44 @@ const unpluginStencil = createUnplugin((options = {}, meta) => {
721
1429
  transformInclude(id) {
722
1430
  return filter(id.split("?")[0]);
723
1431
  },
724
- transform(code, id) {
1432
+ async transform(code, id, transformOpts) {
725
1433
  const cleanId = id.split("?")[0];
1434
+ const folded = foldFlags && !transformOpts?.ssr ? foldBuildFlags(code, cleanId, {
1435
+ isBrowser: true,
1436
+ isServer: false
1437
+ }) : null;
1438
+ if (folded !== null) code = folded;
726
1439
  if (!configOverrides.vdomSignals && SIGNALS_IMPORT_RE.test(code)) configOverrides = {
727
1440
  ...configOverrides,
728
1441
  vdomSignals: true
729
1442
  };
730
- const result = transformStencil(code, cleanId, options, isDev, framework, registerBaseClass, configOverrides);
731
- if (result?.tagName) fileToTagName.set(cleanId, result.tagName);
1443
+ const result = await transformStencil(code, cleanId, options, isDev, framework, registerBaseClass, configOverrides);
1444
+ if (result?.tagName) {
1445
+ fileToTagName.set(cleanId, result.tagName);
1446
+ tagToFile.set(result.tagName, cleanId);
1447
+ }
732
1448
  if (result?.docsComponent && options.docs) {
733
1449
  resolveImportedTypes(result.docsComponent, cleanId);
734
1450
  docsRegistry.set(result.docsComponent.tag, result.docsComponent);
735
1451
  }
736
- return result;
1452
+ return result ?? (folded !== null ? {
1453
+ code,
1454
+ map: null
1455
+ } : null);
737
1456
  },
738
1457
  loadInclude(id) {
739
- return id === VIRTUAL_DOCS_PREFIX || isStencilCss(id) || id.startsWith(VIRTUAL_BASE_PREFIX);
1458
+ return id === VIRTUAL_DOCS_PREFIX || isStencilCss(id) || id.startsWith(VIRTUAL_BASE_PREFIX) || virtualCss.isPath(id);
740
1459
  },
741
1460
  async load(id) {
742
1461
  if (id === VIRTUAL_DOCS_PREFIX) return `export default ${JSON.stringify(getStencilCEM())}`;
1462
+ if (virtualCss.isPath(id)) {
1463
+ const { code, deps } = await virtualCss.load(id);
1464
+ for (const dep of deps) this.addWatchFile(dep);
1465
+ return {
1466
+ code,
1467
+ map: null
1468
+ };
1469
+ }
743
1470
  if (id.startsWith(VIRTUAL_BASE_PREFIX)) {
744
1471
  const realPath = id.slice(14);
745
1472
  this.addWatchFile(realPath);
@@ -768,55 +1495,55 @@ const unpluginStencil = createUnplugin((options = {}, meta) => {
768
1495
  }
769
1496
  return null;
770
1497
  },
1498
+ async watchChange(id) {
1499
+ if (![
1500
+ "vite",
1501
+ "webpack",
1502
+ "rspack"
1503
+ ].includes(framework) && virtualCss.started) await rescanIfCssOnlyComponent(id);
1504
+ if (framework !== "vite") await updateComponentTypes(id);
1505
+ },
1506
+ webpack(compiler) {
1507
+ watchVirtualCssForCompiles(compiler);
1508
+ },
1509
+ rspack(compiler) {
1510
+ virtualCss.useDefaultDir(compiler.options.context ?? projectRoot);
1511
+ const alias = compiler.options.resolve.alias;
1512
+ compiler.options.resolve.alias = {
1513
+ ...alias && !Array.isArray(alias) ? alias : {},
1514
+ ...virtualGlobalStylesheetAliasMap(virtualCss.dir)
1515
+ };
1516
+ watchVirtualCssForCompiles(compiler);
1517
+ },
771
1518
  vite: {
772
1519
  enforce: "pre",
1520
+ config(userConfig, env) {
1521
+ virtualCss.setDir(resolve(userConfig.root ?? process.cwd(), "node_modules", ".stencil", "virtual-css", env.command));
1522
+ return { resolve: { alias: [virtualGlobalStylesheetAlias(virtualCss.dir)] } };
1523
+ },
773
1524
  configResolved(config) {
774
1525
  isDev = options.dev ?? config.command === "serve";
1526
+ foldFlags = config.command === "build" && options.mode !== "spec-page";
775
1527
  projectRoot = config.root;
776
1528
  },
777
- async handleHotUpdate({ file, server }) {
778
- const tsxTag = fileToTagName.get(file);
779
- const cssTagNames = cssFileToTagNames.get(file);
780
- const tagNames = new Set(cssTagNames);
781
- if (tsxTag) tagNames.add(tsxTag);
782
- if (tagNames.size === 0) return;
783
- const virtualIds = cssRealToVirtualIds.get(file);
784
- if (virtualIds) for (const virtualId of virtualIds) {
785
- const virtualMod = server.moduleGraph.getModuleById?.(virtualId) ?? server.moduleGraph.idToModuleMap?.get(virtualId);
786
- if (virtualMod) server.moduleGraph.invalidateModule(virtualMod, /* @__PURE__ */ new Set(), Date.now(), true);
787
- }
788
- if (options.docs && tsxTag) {
789
- let cemChanged = false;
790
- try {
791
- const prevSnapshot = JSON.stringify(docsRegistry.get(tsxTag));
792
- const code = readFileSync(file, "utf-8");
793
- const result = await transpile(code, {
794
- file,
795
- componentExport: "customelement"
796
- });
797
- for (const item of result.data ?? []) {
798
- if (!item.tagName) continue;
799
- const component = cmpMetaToDocsComponent(item, file);
800
- resolveImportedTypes(component, file);
801
- docsRegistry.set(item.tagName, component);
802
- }
803
- cemChanged = JSON.stringify(docsRegistry.get(tsxTag)) !== prevSnapshot;
804
- } catch {}
805
- if (cemChanged) {
806
- const docsVirtualMod = server.moduleGraph.getModuleById?.(VIRTUAL_DOCS_PREFIX) ?? server.moduleGraph.idToModuleMap?.get(VIRTUAL_DOCS_PREFIX);
807
- if (docsVirtualMod) server.moduleGraph.invalidateModule(docsVirtualMod, /* @__PURE__ */ new Set(), Date.now(), true);
808
- server.ws.send({
809
- type: "custom",
810
- event: "stencil:docs-update"
811
- });
1529
+ configureServer(server) {
1530
+ const onAddedOrDeleted = async (file) => {
1531
+ if (file.endsWith(".css")) {
1532
+ if (options.docs) await refreshDocsForStylesheet(file, server);
1533
+ for (const mod of await hotUpdateVirtualCss(file, server)) await server.reloadModule(mod);
812
1534
  }
813
- }
814
- for (const tagName of tagNames) server.ws.send({
815
- type: "custom",
816
- event: "stencil:hmr",
817
- data: { tagName }
818
- });
819
- return [];
1535
+ await updateComponentTypes(file);
1536
+ };
1537
+ server.watcher.on("add", onAddedOrDeleted);
1538
+ server.watcher.on("unlink", onAddedOrDeleted);
1539
+ },
1540
+ async handleHotUpdate({ file, server }) {
1541
+ if (options.docs && file.endsWith(".css")) await refreshDocsForStylesheet(file, server);
1542
+ const hmrModules = await hotUpdateVirtualCss(file, server);
1543
+ const isComponentFile = await hotUpdateComponents(file, server);
1544
+ await updateComponentTypes(file);
1545
+ if (!isComponentFile && hmrModules.length === 0) return void 0;
1546
+ return hmrModules;
820
1547
  }
821
1548
  }
822
1549
  };