@typestyles/vite 0.5.4 → 0.7.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 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 auto-injects this during dev and build when extraction is enabled):
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.css`, defines `__TYPESTYLES_RUNTIME_DISABLED__`, and the browser loads one cacheable stylesheet.
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
 
@@ -116,7 +116,13 @@ typestyles({
116
116
  extract?: {
117
117
  /** Explicit entry files relative to project root */
118
118
  modules?: string[];
119
- /** Output asset name. Default: 'typestyles.css' */
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
+ */
120
126
  fileName?: string;
121
127
  };
122
128
  });
@@ -130,7 +136,7 @@ Use when you have multiple entry files or non-standard paths:
130
136
  typestyles({
131
137
  extract: {
132
138
  modules: ['src/styles/tokens.ts', 'src/styles/components.ts'],
133
- fileName: 'assets/typestyles.css',
139
+ fileName: 'assets/typestyles-[hash].css',
134
140
  },
135
141
  });
136
142
  ```
@@ -147,7 +153,7 @@ Even with a convention entry present, this keeps `<style>` injection in producti
147
153
 
148
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.
149
155
 
150
- **Extraction:** On `vite build`, matching entry modules are bundled and executed in Node via `@typestyles/build-runner`. The collected CSS is emitted as a static asset. In dev, the same extraction runs on demand when the browser requests `/typestyles.css` so your `<link>` href works without SPA fallback returning HTML.
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.
151
157
 
152
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.
153
159
 
@@ -155,14 +161,14 @@ Even with a convention entry present, this keeps `<style>` injection in producti
155
161
 
156
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.
157
163
 
158
- Tokens, themes, and `style()` calls are still execute-and-collect: anything the entry file does not run is omitted. After `vite build`, assert on the emitted file:
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:
159
165
 
160
166
  ```ts
161
167
  import { verifyTypestylesBuild } from '@typestyles/build-runner';
162
168
 
163
169
  verifyTypestylesBuild({
164
170
  root: process.cwd(),
165
- cssFile: 'dist/typestyles.css',
171
+ cssFile: 'dist/assets/typestyles-<hash>.css',
166
172
  requiredCssSubstrings: ['.button-base'],
167
173
  });
168
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
- function resolveTypestylesCssHref(base, fileName) {
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,10 +52,28 @@ 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 === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) return true;
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
+ }
28
77
  function formatUnextractedRecipeError(missing, extractEntries) {
29
78
  const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
30
79
  return [
@@ -38,7 +87,7 @@ function formatUnextractedRecipeError(missing, extractEntries) {
38
87
  ].join("\n");
39
88
  }
40
89
  function typestylesPlugin(options = {}) {
41
- const { warnDuplicates = true, coverage = true, extract } = options;
90
+ const { warnDuplicates = true, coverage = true, extract, compile = false } = options;
42
91
  let resolvedExtractModules = [];
43
92
  let resolvedMode = "runtime";
44
93
  const moduleNamespaces = new Map();
@@ -48,7 +97,19 @@ function typestylesPlugin(options = {}) {
48
97
  const recipeModules = new Map();
49
98
  let devExtractCss = null;
50
99
  let devExtractInFlight = null;
51
- return {
100
+ let extraction = null;
101
+ let planIndex = null;
102
+ function extractOnce(root) {
103
+ extraction ??= (0, _typestyles_build_runner.runTypestylesExtract)({
104
+ root,
105
+ modules: resolvedExtractModules,
106
+ sourceComments: extract?.sourceComments
107
+ });
108
+ return extraction;
109
+ }
110
+ const compileEnabled = () => compile && isBuildCommand && resolvedMode === "build" && !resolvedConfig?.build?.ssr && resolvedExtractModules.length > 0;
111
+ let builtCssFileName = null;
112
+ const main = {
52
113
  name: "typestyles",
53
114
  enforce: "pre",
54
115
  config(config, env) {
@@ -61,6 +122,25 @@ function typestylesPlugin(options = {}) {
61
122
  };
62
123
  return config;
63
124
  },
125
+ async resolveId(source, importer, resolveOptions) {
126
+ if (!isBuildCommand || resolvedMode !== "build" || !(0, _typestyles_build_runner.isSheetRequest)(source)) return null;
127
+ if (resolveOptions?.ssr) return null;
128
+ const resolved = await this.resolve(source, importer, {
129
+ ...resolveOptions,
130
+ skipSelf: true
131
+ });
132
+ if (!resolved) return null;
133
+ const noop = (0, _typestyles_build_runner.toZeroRuntimeSheetId)(resolved.id);
134
+ return noop ? {
135
+ ...resolved,
136
+ id: noop
137
+ } : null;
138
+ },
139
+ async buildStart() {
140
+ extraction = null;
141
+ planIndex = null;
142
+ if (compileEnabled()) await extractOnce(resolvedConfig?.root ?? process.cwd());
143
+ },
64
144
  configResolved(config) {
65
145
  resolvedConfig = config;
66
146
  isServe = config.command === "serve";
@@ -68,7 +148,7 @@ function typestylesPlugin(options = {}) {
68
148
  configureServer(server) {
69
149
  if (resolvedExtractModules.length === 0) return;
70
150
  if (resolvedMode === "runtime") return;
71
- const fileName = extract?.fileName ?? "typestyles.css";
151
+ const fileName = stableDevCssFileName(extract?.fileName);
72
152
  const invalidateDevExtract = () => {
73
153
  devExtractCss = null;
74
154
  devExtractInFlight = null;
@@ -103,7 +183,8 @@ function typestylesPlugin(options = {}) {
103
183
  }
104
184
  if (!devExtractInFlight) devExtractInFlight = (0, _typestyles_build_runner.runTypestylesBuild)({
105
185
  root,
106
- modules: resolvedExtractModules
186
+ modules: resolvedExtractModules,
187
+ sourceComments: extract?.sourceComments
107
188
  }).then((css) => {
108
189
  devExtractCss = css;
109
190
  return css;
@@ -121,6 +202,13 @@ function typestylesPlugin(options = {}) {
121
202
  });
122
203
  },
123
204
  transform(code, id) {
205
+ if (isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && id.split("?")[0]?.endsWith(".html")) {
206
+ const parked = retargetTypestylesStylesheet(code, stableDevCssFileName(extract?.fileName), PARKED_CSS_HREF);
207
+ if (parked !== code) return {
208
+ code: parked,
209
+ map: null
210
+ };
211
+ }
124
212
  if (!/\.[jt]sx?$/.test(id)) return null;
125
213
  if (id.includes("node_modules")) return null;
126
214
  const { keys, prefixes, recipeNames } = (0, _typestyles_build_runner.extractNamespaces)(code);
@@ -150,14 +238,30 @@ if (import.meta.hot) {
150
238
  };
151
239
  },
152
240
  transformIndexHtml: {
153
- order: "pre",
154
- handler(html) {
241
+ order: "post",
242
+ handler(html, ctx) {
155
243
  if (resolvedExtractModules.length === 0) return;
156
244
  if (resolvedMode === "runtime") return;
157
245
  if (!resolvedConfig) return;
158
- const fileName = extract?.fileName ?? "typestyles.css";
159
- const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
160
- if (htmlLinksTypestylesCss(html, href, fileName)) return;
246
+ const stableFileName = stableDevCssFileName(extract?.fileName);
247
+ if (!isBuildCommand) {
248
+ const href = resolveTypestylesCssHref(resolvedConfig.base, stableFileName);
249
+ if (htmlLinksTypestylesCss(html, href, stableFileName)) return;
250
+ return [{
251
+ tag: "link",
252
+ attrs: {
253
+ rel: "stylesheet",
254
+ href
255
+ },
256
+ injectTo: "head"
257
+ }];
258
+ }
259
+ if (!builtCssFileName) return;
260
+ const href = resolveTypestylesCssHref(resolvedConfig.base, builtCssFileName, ctx?.path);
261
+ if (html.includes(PARKED_CSS_HREF)) return html.split(PARKED_CSS_HREF).join(href);
262
+ if (htmlLinksTypestylesCss(html, href, builtCssFileName)) return;
263
+ const retargeted = retargetTypestylesStylesheet(html, stableFileName, href);
264
+ if (retargeted !== html) return retargeted;
161
265
  return [{
162
266
  tag: "link",
163
267
  attrs: {
@@ -168,13 +272,21 @@ if (import.meta.hot) {
168
272
  }];
169
273
  }
170
274
  },
171
- async generateBundle() {
275
+ async generateBundle(_options, bundle) {
172
276
  if (!isBuildCommand) return;
277
+ if (resolvedMode === "build" && !resolvedConfig?.build?.ssr) {
278
+ const leaked = (0, _typestyles_build_runner.findRealSheetModules)(Object.values(bundle ?? {}).flatMap((chunk) => chunk.type === "chunk" ? Object.keys(chunk.modules) : []));
279
+ if (leaked.length > 0) this.warn((0, _typestyles_build_runner.zeroRuntimeLeakMessage)(leaked));
280
+ if (compileEnabled()) {
281
+ const warning = (0, _typestyles_build_runner.lingeringRuntimeWarning)(bundle ?? {}, (id) => this.getModuleInfo(id)?.importers, resolvedConfig?.root ?? process.cwd());
282
+ if (warning) this.warn(warning);
283
+ }
284
+ }
173
285
  if (resolvedMode === "runtime") return;
174
286
  if (!resolvedExtractModules.length) return;
175
287
  if (!resolvedConfig) return;
176
288
  const root = resolvedConfig.root ?? process.cwd();
177
- const fileName = extract?.fileName ?? "typestyles.css";
289
+ const requestedFileName = extract?.fileName?.replace(/^\//, "");
178
290
  if (coverage && recipeModules.size > 0) {
179
291
  let missing = [];
180
292
  try {
@@ -196,20 +308,50 @@ if (import.meta.hot) {
196
308
  }
197
309
  }
198
310
  try {
199
- const css = await (0, _typestyles_build_runner.runTypestylesBuild)({
200
- root,
201
- modules: resolvedExtractModules
202
- });
203
- this.emitFile({
204
- type: "asset",
205
- fileName,
206
- source: css
207
- });
311
+ const { css } = await extractOnce(root);
312
+ if (requestedFileName && cssFileNameHasPlaceholder(requestedFileName)) {
313
+ builtCssFileName = renderCssFileName(requestedFileName, css);
314
+ this.emitFile({
315
+ type: "asset",
316
+ fileName: builtCssFileName,
317
+ source: css
318
+ });
319
+ } else if (requestedFileName) {
320
+ builtCssFileName = requestedFileName;
321
+ this.emitFile({
322
+ type: "asset",
323
+ fileName: requestedFileName,
324
+ source: css
325
+ });
326
+ } else {
327
+ const referenceId = this.emitFile({
328
+ type: "asset",
329
+ name: DEFAULT_CSS_FILE_NAME,
330
+ source: css
331
+ });
332
+ builtCssFileName = this.getFileName(referenceId);
333
+ const asset = bundle?.[builtCssFileName];
334
+ if (asset?.type === "asset" && typeof asset.source === "string") asset.source = rebaseRelativeCssUrls(asset.source, builtCssFileName.split("/").length - 1);
335
+ }
208
336
  } catch (err) {
209
337
  this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
210
338
  }
211
339
  }
212
340
  };
341
+ if (!compile) return main;
342
+ return [main, {
343
+ name: "typestyles:compile",
344
+ apply: "build",
345
+ enforce: "post",
346
+ async transform(code, id) {
347
+ if (!compileEnabled() || !(0, _typestyles_build_runner.isTransformableId)(id)) return null;
348
+ planIndex ??= (0, _typestyles_build_runner.indexPlans)((await extractOnce(resolvedConfig?.root ?? process.cwd())).plans);
349
+ return (0, _typestyles_build_runner.transformRecipeCalls)(code, planIndex, (source) => this.parse(source), id);
350
+ },
351
+ shouldTransformCachedModule({ code }) {
352
+ return compileEnabled() && (0, _typestyles_build_runner.mayNeedRecompile)(code);
353
+ }
354
+ }];
213
355
  }
214
356
  //#endregion
215
357
  Object.defineProperty(exports, "DEFAULT_EXTRACT_MODULE_CANDIDATES", {
package/dist/index.d.cts CHANGED
@@ -36,10 +36,11 @@ export interface TypestylesPluginOptions {
36
36
  *
37
37
  * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
38
38
  * discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
39
- * injection + HMR (runtime is only disabled during `vite build`), serves the same extracted CSS
40
- * at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA fallback
41
- * returning HTML for that URL), and production emits the CSS file. If no modules are resolved,
42
- * defaults to `"runtime"`.
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"`.
43
44
  */
44
45
  mode?: TypestylesIntegrationMode;
45
46
  /**
@@ -49,9 +50,19 @@ export interface TypestylesPluginOptions {
49
50
  * {@link discoverDefaultExtractModules}); if none exist, stays in runtime-only mode.
50
51
  */
51
52
  extract?: TypestylesExtractOptions;
53
+ /**
54
+ * Experimental. In `"build"` mode on client builds, replace `recipe()` definitions with
55
+ * the small call-behavior plans recorded during extraction, so the style configs, token
56
+ * tables and CSS machinery they reference tree-shake out of the client bundle. Class
57
+ * names and `data-*` attributes are unchanged. Calls whose behavior can't be planned keep
58
+ * the runtime. Returns an array of two plugins when `true`.
59
+ */
60
+ compile?: boolean;
52
61
  }
53
62
  /** Public URL path for the extracted CSS asset (respects Vite `base`). */
54
- export declare function resolveTypestylesCssHref(base: string, fileName: string): string;
63
+ export declare function resolveTypestylesCssHref(base: string, fileName: string,
64
+ /** Root-relative HTML path (e.g. `/nested/index.html`); only used when `base` is relative. */
65
+ htmlPath?: string): string;
55
66
  /** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
56
67
  export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
57
68
  /**
@@ -62,6 +73,9 @@ export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fi
62
73
  * before re-execution. Files may import from a local re-export such as `./typestyles` rather
63
74
  * than `from 'typestyles'` directly — we key off API call patterns in the source, not the import path.
64
75
  */
65
- export default function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
76
+ declare function typestylesPlugin(options: TypestylesPluginOptions & {
77
+ compile: true;
78
+ }): Plugin[];
79
+ declare function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
66
80
  //#endregion
67
- export { DEFAULT_EXTRACT_MODULE_CANDIDATES, type TypestylesExtractOptions, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr };
81
+ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, type TypestylesExtractOptions, typestylesPlugin as default, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr };
package/dist/index.d.ts CHANGED
@@ -36,10 +36,11 @@ export interface TypestylesPluginOptions {
36
36
  *
37
37
  * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
38
38
  * discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
39
- * injection + HMR (runtime is only disabled during `vite build`), serves the same extracted CSS
40
- * at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA fallback
41
- * returning HTML for that URL), and production emits the CSS file. If no modules are resolved,
42
- * defaults to `"runtime"`.
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"`.
43
44
  */
44
45
  mode?: TypestylesIntegrationMode;
45
46
  /**
@@ -49,9 +50,19 @@ export interface TypestylesPluginOptions {
49
50
  * {@link discoverDefaultExtractModules}); if none exist, stays in runtime-only mode.
50
51
  */
51
52
  extract?: TypestylesExtractOptions;
53
+ /**
54
+ * Experimental. In `"build"` mode on client builds, replace `recipe()` definitions with
55
+ * the small call-behavior plans recorded during extraction, so the style configs, token
56
+ * tables and CSS machinery they reference tree-shake out of the client bundle. Class
57
+ * names and `data-*` attributes are unchanged. Calls whose behavior can't be planned keep
58
+ * the runtime. Returns an array of two plugins when `true`.
59
+ */
60
+ compile?: boolean;
52
61
  }
53
62
  /** Public URL path for the extracted CSS asset (respects Vite `base`). */
54
- export declare function resolveTypestylesCssHref(base: string, fileName: string): string;
63
+ export declare function resolveTypestylesCssHref(base: string, fileName: string,
64
+ /** Root-relative HTML path (e.g. `/nested/index.html`); only used when `base` is relative. */
65
+ htmlPath?: string): string;
55
66
  /** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
56
67
  export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
57
68
  /**
@@ -62,6 +73,9 @@ export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fi
62
73
  * before re-execution. Files may import from a local re-export such as `./typestyles` rather
63
74
  * than `from 'typestyles'` directly — we key off API call patterns in the source, not the import path.
64
75
  */
65
- export default function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
76
+ declare function typestylesPlugin(options: TypestylesPluginOptions & {
77
+ compile: true;
78
+ }): Plugin[];
79
+ declare function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
66
80
  //#endregion
67
- export { DEFAULT_EXTRACT_MODULE_CANDIDATES, type TypestylesExtractOptions, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr };
81
+ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, type TypestylesExtractOptions, typestylesPlugin as default, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr };
package/dist/index.js CHANGED
@@ -1,15 +1,46 @@
1
- import { resolve } from "node:path";
2
- import { DEFAULT_EXTRACT_MODULE_CANDIDATES, discoverDefaultExtractModules, extractNamespaces, findUnextractedRecipes, moduleNeedsOverrideHmr, moduleNeedsOverrideHmr as moduleNeedsOverrideHmr$1, reportDuplicateNamespaces, resolveExtractMode, resolveExtractModules, runTypestylesBuild } from "@typestyles/build-runner";
1
+ import { createHash } from "node:crypto";
2
+ import { posix, resolve } from "node:path";
3
+ import { DEFAULT_EXTRACT_MODULE_CANDIDATES, discoverDefaultExtractModules, extractNamespaces, findRealSheetModules, findUnextractedRecipes, indexPlans, isSheetRequest, isTransformableId, lingeringRuntimeWarning, mayNeedRecompile, moduleNeedsOverrideHmr, moduleNeedsOverrideHmr as moduleNeedsOverrideHmr$1, reportDuplicateNamespaces, resolveExtractMode, resolveExtractModules, runTypestylesBuild, runTypestylesExtract, toZeroRuntimeSheetId, transformRecipeCalls, zeroRuntimeLeakMessage } 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
- function resolveTypestylesCssHref(base, fileName) {
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,10 +48,28 @@ 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 === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) return true;
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
+ }
24
73
  function formatUnextractedRecipeError(missing, extractEntries) {
25
74
  const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
26
75
  return [
@@ -34,7 +83,7 @@ function formatUnextractedRecipeError(missing, extractEntries) {
34
83
  ].join("\n");
35
84
  }
36
85
  function typestylesPlugin(options = {}) {
37
- const { warnDuplicates = true, coverage = true, extract } = options;
86
+ const { warnDuplicates = true, coverage = true, extract, compile = false } = options;
38
87
  let resolvedExtractModules = [];
39
88
  let resolvedMode = "runtime";
40
89
  const moduleNamespaces = new Map();
@@ -44,7 +93,19 @@ function typestylesPlugin(options = {}) {
44
93
  const recipeModules = new Map();
45
94
  let devExtractCss = null;
46
95
  let devExtractInFlight = null;
47
- return {
96
+ let extraction = null;
97
+ let planIndex = null;
98
+ function extractOnce(root) {
99
+ extraction ??= runTypestylesExtract({
100
+ root,
101
+ modules: resolvedExtractModules,
102
+ sourceComments: extract?.sourceComments
103
+ });
104
+ return extraction;
105
+ }
106
+ const compileEnabled = () => compile && isBuildCommand && resolvedMode === "build" && !resolvedConfig?.build?.ssr && resolvedExtractModules.length > 0;
107
+ let builtCssFileName = null;
108
+ const main = {
48
109
  name: "typestyles",
49
110
  enforce: "pre",
50
111
  config(config, env) {
@@ -57,6 +118,25 @@ function typestylesPlugin(options = {}) {
57
118
  };
58
119
  return config;
59
120
  },
121
+ async resolveId(source, importer, resolveOptions) {
122
+ if (!isBuildCommand || resolvedMode !== "build" || !isSheetRequest(source)) return null;
123
+ if (resolveOptions?.ssr) return null;
124
+ const resolved = await this.resolve(source, importer, {
125
+ ...resolveOptions,
126
+ skipSelf: true
127
+ });
128
+ if (!resolved) return null;
129
+ const noop = toZeroRuntimeSheetId(resolved.id);
130
+ return noop ? {
131
+ ...resolved,
132
+ id: noop
133
+ } : null;
134
+ },
135
+ async buildStart() {
136
+ extraction = null;
137
+ planIndex = null;
138
+ if (compileEnabled()) await extractOnce(resolvedConfig?.root ?? process.cwd());
139
+ },
60
140
  configResolved(config) {
61
141
  resolvedConfig = config;
62
142
  isServe = config.command === "serve";
@@ -64,7 +144,7 @@ function typestylesPlugin(options = {}) {
64
144
  configureServer(server) {
65
145
  if (resolvedExtractModules.length === 0) return;
66
146
  if (resolvedMode === "runtime") return;
67
- const fileName = extract?.fileName ?? "typestyles.css";
147
+ const fileName = stableDevCssFileName(extract?.fileName);
68
148
  const invalidateDevExtract = () => {
69
149
  devExtractCss = null;
70
150
  devExtractInFlight = null;
@@ -99,7 +179,8 @@ function typestylesPlugin(options = {}) {
99
179
  }
100
180
  if (!devExtractInFlight) devExtractInFlight = runTypestylesBuild({
101
181
  root,
102
- modules: resolvedExtractModules
182
+ modules: resolvedExtractModules,
183
+ sourceComments: extract?.sourceComments
103
184
  }).then((css) => {
104
185
  devExtractCss = css;
105
186
  return css;
@@ -117,6 +198,13 @@ function typestylesPlugin(options = {}) {
117
198
  });
118
199
  },
119
200
  transform(code, id) {
201
+ if (isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && id.split("?")[0]?.endsWith(".html")) {
202
+ const parked = retargetTypestylesStylesheet(code, stableDevCssFileName(extract?.fileName), PARKED_CSS_HREF);
203
+ if (parked !== code) return {
204
+ code: parked,
205
+ map: null
206
+ };
207
+ }
120
208
  if (!/\.[jt]sx?$/.test(id)) return null;
121
209
  if (id.includes("node_modules")) return null;
122
210
  const { keys, prefixes, recipeNames } = extractNamespaces(code);
@@ -146,14 +234,30 @@ if (import.meta.hot) {
146
234
  };
147
235
  },
148
236
  transformIndexHtml: {
149
- order: "pre",
150
- handler(html) {
237
+ order: "post",
238
+ handler(html, ctx) {
151
239
  if (resolvedExtractModules.length === 0) return;
152
240
  if (resolvedMode === "runtime") return;
153
241
  if (!resolvedConfig) return;
154
- const fileName = extract?.fileName ?? "typestyles.css";
155
- const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
156
- if (htmlLinksTypestylesCss(html, href, fileName)) return;
242
+ const stableFileName = stableDevCssFileName(extract?.fileName);
243
+ if (!isBuildCommand) {
244
+ const href = resolveTypestylesCssHref(resolvedConfig.base, stableFileName);
245
+ if (htmlLinksTypestylesCss(html, href, stableFileName)) return;
246
+ return [{
247
+ tag: "link",
248
+ attrs: {
249
+ rel: "stylesheet",
250
+ href
251
+ },
252
+ injectTo: "head"
253
+ }];
254
+ }
255
+ if (!builtCssFileName) return;
256
+ const href = resolveTypestylesCssHref(resolvedConfig.base, builtCssFileName, ctx?.path);
257
+ if (html.includes(PARKED_CSS_HREF)) return html.split(PARKED_CSS_HREF).join(href);
258
+ if (htmlLinksTypestylesCss(html, href, builtCssFileName)) return;
259
+ const retargeted = retargetTypestylesStylesheet(html, stableFileName, href);
260
+ if (retargeted !== html) return retargeted;
157
261
  return [{
158
262
  tag: "link",
159
263
  attrs: {
@@ -164,13 +268,21 @@ if (import.meta.hot) {
164
268
  }];
165
269
  }
166
270
  },
167
- async generateBundle() {
271
+ async generateBundle(_options, bundle) {
168
272
  if (!isBuildCommand) return;
273
+ if (resolvedMode === "build" && !resolvedConfig?.build?.ssr) {
274
+ const leaked = findRealSheetModules(Object.values(bundle ?? {}).flatMap((chunk) => chunk.type === "chunk" ? Object.keys(chunk.modules) : []));
275
+ if (leaked.length > 0) this.warn(zeroRuntimeLeakMessage(leaked));
276
+ if (compileEnabled()) {
277
+ const warning = lingeringRuntimeWarning(bundle ?? {}, (id) => this.getModuleInfo(id)?.importers, resolvedConfig?.root ?? process.cwd());
278
+ if (warning) this.warn(warning);
279
+ }
280
+ }
169
281
  if (resolvedMode === "runtime") return;
170
282
  if (!resolvedExtractModules.length) return;
171
283
  if (!resolvedConfig) return;
172
284
  const root = resolvedConfig.root ?? process.cwd();
173
- const fileName = extract?.fileName ?? "typestyles.css";
285
+ const requestedFileName = extract?.fileName?.replace(/^\//, "");
174
286
  if (coverage && recipeModules.size > 0) {
175
287
  let missing = [];
176
288
  try {
@@ -192,20 +304,50 @@ if (import.meta.hot) {
192
304
  }
193
305
  }
194
306
  try {
195
- const css = await runTypestylesBuild({
196
- root,
197
- modules: resolvedExtractModules
198
- });
199
- this.emitFile({
200
- type: "asset",
201
- fileName,
202
- source: css
203
- });
307
+ const { css } = await extractOnce(root);
308
+ if (requestedFileName && cssFileNameHasPlaceholder(requestedFileName)) {
309
+ builtCssFileName = renderCssFileName(requestedFileName, css);
310
+ this.emitFile({
311
+ type: "asset",
312
+ fileName: builtCssFileName,
313
+ source: css
314
+ });
315
+ } else if (requestedFileName) {
316
+ builtCssFileName = requestedFileName;
317
+ this.emitFile({
318
+ type: "asset",
319
+ fileName: requestedFileName,
320
+ source: css
321
+ });
322
+ } else {
323
+ const referenceId = this.emitFile({
324
+ type: "asset",
325
+ name: DEFAULT_CSS_FILE_NAME,
326
+ source: css
327
+ });
328
+ builtCssFileName = this.getFileName(referenceId);
329
+ const asset = bundle?.[builtCssFileName];
330
+ if (asset?.type === "asset" && typeof asset.source === "string") asset.source = rebaseRelativeCssUrls(asset.source, builtCssFileName.split("/").length - 1);
331
+ }
204
332
  } catch (err) {
205
333
  this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
206
334
  }
207
335
  }
208
336
  };
337
+ if (!compile) return main;
338
+ return [main, {
339
+ name: "typestyles:compile",
340
+ apply: "build",
341
+ enforce: "post",
342
+ async transform(code, id) {
343
+ if (!compileEnabled() || !isTransformableId(id)) return null;
344
+ planIndex ??= indexPlans((await extractOnce(resolvedConfig?.root ?? process.cwd())).plans);
345
+ return transformRecipeCalls(code, planIndex, (source) => this.parse(source), id);
346
+ },
347
+ shouldTransformCachedModule({ code }) {
348
+ return compileEnabled() && mayNeedRecompile(code);
349
+ }
350
+ }];
209
351
  }
210
352
  //#endregion
211
353
  export { DEFAULT_EXTRACT_MODULE_CANDIDATES, typestylesPlugin as default, discoverDefaultExtractModules, extractNamespaces, htmlLinksTypestylesCss, moduleNeedsOverrideHmr, resolveTypestylesCssHref };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typestyles/vite",
3
- "version": "0.5.4",
3
+ "version": "0.7.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.33.0"
44
+ "typestyles": "0.35.0"
45
45
  },
46
46
  "dependencies": {
47
- "@typestyles/build-runner": "0.6.4"
47
+ "@typestyles/build-runner": "0.8.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "vp pack",