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