@typestyles/vite 0.5.3 → 0.6.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/README.md +22 -7
- package/dist/index.cjs +147 -19
- package/dist/index.d.cts +16 -5
- package/dist/index.d.ts +16 -5
- package/dist/index.js +149 -21
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -63,13 +63,13 @@ export default defineConfig({
|
|
|
63
63
|
});
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
-
**3. Link the CSS** in your HTML shell (optional — the plugin
|
|
66
|
+
**3. Link the CSS** in your HTML shell (optional — the plugin injects this during dev and build when extraction is enabled):
|
|
67
67
|
|
|
68
68
|
```html
|
|
69
69
|
<link rel="stylesheet" href="/typestyles.css" />
|
|
70
70
|
```
|
|
71
71
|
|
|
72
|
-
During `vite dev`, styles still inject at runtime and HMR works. During `vite build`, the plugin emits `typestyles
|
|
72
|
+
During `vite dev`, styles still inject at runtime and HMR works, and the dev server serves that stable URL. During `vite build`, the plugin emits a content-hashed asset (Vite's `assetFileNames`, usually `assets/typestyles-<hash>.css`), rewrites the link to that href, and defines `__TYPESTYLES_RUNTIME_DISABLED__`. The hashed URL cache-busts on each deploy. Set `extract.fileName` to a literal such as `typestyles.css` to keep a fixed path.
|
|
73
73
|
|
|
74
74
|
Example app: [`examples/vite-app`](../../examples/vite-app)
|
|
75
75
|
|
|
@@ -99,6 +99,13 @@ typestyles({
|
|
|
99
99
|
/** Default: true — fail the build on duplicate recipe / style namespaces */
|
|
100
100
|
warnDuplicates?: boolean;
|
|
101
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Default: true — fail `vite build` when a local module reachable from the app
|
|
104
|
+
* calls `recipe()` and is missing from the extract entry. Set false to extract
|
|
105
|
+
* a subset on purpose.
|
|
106
|
+
*/
|
|
107
|
+
coverage?: boolean;
|
|
108
|
+
|
|
102
109
|
/**
|
|
103
110
|
* - 'runtime': HMR only, no extraction
|
|
104
111
|
* - 'build': extract on vite build; runtime stays on during vite dev (default when modules resolve)
|
|
@@ -109,7 +116,13 @@ typestyles({
|
|
|
109
116
|
extract?: {
|
|
110
117
|
/** Explicit entry files relative to project root */
|
|
111
118
|
modules?: string[];
|
|
112
|
-
/**
|
|
119
|
+
/**
|
|
120
|
+
* Production CSS path.
|
|
121
|
+
* Omitted: content-hashed asset (`assets/typestyles-<hash>.css`).
|
|
122
|
+
* A literal such as `'typestyles.css'` opts out of hashing.
|
|
123
|
+
* `[name]`, `[hash]`, `[hash:N]`, `[ext]`, and `[extname]` are expanded.
|
|
124
|
+
* Dev always serves the stable unhashed URL.
|
|
125
|
+
*/
|
|
113
126
|
fileName?: string;
|
|
114
127
|
};
|
|
115
128
|
});
|
|
@@ -123,7 +136,7 @@ Use when you have multiple entry files or non-standard paths:
|
|
|
123
136
|
typestyles({
|
|
124
137
|
extract: {
|
|
125
138
|
modules: ['src/styles/tokens.ts', 'src/styles/components.ts'],
|
|
126
|
-
fileName: 'assets/typestyles.css',
|
|
139
|
+
fileName: 'assets/typestyles-[hash].css',
|
|
127
140
|
},
|
|
128
141
|
});
|
|
129
142
|
```
|
|
@@ -140,20 +153,22 @@ Even with a convention entry present, this keeps `<style>` injection in producti
|
|
|
140
153
|
|
|
141
154
|
**HMR:** On each `.ts`/`.tsx` module that registers typestyles APIs, the plugin injects `import.meta.hot` accept/dispose handlers. On dispose, it calls `invalidateKeys` from `typestyles/hmr` so stale rules are removed before the module re-executes. HMR code is only injected during `vite dev`, not in production bundles.
|
|
142
155
|
|
|
143
|
-
**Extraction:** On `vite build`, matching entry modules are bundled and executed in Node via `@typestyles/build-runner`. The collected CSS is emitted as a
|
|
156
|
+
**Extraction:** On `vite build`, matching entry modules are bundled and executed in Node via `@typestyles/build-runner`. The collected CSS is emitted as a content-hashed asset so a new deploy cannot be served with a cached copy of the previous stylesheet. In dev, extraction runs on demand when the browser requests `/typestyles.css` so your `<link>` href works without SPA fallback returning HTML.
|
|
144
157
|
|
|
145
158
|
**Duplicate detection:** The plugin scans every source file for namespace strings (`recipe({ name: 'button' })` → `.button-`). Collisions across files fail the build with a clear error.
|
|
146
159
|
|
|
147
160
|
## Verify production output
|
|
148
161
|
|
|
149
|
-
|
|
162
|
+
On `vite build`, the plugin fails if a local module reachable from the app calls `recipe()` and that file is missing from the extract entry. The error names the module and the recipe `name`. Import the module from the convention entry, or set `coverage: false` when the production CSS is meant to omit it.
|
|
163
|
+
|
|
164
|
+
Tokens, themes, and `style()` calls are still execute-and-collect: anything the entry file does not run is omitted. The default build filename includes a content hash. Point `verifyTypestylesBuild` at that file, or set `extract.fileName` to a literal path first:
|
|
150
165
|
|
|
151
166
|
```ts
|
|
152
167
|
import { verifyTypestylesBuild } from '@typestyles/build-runner';
|
|
153
168
|
|
|
154
169
|
verifyTypestylesBuild({
|
|
155
170
|
root: process.cwd(),
|
|
156
|
-
cssFile: 'dist/typestyles
|
|
171
|
+
cssFile: 'dist/assets/typestyles-<hash>.css',
|
|
157
172
|
requiredCssSubstrings: ['.button-base'],
|
|
158
173
|
});
|
|
159
174
|
```
|
package/dist/index.cjs
CHANGED
|
@@ -2,18 +2,49 @@ Object.defineProperties(exports, {
|
|
|
2
2
|
__esModule: { value: true },
|
|
3
3
|
[Symbol.toStringTag]: { value: "Module" }
|
|
4
4
|
});
|
|
5
|
+
let node_crypto = require("node:crypto");
|
|
5
6
|
let node_path = require("node:path");
|
|
6
7
|
let _typestyles_build_runner = require("@typestyles/build-runner");
|
|
7
8
|
//#region src/index.ts
|
|
8
9
|
function resolveExtractModulesForVite(root, extract) {
|
|
9
10
|
return (0, _typestyles_build_runner.resolveExtractModules)(root, extract);
|
|
10
11
|
}
|
|
11
|
-
|
|
12
|
+
const DEFAULT_CSS_FILE_NAME = "typestyles.css";
|
|
13
|
+
const PARKED_CSS_HREF = "#__typestyles_css__";
|
|
14
|
+
function resolveTypestylesCssHref(base, fileName, htmlPath) {
|
|
12
15
|
const normalizedFileName = fileName.replace(/^\//, "");
|
|
16
|
+
if (base.startsWith(".")) {
|
|
17
|
+
const fromDir = node_path.posix.dirname(`/${(htmlPath ?? "index.html").replace(/^\//, "")}`);
|
|
18
|
+
const relative = node_path.posix.relative(fromDir, `/${normalizedFileName}`);
|
|
19
|
+
return relative.startsWith(".") ? relative : `./${relative}`;
|
|
20
|
+
}
|
|
13
21
|
const normalizedBase = base.replace(/\/$/, "") || "";
|
|
14
22
|
if (normalizedBase === "" || normalizedBase === "/") return `/${normalizedFileName}`;
|
|
15
23
|
return `${normalizedBase}/${normalizedFileName}`;
|
|
16
24
|
}
|
|
25
|
+
function cssFileNameHasPlaceholder(fileName) {
|
|
26
|
+
return /\[(?:hash(?::\d+)?|name|extname|ext)\]/.test(fileName);
|
|
27
|
+
}
|
|
28
|
+
function stableDevCssFileName(fileName) {
|
|
29
|
+
if (!fileName) return DEFAULT_CSS_FILE_NAME;
|
|
30
|
+
const normalized = fileName.replace(/^\//, "");
|
|
31
|
+
if (!cssFileNameHasPlaceholder(normalized)) return normalized;
|
|
32
|
+
return normalized.replace(/-?\[hash(?::\d+)?\]/g, "").replace(/\[name\]/g, "typestyles").replace(/\[extname\]/g, ".css").replace(/\[ext\]/g, "css");
|
|
33
|
+
}
|
|
34
|
+
function renderCssFileName(pattern, source) {
|
|
35
|
+
const hash = (0, node_crypto.createHash)("sha256").update(source).digest("base64url");
|
|
36
|
+
return pattern.replace(/\[(hash(?::(\d+))?|name|extname|ext)\]/g, (_match, kind, size) => {
|
|
37
|
+
if (kind === "name") return "typestyles";
|
|
38
|
+
if (kind === "extname") return ".css";
|
|
39
|
+
if (kind === "ext") return "css";
|
|
40
|
+
const length = size ? Number(size) : 8;
|
|
41
|
+
const clamped = Math.min(Math.max(1, length), hash.length);
|
|
42
|
+
return hash.slice(0, clamped);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function isTypestylesStylesheetHref(href, cssHref, bareName) {
|
|
46
|
+
return href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`;
|
|
47
|
+
}
|
|
17
48
|
function htmlLinksTypestylesCss(html, cssHref, fileName) {
|
|
18
49
|
const bareName = fileName.replace(/^\//, "");
|
|
19
50
|
const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
|
|
@@ -21,20 +52,52 @@ function htmlLinksTypestylesCss(html, cssHref, fileName) {
|
|
|
21
52
|
for (const match of html.matchAll(linkPattern)) {
|
|
22
53
|
const href = match[0].match(hrefPattern)?.[1];
|
|
23
54
|
if (!href) continue;
|
|
24
|
-
if (href
|
|
55
|
+
if (isTypestylesStylesheetHref(href, cssHref, bareName)) return true;
|
|
25
56
|
}
|
|
26
57
|
return false;
|
|
27
58
|
}
|
|
59
|
+
function retargetTypestylesStylesheet(html, fileName, nextHref) {
|
|
60
|
+
const bareNames = [...new Set([fileName.replace(/^\//, ""), DEFAULT_CSS_FILE_NAME])];
|
|
61
|
+
return html.replace(/<link\b[^>]*>/gi, (tag) => {
|
|
62
|
+
if (!/\brel=["']stylesheet["']/i.test(tag)) return tag;
|
|
63
|
+
return tag.replace(/\bhref=(["'])([^"']+)\1/i, (attr, quote, href) => {
|
|
64
|
+
if (!bareNames.some((name) => isTypestylesStylesheetHref(href, `/${name}`, name))) return attr;
|
|
65
|
+
return `href=${quote}${nextHref}${quote}`;
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function rebaseRelativeCssUrls(css, depth) {
|
|
70
|
+
if (depth <= 0) return css;
|
|
71
|
+
const up = "../".repeat(depth);
|
|
72
|
+
return css.replace(/url\(\s*(['"]?)([^'")]+?)\1\s*\)/g, (match, quote, url) => {
|
|
73
|
+
if (/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(url)) return match;
|
|
74
|
+
return `url(${quote}${up}${url.replace(/^\.\//, "")}${quote})`;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function formatUnextractedRecipeError(missing, extractEntries) {
|
|
78
|
+
const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
|
|
79
|
+
return [
|
|
80
|
+
"[typestyles] Production extract is missing app recipes:",
|
|
81
|
+
...missing.map((item) => {
|
|
82
|
+
const quoted = item.names.map((name) => `"${name}"`).join(", ");
|
|
83
|
+
return ` ${item.names.length === 1 ? "recipe" : "recipes"} ${quoted} in ${item.modulePath}`;
|
|
84
|
+
}),
|
|
85
|
+
`These modules are reachable from the app and missing from the extract entry (${entries}).`,
|
|
86
|
+
"Import them from the extract entry, or set coverage: false to extract a subset."
|
|
87
|
+
].join("\n");
|
|
88
|
+
}
|
|
28
89
|
function typestylesPlugin(options = {}) {
|
|
29
|
-
const { warnDuplicates = true, extract } = options;
|
|
90
|
+
const { warnDuplicates = true, coverage = true, extract } = options;
|
|
30
91
|
let resolvedExtractModules = [];
|
|
31
92
|
let resolvedMode = "runtime";
|
|
32
93
|
const moduleNamespaces = new Map();
|
|
33
94
|
let resolvedConfig = null;
|
|
34
95
|
let isBuildCommand = false;
|
|
35
96
|
let isServe = false;
|
|
97
|
+
const recipeModules = new Map();
|
|
36
98
|
let devExtractCss = null;
|
|
37
99
|
let devExtractInFlight = null;
|
|
100
|
+
let builtCssFileName = null;
|
|
38
101
|
return {
|
|
39
102
|
name: "typestyles",
|
|
40
103
|
enforce: "pre",
|
|
@@ -55,7 +118,7 @@ function typestylesPlugin(options = {}) {
|
|
|
55
118
|
configureServer(server) {
|
|
56
119
|
if (resolvedExtractModules.length === 0) return;
|
|
57
120
|
if (resolvedMode === "runtime") return;
|
|
58
|
-
const fileName = extract?.fileName
|
|
121
|
+
const fileName = stableDevCssFileName(extract?.fileName);
|
|
59
122
|
const invalidateDevExtract = () => {
|
|
60
123
|
devExtractCss = null;
|
|
61
124
|
devExtractInFlight = null;
|
|
@@ -90,7 +153,8 @@ function typestylesPlugin(options = {}) {
|
|
|
90
153
|
}
|
|
91
154
|
if (!devExtractInFlight) devExtractInFlight = (0, _typestyles_build_runner.runTypestylesBuild)({
|
|
92
155
|
root,
|
|
93
|
-
modules: resolvedExtractModules
|
|
156
|
+
modules: resolvedExtractModules,
|
|
157
|
+
sourceComments: extract?.sourceComments
|
|
94
158
|
}).then((css) => {
|
|
95
159
|
devExtractCss = css;
|
|
96
160
|
return css;
|
|
@@ -108,10 +172,18 @@ function typestylesPlugin(options = {}) {
|
|
|
108
172
|
});
|
|
109
173
|
},
|
|
110
174
|
transform(code, id) {
|
|
175
|
+
if (isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && id.split("?")[0]?.endsWith(".html")) {
|
|
176
|
+
const parked = retargetTypestylesStylesheet(code, stableDevCssFileName(extract?.fileName), PARKED_CSS_HREF);
|
|
177
|
+
if (parked !== code) return {
|
|
178
|
+
code: parked,
|
|
179
|
+
map: null
|
|
180
|
+
};
|
|
181
|
+
}
|
|
111
182
|
if (!/\.[jt]sx?$/.test(id)) return null;
|
|
112
183
|
if (id.includes("node_modules")) return null;
|
|
113
|
-
const { keys, prefixes } = (0, _typestyles_build_runner.extractNamespaces)(code);
|
|
184
|
+
const { keys, prefixes, recipeNames } = (0, _typestyles_build_runner.extractNamespaces)(code);
|
|
114
185
|
const overrideHmr = (0, _typestyles_build_runner.moduleNeedsOverrideHmr)(code);
|
|
186
|
+
if (coverage && isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && recipeNames.length > 0) recipeModules.set(id, recipeNames);
|
|
115
187
|
if (keys.length === 0 && prefixes.length === 0 && !overrideHmr) return null;
|
|
116
188
|
if (warnDuplicates && prefixes.length > 0) (0, _typestyles_build_runner.reportDuplicateNamespaces)(moduleNamespaces, id, prefixes, this);
|
|
117
189
|
if (keys.length > 0 || prefixes.length > 0) moduleNamespaces.set(id, {
|
|
@@ -136,14 +208,30 @@ if (import.meta.hot) {
|
|
|
136
208
|
};
|
|
137
209
|
},
|
|
138
210
|
transformIndexHtml: {
|
|
139
|
-
order: "
|
|
140
|
-
handler(html) {
|
|
211
|
+
order: "post",
|
|
212
|
+
handler(html, ctx) {
|
|
141
213
|
if (resolvedExtractModules.length === 0) return;
|
|
142
214
|
if (resolvedMode === "runtime") return;
|
|
143
215
|
if (!resolvedConfig) return;
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
216
|
+
const stableFileName = stableDevCssFileName(extract?.fileName);
|
|
217
|
+
if (!isBuildCommand) {
|
|
218
|
+
const href = resolveTypestylesCssHref(resolvedConfig.base, stableFileName);
|
|
219
|
+
if (htmlLinksTypestylesCss(html, href, stableFileName)) return;
|
|
220
|
+
return [{
|
|
221
|
+
tag: "link",
|
|
222
|
+
attrs: {
|
|
223
|
+
rel: "stylesheet",
|
|
224
|
+
href
|
|
225
|
+
},
|
|
226
|
+
injectTo: "head"
|
|
227
|
+
}];
|
|
228
|
+
}
|
|
229
|
+
if (!builtCssFileName) return;
|
|
230
|
+
const href = resolveTypestylesCssHref(resolvedConfig.base, builtCssFileName, ctx?.path);
|
|
231
|
+
if (html.includes(PARKED_CSS_HREF)) return html.split(PARKED_CSS_HREF).join(href);
|
|
232
|
+
if (htmlLinksTypestylesCss(html, href, builtCssFileName)) return;
|
|
233
|
+
const retargeted = retargetTypestylesStylesheet(html, stableFileName, href);
|
|
234
|
+
if (retargeted !== html) return retargeted;
|
|
147
235
|
return [{
|
|
148
236
|
tag: "link",
|
|
149
237
|
attrs: {
|
|
@@ -154,23 +242,63 @@ if (import.meta.hot) {
|
|
|
154
242
|
}];
|
|
155
243
|
}
|
|
156
244
|
},
|
|
157
|
-
async generateBundle() {
|
|
245
|
+
async generateBundle(_options, bundle) {
|
|
158
246
|
if (!isBuildCommand) return;
|
|
159
247
|
if (resolvedMode === "runtime") return;
|
|
160
248
|
if (!resolvedExtractModules.length) return;
|
|
161
249
|
if (!resolvedConfig) return;
|
|
162
250
|
const root = resolvedConfig.root ?? process.cwd();
|
|
163
|
-
const
|
|
251
|
+
const requestedFileName = extract?.fileName?.replace(/^\//, "");
|
|
252
|
+
if (coverage && recipeModules.size > 0) {
|
|
253
|
+
let missing = [];
|
|
254
|
+
try {
|
|
255
|
+
missing = await (0, _typestyles_build_runner.findUnextractedRecipes)({
|
|
256
|
+
root,
|
|
257
|
+
extractEntries: resolvedExtractModules,
|
|
258
|
+
recipeModules: [...recipeModules.entries()].map(([id, names]) => ({
|
|
259
|
+
id,
|
|
260
|
+
names
|
|
261
|
+
}))
|
|
262
|
+
});
|
|
263
|
+
} catch (err) {
|
|
264
|
+
this.error(`[typestyles] Failed to check extract coverage: ${err instanceof Error ? err.message : String(err)}`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (missing.length > 0) {
|
|
268
|
+
this.error(formatUnextractedRecipeError(missing, resolvedExtractModules));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
164
272
|
try {
|
|
165
273
|
const css = await (0, _typestyles_build_runner.runTypestylesBuild)({
|
|
166
274
|
root,
|
|
167
|
-
modules: resolvedExtractModules
|
|
168
|
-
|
|
169
|
-
this.emitFile({
|
|
170
|
-
type: "asset",
|
|
171
|
-
fileName,
|
|
172
|
-
source: css
|
|
275
|
+
modules: resolvedExtractModules,
|
|
276
|
+
sourceComments: extract?.sourceComments
|
|
173
277
|
});
|
|
278
|
+
if (requestedFileName && cssFileNameHasPlaceholder(requestedFileName)) {
|
|
279
|
+
builtCssFileName = renderCssFileName(requestedFileName, css);
|
|
280
|
+
this.emitFile({
|
|
281
|
+
type: "asset",
|
|
282
|
+
fileName: builtCssFileName,
|
|
283
|
+
source: css
|
|
284
|
+
});
|
|
285
|
+
} else if (requestedFileName) {
|
|
286
|
+
builtCssFileName = requestedFileName;
|
|
287
|
+
this.emitFile({
|
|
288
|
+
type: "asset",
|
|
289
|
+
fileName: requestedFileName,
|
|
290
|
+
source: css
|
|
291
|
+
});
|
|
292
|
+
} else {
|
|
293
|
+
const referenceId = this.emitFile({
|
|
294
|
+
type: "asset",
|
|
295
|
+
name: DEFAULT_CSS_FILE_NAME,
|
|
296
|
+
source: css
|
|
297
|
+
});
|
|
298
|
+
builtCssFileName = this.getFileName(referenceId);
|
|
299
|
+
const asset = bundle?.[builtCssFileName];
|
|
300
|
+
if (asset?.type === "asset" && typeof asset.source === "string") asset.source = rebaseRelativeCssUrls(asset.source, builtCssFileName.split("/").length - 1);
|
|
301
|
+
}
|
|
174
302
|
} catch (err) {
|
|
175
303
|
this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
|
|
176
304
|
}
|
package/dist/index.d.cts
CHANGED
|
@@ -20,6 +20,14 @@ export interface TypestylesPluginOptions {
|
|
|
20
20
|
* namespace appears in more than one module. Set to `false` to skip this check.
|
|
21
21
|
*/
|
|
22
22
|
warnDuplicates?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* When true (default), fail `vite build` if a local module reachable from the app calls
|
|
25
|
+
* `recipe()` (or `styles.component()`) and that module is missing from the extract entry.
|
|
26
|
+
* The error names the module and the recipe. Set to `false` when the production extract
|
|
27
|
+
* is meant to cover only part of the app. Ignored in `runtime` mode and when nothing
|
|
28
|
+
* is extracted.
|
|
29
|
+
*/
|
|
30
|
+
coverage?: boolean;
|
|
23
31
|
/**
|
|
24
32
|
* Mode for typestyles integration:
|
|
25
33
|
* - `"runtime"`: HMR only, no build-time extraction.
|
|
@@ -28,10 +36,11 @@ export interface TypestylesPluginOptions {
|
|
|
28
36
|
*
|
|
29
37
|
* When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
|
|
30
38
|
* discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
|
|
31
|
-
* injection + HMR (runtime is only disabled during `vite build`)
|
|
32
|
-
*
|
|
33
|
-
* returning HTML for that URL)
|
|
34
|
-
*
|
|
39
|
+
* injection + HMR (runtime is only disabled during `vite build`) and serves extracted CSS at a
|
|
40
|
+
* stable URL (`/typestyles.css`, unless `extract.fileName` sets another path) so
|
|
41
|
+
* `<link href="/typestyles.css">` is valid (avoids SPA fallback returning HTML for that URL).
|
|
42
|
+
* Production emits a content-hashed CSS asset and points the HTML link at it. If no modules
|
|
43
|
+
* are resolved, defaults to `"runtime"`.
|
|
35
44
|
*/
|
|
36
45
|
mode?: TypestylesIntegrationMode;
|
|
37
46
|
/**
|
|
@@ -43,7 +52,9 @@ export interface TypestylesPluginOptions {
|
|
|
43
52
|
extract?: TypestylesExtractOptions;
|
|
44
53
|
}
|
|
45
54
|
/** Public URL path for the extracted CSS asset (respects Vite `base`). */
|
|
46
|
-
export declare function resolveTypestylesCssHref(base: string, fileName: string
|
|
55
|
+
export declare function resolveTypestylesCssHref(base: string, fileName: string,
|
|
56
|
+
/** Root-relative HTML path (e.g. `/nested/index.html`); only used when `base` is relative. */
|
|
57
|
+
htmlPath?: string): string;
|
|
47
58
|
/** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
|
|
48
59
|
export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
|
|
49
60
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -20,6 +20,14 @@ export interface TypestylesPluginOptions {
|
|
|
20
20
|
* namespace appears in more than one module. Set to `false` to skip this check.
|
|
21
21
|
*/
|
|
22
22
|
warnDuplicates?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* When true (default), fail `vite build` if a local module reachable from the app calls
|
|
25
|
+
* `recipe()` (or `styles.component()`) and that module is missing from the extract entry.
|
|
26
|
+
* The error names the module and the recipe. Set to `false` when the production extract
|
|
27
|
+
* is meant to cover only part of the app. Ignored in `runtime` mode and when nothing
|
|
28
|
+
* is extracted.
|
|
29
|
+
*/
|
|
30
|
+
coverage?: boolean;
|
|
23
31
|
/**
|
|
24
32
|
* Mode for typestyles integration:
|
|
25
33
|
* - `"runtime"`: HMR only, no build-time extraction.
|
|
@@ -28,10 +36,11 @@ export interface TypestylesPluginOptions {
|
|
|
28
36
|
*
|
|
29
37
|
* When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
|
|
30
38
|
* discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
|
|
31
|
-
* injection + HMR (runtime is only disabled during `vite build`)
|
|
32
|
-
*
|
|
33
|
-
* returning HTML for that URL)
|
|
34
|
-
*
|
|
39
|
+
* injection + HMR (runtime is only disabled during `vite build`) and serves extracted CSS at a
|
|
40
|
+
* stable URL (`/typestyles.css`, unless `extract.fileName` sets another path) so
|
|
41
|
+
* `<link href="/typestyles.css">` is valid (avoids SPA fallback returning HTML for that URL).
|
|
42
|
+
* Production emits a content-hashed CSS asset and points the HTML link at it. If no modules
|
|
43
|
+
* are resolved, defaults to `"runtime"`.
|
|
35
44
|
*/
|
|
36
45
|
mode?: TypestylesIntegrationMode;
|
|
37
46
|
/**
|
|
@@ -43,7 +52,9 @@ export interface TypestylesPluginOptions {
|
|
|
43
52
|
extract?: TypestylesExtractOptions;
|
|
44
53
|
}
|
|
45
54
|
/** Public URL path for the extracted CSS asset (respects Vite `base`). */
|
|
46
|
-
export declare function resolveTypestylesCssHref(base: string, fileName: string
|
|
55
|
+
export declare function resolveTypestylesCssHref(base: string, fileName: string,
|
|
56
|
+
/** Root-relative HTML path (e.g. `/nested/index.html`); only used when `base` is relative. */
|
|
57
|
+
htmlPath?: string): string;
|
|
47
58
|
/** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
|
|
48
59
|
export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
|
|
49
60
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,46 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { posix, resolve } from "node:path";
|
|
3
|
+
import { DEFAULT_EXTRACT_MODULE_CANDIDATES, discoverDefaultExtractModules, extractNamespaces, findUnextractedRecipes, moduleNeedsOverrideHmr, moduleNeedsOverrideHmr as moduleNeedsOverrideHmr$1, reportDuplicateNamespaces, resolveExtractMode, resolveExtractModules, runTypestylesBuild } from "@typestyles/build-runner";
|
|
3
4
|
//#region src/index.ts
|
|
4
5
|
function resolveExtractModulesForVite(root, extract) {
|
|
5
6
|
return resolveExtractModules(root, extract);
|
|
6
7
|
}
|
|
7
|
-
|
|
8
|
+
const DEFAULT_CSS_FILE_NAME = "typestyles.css";
|
|
9
|
+
const PARKED_CSS_HREF = "#__typestyles_css__";
|
|
10
|
+
function resolveTypestylesCssHref(base, fileName, htmlPath) {
|
|
8
11
|
const normalizedFileName = fileName.replace(/^\//, "");
|
|
12
|
+
if (base.startsWith(".")) {
|
|
13
|
+
const fromDir = posix.dirname(`/${(htmlPath ?? "index.html").replace(/^\//, "")}`);
|
|
14
|
+
const relative = posix.relative(fromDir, `/${normalizedFileName}`);
|
|
15
|
+
return relative.startsWith(".") ? relative : `./${relative}`;
|
|
16
|
+
}
|
|
9
17
|
const normalizedBase = base.replace(/\/$/, "") || "";
|
|
10
18
|
if (normalizedBase === "" || normalizedBase === "/") return `/${normalizedFileName}`;
|
|
11
19
|
return `${normalizedBase}/${normalizedFileName}`;
|
|
12
20
|
}
|
|
21
|
+
function cssFileNameHasPlaceholder(fileName) {
|
|
22
|
+
return /\[(?:hash(?::\d+)?|name|extname|ext)\]/.test(fileName);
|
|
23
|
+
}
|
|
24
|
+
function stableDevCssFileName(fileName) {
|
|
25
|
+
if (!fileName) return DEFAULT_CSS_FILE_NAME;
|
|
26
|
+
const normalized = fileName.replace(/^\//, "");
|
|
27
|
+
if (!cssFileNameHasPlaceholder(normalized)) return normalized;
|
|
28
|
+
return normalized.replace(/-?\[hash(?::\d+)?\]/g, "").replace(/\[name\]/g, "typestyles").replace(/\[extname\]/g, ".css").replace(/\[ext\]/g, "css");
|
|
29
|
+
}
|
|
30
|
+
function renderCssFileName(pattern, source) {
|
|
31
|
+
const hash = createHash("sha256").update(source).digest("base64url");
|
|
32
|
+
return pattern.replace(/\[(hash(?::(\d+))?|name|extname|ext)\]/g, (_match, kind, size) => {
|
|
33
|
+
if (kind === "name") return "typestyles";
|
|
34
|
+
if (kind === "extname") return ".css";
|
|
35
|
+
if (kind === "ext") return "css";
|
|
36
|
+
const length = size ? Number(size) : 8;
|
|
37
|
+
const clamped = Math.min(Math.max(1, length), hash.length);
|
|
38
|
+
return hash.slice(0, clamped);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
function isTypestylesStylesheetHref(href, cssHref, bareName) {
|
|
42
|
+
return href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`;
|
|
43
|
+
}
|
|
13
44
|
function htmlLinksTypestylesCss(html, cssHref, fileName) {
|
|
14
45
|
const bareName = fileName.replace(/^\//, "");
|
|
15
46
|
const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
|
|
@@ -17,20 +48,52 @@ function htmlLinksTypestylesCss(html, cssHref, fileName) {
|
|
|
17
48
|
for (const match of html.matchAll(linkPattern)) {
|
|
18
49
|
const href = match[0].match(hrefPattern)?.[1];
|
|
19
50
|
if (!href) continue;
|
|
20
|
-
if (href
|
|
51
|
+
if (isTypestylesStylesheetHref(href, cssHref, bareName)) return true;
|
|
21
52
|
}
|
|
22
53
|
return false;
|
|
23
54
|
}
|
|
55
|
+
function retargetTypestylesStylesheet(html, fileName, nextHref) {
|
|
56
|
+
const bareNames = [...new Set([fileName.replace(/^\//, ""), DEFAULT_CSS_FILE_NAME])];
|
|
57
|
+
return html.replace(/<link\b[^>]*>/gi, (tag) => {
|
|
58
|
+
if (!/\brel=["']stylesheet["']/i.test(tag)) return tag;
|
|
59
|
+
return tag.replace(/\bhref=(["'])([^"']+)\1/i, (attr, quote, href) => {
|
|
60
|
+
if (!bareNames.some((name) => isTypestylesStylesheetHref(href, `/${name}`, name))) return attr;
|
|
61
|
+
return `href=${quote}${nextHref}${quote}`;
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function rebaseRelativeCssUrls(css, depth) {
|
|
66
|
+
if (depth <= 0) return css;
|
|
67
|
+
const up = "../".repeat(depth);
|
|
68
|
+
return css.replace(/url\(\s*(['"]?)([^'")]+?)\1\s*\)/g, (match, quote, url) => {
|
|
69
|
+
if (/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(url)) return match;
|
|
70
|
+
return `url(${quote}${up}${url.replace(/^\.\//, "")}${quote})`;
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function formatUnextractedRecipeError(missing, extractEntries) {
|
|
74
|
+
const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
|
|
75
|
+
return [
|
|
76
|
+
"[typestyles] Production extract is missing app recipes:",
|
|
77
|
+
...missing.map((item) => {
|
|
78
|
+
const quoted = item.names.map((name) => `"${name}"`).join(", ");
|
|
79
|
+
return ` ${item.names.length === 1 ? "recipe" : "recipes"} ${quoted} in ${item.modulePath}`;
|
|
80
|
+
}),
|
|
81
|
+
`These modules are reachable from the app and missing from the extract entry (${entries}).`,
|
|
82
|
+
"Import them from the extract entry, or set coverage: false to extract a subset."
|
|
83
|
+
].join("\n");
|
|
84
|
+
}
|
|
24
85
|
function typestylesPlugin(options = {}) {
|
|
25
|
-
const { warnDuplicates = true, extract } = options;
|
|
86
|
+
const { warnDuplicates = true, coverage = true, extract } = options;
|
|
26
87
|
let resolvedExtractModules = [];
|
|
27
88
|
let resolvedMode = "runtime";
|
|
28
89
|
const moduleNamespaces = new Map();
|
|
29
90
|
let resolvedConfig = null;
|
|
30
91
|
let isBuildCommand = false;
|
|
31
92
|
let isServe = false;
|
|
93
|
+
const recipeModules = new Map();
|
|
32
94
|
let devExtractCss = null;
|
|
33
95
|
let devExtractInFlight = null;
|
|
96
|
+
let builtCssFileName = null;
|
|
34
97
|
return {
|
|
35
98
|
name: "typestyles",
|
|
36
99
|
enforce: "pre",
|
|
@@ -51,7 +114,7 @@ function typestylesPlugin(options = {}) {
|
|
|
51
114
|
configureServer(server) {
|
|
52
115
|
if (resolvedExtractModules.length === 0) return;
|
|
53
116
|
if (resolvedMode === "runtime") return;
|
|
54
|
-
const fileName = extract?.fileName
|
|
117
|
+
const fileName = stableDevCssFileName(extract?.fileName);
|
|
55
118
|
const invalidateDevExtract = () => {
|
|
56
119
|
devExtractCss = null;
|
|
57
120
|
devExtractInFlight = null;
|
|
@@ -86,7 +149,8 @@ function typestylesPlugin(options = {}) {
|
|
|
86
149
|
}
|
|
87
150
|
if (!devExtractInFlight) devExtractInFlight = runTypestylesBuild({
|
|
88
151
|
root,
|
|
89
|
-
modules: resolvedExtractModules
|
|
152
|
+
modules: resolvedExtractModules,
|
|
153
|
+
sourceComments: extract?.sourceComments
|
|
90
154
|
}).then((css) => {
|
|
91
155
|
devExtractCss = css;
|
|
92
156
|
return css;
|
|
@@ -104,10 +168,18 @@ function typestylesPlugin(options = {}) {
|
|
|
104
168
|
});
|
|
105
169
|
},
|
|
106
170
|
transform(code, id) {
|
|
171
|
+
if (isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && id.split("?")[0]?.endsWith(".html")) {
|
|
172
|
+
const parked = retargetTypestylesStylesheet(code, stableDevCssFileName(extract?.fileName), PARKED_CSS_HREF);
|
|
173
|
+
if (parked !== code) return {
|
|
174
|
+
code: parked,
|
|
175
|
+
map: null
|
|
176
|
+
};
|
|
177
|
+
}
|
|
107
178
|
if (!/\.[jt]sx?$/.test(id)) return null;
|
|
108
179
|
if (id.includes("node_modules")) return null;
|
|
109
|
-
const { keys, prefixes } = extractNamespaces(code);
|
|
180
|
+
const { keys, prefixes, recipeNames } = extractNamespaces(code);
|
|
110
181
|
const overrideHmr = moduleNeedsOverrideHmr$1(code);
|
|
182
|
+
if (coverage && isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && recipeNames.length > 0) recipeModules.set(id, recipeNames);
|
|
111
183
|
if (keys.length === 0 && prefixes.length === 0 && !overrideHmr) return null;
|
|
112
184
|
if (warnDuplicates && prefixes.length > 0) reportDuplicateNamespaces(moduleNamespaces, id, prefixes, this);
|
|
113
185
|
if (keys.length > 0 || prefixes.length > 0) moduleNamespaces.set(id, {
|
|
@@ -132,14 +204,30 @@ if (import.meta.hot) {
|
|
|
132
204
|
};
|
|
133
205
|
},
|
|
134
206
|
transformIndexHtml: {
|
|
135
|
-
order: "
|
|
136
|
-
handler(html) {
|
|
207
|
+
order: "post",
|
|
208
|
+
handler(html, ctx) {
|
|
137
209
|
if (resolvedExtractModules.length === 0) return;
|
|
138
210
|
if (resolvedMode === "runtime") return;
|
|
139
211
|
if (!resolvedConfig) return;
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
212
|
+
const stableFileName = stableDevCssFileName(extract?.fileName);
|
|
213
|
+
if (!isBuildCommand) {
|
|
214
|
+
const href = resolveTypestylesCssHref(resolvedConfig.base, stableFileName);
|
|
215
|
+
if (htmlLinksTypestylesCss(html, href, stableFileName)) return;
|
|
216
|
+
return [{
|
|
217
|
+
tag: "link",
|
|
218
|
+
attrs: {
|
|
219
|
+
rel: "stylesheet",
|
|
220
|
+
href
|
|
221
|
+
},
|
|
222
|
+
injectTo: "head"
|
|
223
|
+
}];
|
|
224
|
+
}
|
|
225
|
+
if (!builtCssFileName) return;
|
|
226
|
+
const href = resolveTypestylesCssHref(resolvedConfig.base, builtCssFileName, ctx?.path);
|
|
227
|
+
if (html.includes(PARKED_CSS_HREF)) return html.split(PARKED_CSS_HREF).join(href);
|
|
228
|
+
if (htmlLinksTypestylesCss(html, href, builtCssFileName)) return;
|
|
229
|
+
const retargeted = retargetTypestylesStylesheet(html, stableFileName, href);
|
|
230
|
+
if (retargeted !== html) return retargeted;
|
|
143
231
|
return [{
|
|
144
232
|
tag: "link",
|
|
145
233
|
attrs: {
|
|
@@ -150,23 +238,63 @@ if (import.meta.hot) {
|
|
|
150
238
|
}];
|
|
151
239
|
}
|
|
152
240
|
},
|
|
153
|
-
async generateBundle() {
|
|
241
|
+
async generateBundle(_options, bundle) {
|
|
154
242
|
if (!isBuildCommand) return;
|
|
155
243
|
if (resolvedMode === "runtime") return;
|
|
156
244
|
if (!resolvedExtractModules.length) return;
|
|
157
245
|
if (!resolvedConfig) return;
|
|
158
246
|
const root = resolvedConfig.root ?? process.cwd();
|
|
159
|
-
const
|
|
247
|
+
const requestedFileName = extract?.fileName?.replace(/^\//, "");
|
|
248
|
+
if (coverage && recipeModules.size > 0) {
|
|
249
|
+
let missing = [];
|
|
250
|
+
try {
|
|
251
|
+
missing = await findUnextractedRecipes({
|
|
252
|
+
root,
|
|
253
|
+
extractEntries: resolvedExtractModules,
|
|
254
|
+
recipeModules: [...recipeModules.entries()].map(([id, names]) => ({
|
|
255
|
+
id,
|
|
256
|
+
names
|
|
257
|
+
}))
|
|
258
|
+
});
|
|
259
|
+
} catch (err) {
|
|
260
|
+
this.error(`[typestyles] Failed to check extract coverage: ${err instanceof Error ? err.message : String(err)}`);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (missing.length > 0) {
|
|
264
|
+
this.error(formatUnextractedRecipeError(missing, resolvedExtractModules));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
160
268
|
try {
|
|
161
269
|
const css = await runTypestylesBuild({
|
|
162
270
|
root,
|
|
163
|
-
modules: resolvedExtractModules
|
|
164
|
-
|
|
165
|
-
this.emitFile({
|
|
166
|
-
type: "asset",
|
|
167
|
-
fileName,
|
|
168
|
-
source: css
|
|
271
|
+
modules: resolvedExtractModules,
|
|
272
|
+
sourceComments: extract?.sourceComments
|
|
169
273
|
});
|
|
274
|
+
if (requestedFileName && cssFileNameHasPlaceholder(requestedFileName)) {
|
|
275
|
+
builtCssFileName = renderCssFileName(requestedFileName, css);
|
|
276
|
+
this.emitFile({
|
|
277
|
+
type: "asset",
|
|
278
|
+
fileName: builtCssFileName,
|
|
279
|
+
source: css
|
|
280
|
+
});
|
|
281
|
+
} else if (requestedFileName) {
|
|
282
|
+
builtCssFileName = requestedFileName;
|
|
283
|
+
this.emitFile({
|
|
284
|
+
type: "asset",
|
|
285
|
+
fileName: requestedFileName,
|
|
286
|
+
source: css
|
|
287
|
+
});
|
|
288
|
+
} else {
|
|
289
|
+
const referenceId = this.emitFile({
|
|
290
|
+
type: "asset",
|
|
291
|
+
name: DEFAULT_CSS_FILE_NAME,
|
|
292
|
+
source: css
|
|
293
|
+
});
|
|
294
|
+
builtCssFileName = this.getFileName(referenceId);
|
|
295
|
+
const asset = bundle?.[builtCssFileName];
|
|
296
|
+
if (asset?.type === "asset" && typeof asset.source === "string") asset.source = rebaseRelativeCssUrls(asset.source, builtCssFileName.split("/").length - 1);
|
|
297
|
+
}
|
|
170
298
|
} catch (err) {
|
|
171
299
|
this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
|
|
172
300
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@typestyles/vite",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Vite plugin for typestyles HMR support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -41,10 +41,10 @@
|
|
|
41
41
|
"typescript": "^6.0.0",
|
|
42
42
|
"vite": "npm:@voidzero-dev/vite-plus-core@1.3.0",
|
|
43
43
|
"vite-plus": "1.3.0",
|
|
44
|
-
"typestyles": "0.
|
|
44
|
+
"typestyles": "0.34.0"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@typestyles/build-runner": "0.
|
|
47
|
+
"@typestyles/build-runner": "0.7.0"
|
|
48
48
|
},
|
|
49
49
|
"scripts": {
|
|
50
50
|
"build": "vp pack",
|