@typestyles/vite 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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)
@@ -146,7 +153,9 @@ Even with a convention entry present, this keeps `<style>` injection in producti
146
153
 
147
154
  ## Verify production output
148
155
 
149
- Extraction is execute-and-collect: styles unreachable from your entry file are silently dropped. After `vite build`, run:
156
+ 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
+
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:
150
159
 
151
160
  ```ts
152
161
  import { verifyTypestylesBuild } from '@typestyles/build-runner';
package/dist/index.cjs CHANGED
@@ -1,248 +1,241 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- DEFAULT_EXTRACT_MODULE_CANDIDATES: () => import_build_runner2.DEFAULT_EXTRACT_MODULE_CANDIDATES,
24
- default: () => typestylesPlugin,
25
- discoverDefaultExtractModules: () => import_build_runner2.discoverDefaultExtractModules,
26
- extractNamespaces: () => import_build_runner.extractNamespaces,
27
- htmlLinksTypestylesCss: () => htmlLinksTypestylesCss,
28
- moduleNeedsOverrideHmr: () => import_build_runner3.moduleNeedsOverrideHmr,
29
- resolveTypestylesCssHref: () => resolveTypestylesCssHref
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
30
4
  });
31
- module.exports = __toCommonJS(index_exports);
32
- var import_node_path = require("path");
33
- var import_build_runner = require("@typestyles/build-runner");
34
- var import_build_runner2 = require("@typestyles/build-runner");
35
- var import_build_runner3 = require("@typestyles/build-runner");
5
+ let node_path = require("node:path");
6
+ let _typestyles_build_runner = require("@typestyles/build-runner");
7
+ //#region src/index.ts
36
8
  function resolveExtractModulesForVite(root, extract) {
37
- return (0, import_build_runner.resolveExtractModules)(root, extract);
9
+ return (0, _typestyles_build_runner.resolveExtractModules)(root, extract);
38
10
  }
39
11
  function resolveTypestylesCssHref(base, fileName) {
40
- const normalizedFileName = fileName.replace(/^\//, "");
41
- const normalizedBase = base.replace(/\/$/, "") || "";
42
- if (normalizedBase === "" || normalizedBase === "/") {
43
- return `/${normalizedFileName}`;
44
- }
45
- return `${normalizedBase}/${normalizedFileName}`;
12
+ const normalizedFileName = fileName.replace(/^\//, "");
13
+ const normalizedBase = base.replace(/\/$/, "") || "";
14
+ if (normalizedBase === "" || normalizedBase === "/") return `/${normalizedFileName}`;
15
+ return `${normalizedBase}/${normalizedFileName}`;
46
16
  }
47
17
  function htmlLinksTypestylesCss(html, cssHref, fileName) {
48
- const bareName = fileName.replace(/^\//, "");
49
- const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
50
- const hrefPattern = /\bhref=["']([^"']+)["']/i;
51
- for (const match of html.matchAll(linkPattern)) {
52
- const hrefMatch = match[0].match(hrefPattern);
53
- const href = hrefMatch?.[1];
54
- if (!href) continue;
55
- if (href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) {
56
- return true;
57
- }
58
- }
59
- return false;
18
+ const bareName = fileName.replace(/^\//, "");
19
+ const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
20
+ const hrefPattern = /\bhref=["']([^"']+)["']/i;
21
+ for (const match of html.matchAll(linkPattern)) {
22
+ const href = match[0].match(hrefPattern)?.[1];
23
+ if (!href) continue;
24
+ if (href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) return true;
25
+ }
26
+ return false;
27
+ }
28
+ function formatUnextractedRecipeError(missing, extractEntries) {
29
+ const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
30
+ return [
31
+ "[typestyles] Production extract is missing app recipes:",
32
+ ...missing.map((item) => {
33
+ const quoted = item.names.map((name) => `"${name}"`).join(", ");
34
+ return ` ${item.names.length === 1 ? "recipe" : "recipes"} ${quoted} in ${item.modulePath}`;
35
+ }),
36
+ `These modules are reachable from the app and missing from the extract entry (${entries}).`,
37
+ "Import them from the extract entry, or set coverage: false to extract a subset."
38
+ ].join("\n");
60
39
  }
61
40
  function typestylesPlugin(options = {}) {
62
- const { warnDuplicates = true, extract } = options;
63
- let resolvedExtractModules = [];
64
- let resolvedMode = "runtime";
65
- const moduleNamespaces = /* @__PURE__ */ new Map();
66
- let resolvedConfig = null;
67
- let isBuildCommand = false;
68
- let isServe = false;
69
- let devExtractCss = null;
70
- let devExtractInFlight = null;
71
- return {
72
- name: "typestyles",
73
- enforce: "pre",
74
- config(config, env) {
75
- isBuildCommand = env.command === "build";
76
- const root = (0, import_node_path.resolve)(config.root ?? process.cwd());
77
- resolvedExtractModules = resolveExtractModulesForVite(root, extract);
78
- resolvedMode = (0, import_build_runner.resolveExtractMode)(options.mode, resolvedExtractModules);
79
- if (env.command === "build" && (resolvedMode === "build" || resolvedMode === "hybrid")) {
80
- config.define = {
81
- ...config.define ?? {},
82
- // Inlined by the bundler so typestyles sheet skips creating <style> in production
83
- __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
84
- };
85
- }
86
- return config;
87
- },
88
- configResolved(config) {
89
- resolvedConfig = config;
90
- isServe = config.command === "serve";
91
- },
92
- configureServer(server) {
93
- if (resolvedExtractModules.length === 0) return;
94
- if (resolvedMode === "runtime") return;
95
- const fileName = extract?.fileName ?? "typestyles.css";
96
- const invalidateDevExtract = () => {
97
- devExtractCss = null;
98
- devExtractInFlight = null;
99
- };
100
- server.watcher.on("change", invalidateDevExtract);
101
- server.watcher.on("add", invalidateDevExtract);
102
- server.watcher.on("unlink", invalidateDevExtract);
103
- server.middlewares.use(async (req, res, next) => {
104
- if (req.method !== "GET" && req.method !== "HEAD") {
105
- next();
106
- return;
107
- }
108
- const config = resolvedConfig;
109
- if (!config) {
110
- next();
111
- return;
112
- }
113
- const url = req.url?.split("?")[0] ?? "";
114
- const base = config.base.replace(/\/$/, "") || "";
115
- const expectedPath = base === "" || base === "/" ? `/${fileName.replace(/^\//, "")}` : `${base}/${fileName.replace(/^\//, "")}`;
116
- if (url !== expectedPath) {
117
- next();
118
- return;
119
- }
120
- const root = config.root ?? process.cwd();
121
- try {
122
- if (devExtractCss !== null) {
123
- res.statusCode = 200;
124
- res.setHeader("Content-Type", "text/css; charset=utf-8");
125
- res.setHeader("Cache-Control", "no-cache");
126
- res.end(devExtractCss);
127
- return;
128
- }
129
- if (!devExtractInFlight) {
130
- devExtractInFlight = (0, import_build_runner.runTypestylesBuild)({
131
- root,
132
- modules: resolvedExtractModules
133
- }).then((css2) => {
134
- devExtractCss = css2;
135
- return css2;
136
- }).finally(() => {
137
- devExtractInFlight = null;
138
- });
139
- }
140
- const css = await devExtractInFlight;
141
- res.statusCode = 200;
142
- res.setHeader("Content-Type", "text/css; charset=utf-8");
143
- res.setHeader("Cache-Control", "no-cache");
144
- res.end(css);
145
- } catch (err) {
146
- next(err);
147
- }
148
- });
149
- },
150
- transform(code, id) {
151
- if (!/\.[jt]sx?$/.test(id)) return null;
152
- if (id.includes("node_modules")) return null;
153
- const { keys, prefixes } = (0, import_build_runner.extractNamespaces)(code);
154
- const overrideHmr = (0, import_build_runner.moduleNeedsOverrideHmr)(code);
155
- if (keys.length === 0 && prefixes.length === 0 && !overrideHmr) return null;
156
- if (warnDuplicates && prefixes.length > 0) {
157
- (0, import_build_runner.reportDuplicateNamespaces)(moduleNamespaces, id, prefixes, this);
158
- }
159
- if (keys.length > 0 || prefixes.length > 0) {
160
- moduleNamespaces.set(id, { keys, prefixes });
161
- }
162
- if (!isServe) {
163
- return null;
164
- }
165
- const keysJSON = JSON.stringify(keys);
166
- const prefixesJSON = JSON.stringify(prefixes);
167
- const hmrImports = overrideHmr ? `import { invalidateKeys as __typestylesInvalidateKeys, createOverrideHmrSlot as __tsCreateOvHmr } from 'typestyles/hmr';
168
- ` : `import { invalidateKeys as __typestylesInvalidateKeys } from 'typestyles/hmr';
169
- `;
170
- const overrideBootstrap = overrideHmr ? `const __tsOvHmr = __tsCreateOvHmr();
171
- __tsOvHmr.activate();
172
- ` : "";
173
- const overrideTeardown = overrideHmr ? `
174
- __tsOvHmr.deactivate();
175
- ` : "";
176
- const disposeBody = [
177
- keys.length > 0 || prefixes.length > 0 ? `__typestylesInvalidateKeys(${keysJSON}, ${prefixesJSON});` : null,
178
- overrideHmr ? `__tsOvHmr.dispose();` : null
179
- ].filter(Boolean).join("\n ");
180
- const hmrCode = `${overrideTeardown}
41
+ const { warnDuplicates = true, coverage = true, extract } = options;
42
+ let resolvedExtractModules = [];
43
+ let resolvedMode = "runtime";
44
+ const moduleNamespaces = new Map();
45
+ let resolvedConfig = null;
46
+ let isBuildCommand = false;
47
+ let isServe = false;
48
+ const recipeModules = new Map();
49
+ let devExtractCss = null;
50
+ let devExtractInFlight = null;
51
+ return {
52
+ name: "typestyles",
53
+ enforce: "pre",
54
+ config(config, env) {
55
+ isBuildCommand = env.command === "build";
56
+ resolvedExtractModules = resolveExtractModulesForVite((0, node_path.resolve)(config.root ?? process.cwd()), extract);
57
+ resolvedMode = (0, _typestyles_build_runner.resolveExtractMode)(options.mode, resolvedExtractModules);
58
+ if (env.command === "build" && (resolvedMode === "build" || resolvedMode === "hybrid")) config.define = {
59
+ ...config.define ?? {},
60
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
61
+ };
62
+ return config;
63
+ },
64
+ configResolved(config) {
65
+ resolvedConfig = config;
66
+ isServe = config.command === "serve";
67
+ },
68
+ configureServer(server) {
69
+ if (resolvedExtractModules.length === 0) return;
70
+ if (resolvedMode === "runtime") return;
71
+ const fileName = extract?.fileName ?? "typestyles.css";
72
+ const invalidateDevExtract = () => {
73
+ devExtractCss = null;
74
+ devExtractInFlight = null;
75
+ };
76
+ server.watcher.on("change", invalidateDevExtract);
77
+ server.watcher.on("add", invalidateDevExtract);
78
+ server.watcher.on("unlink", invalidateDevExtract);
79
+ server.middlewares.use(async (req, res, next) => {
80
+ if (req.method !== "GET" && req.method !== "HEAD") {
81
+ next();
82
+ return;
83
+ }
84
+ const config = resolvedConfig;
85
+ if (!config) {
86
+ next();
87
+ return;
88
+ }
89
+ const url = req.url?.split("?")[0] ?? "";
90
+ const base = config.base.replace(/\/$/, "") || "";
91
+ if (url !== (base === "" || base === "/" ? `/${fileName.replace(/^\//, "")}` : `${base}/${fileName.replace(/^\//, "")}`)) {
92
+ next();
93
+ return;
94
+ }
95
+ const root = config.root ?? process.cwd();
96
+ try {
97
+ if (devExtractCss !== null) {
98
+ res.statusCode = 200;
99
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
100
+ res.setHeader("Cache-Control", "no-cache");
101
+ res.end(devExtractCss);
102
+ return;
103
+ }
104
+ if (!devExtractInFlight) devExtractInFlight = (0, _typestyles_build_runner.runTypestylesBuild)({
105
+ root,
106
+ modules: resolvedExtractModules
107
+ }).then((css) => {
108
+ devExtractCss = css;
109
+ return css;
110
+ }).finally(() => {
111
+ devExtractInFlight = null;
112
+ });
113
+ const css = await devExtractInFlight;
114
+ res.statusCode = 200;
115
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
116
+ res.setHeader("Cache-Control", "no-cache");
117
+ res.end(css);
118
+ } catch (err) {
119
+ next(err);
120
+ }
121
+ });
122
+ },
123
+ transform(code, id) {
124
+ if (!/\.[jt]sx?$/.test(id)) return null;
125
+ if (id.includes("node_modules")) return null;
126
+ const { keys, prefixes, recipeNames } = (0, _typestyles_build_runner.extractNamespaces)(code);
127
+ const overrideHmr = (0, _typestyles_build_runner.moduleNeedsOverrideHmr)(code);
128
+ if (coverage && isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && recipeNames.length > 0) recipeModules.set(id, recipeNames);
129
+ if (keys.length === 0 && prefixes.length === 0 && !overrideHmr) return null;
130
+ if (warnDuplicates && prefixes.length > 0) (0, _typestyles_build_runner.reportDuplicateNamespaces)(moduleNamespaces, id, prefixes, this);
131
+ if (keys.length > 0 || prefixes.length > 0) moduleNamespaces.set(id, {
132
+ keys,
133
+ prefixes
134
+ });
135
+ if (!isServe) return null;
136
+ const keysJSON = JSON.stringify(keys);
137
+ const prefixesJSON = JSON.stringify(prefixes);
138
+ const hmrImports = overrideHmr ? `import { invalidateKeys as __typestylesInvalidateKeys, createOverrideHmrSlot as __tsCreateOvHmr } from 'typestyles/hmr';\n` : `import { invalidateKeys as __typestylesInvalidateKeys } from 'typestyles/hmr';\n`;
139
+ const overrideBootstrap = overrideHmr ? `const __tsOvHmr = __tsCreateOvHmr();\n__tsOvHmr.activate();\n` : "";
140
+ const hmrCode = `${overrideHmr ? `\n__tsOvHmr.deactivate();\n` : ""}
181
141
  if (import.meta.hot) {
182
142
  import.meta.hot.accept();
183
143
  import.meta.hot.dispose(() => {
184
- ${disposeBody}
144
+ ${[keys.length > 0 || prefixes.length > 0 ? `__typestylesInvalidateKeys(${keysJSON}, ${prefixesJSON});` : null, overrideHmr ? `__tsOvHmr.dispose();` : null].filter(Boolean).join("\n ")}
185
145
  });
186
146
  }`;
187
- return {
188
- code: hmrImports + overrideBootstrap + code + hmrCode,
189
- map: null
190
- };
191
- },
192
- transformIndexHtml: {
193
- order: "pre",
194
- handler(html) {
195
- if (resolvedExtractModules.length === 0) return;
196
- if (resolvedMode === "runtime") return;
197
- if (!resolvedConfig) return;
198
- const fileName = extract?.fileName ?? "typestyles.css";
199
- const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
200
- if (htmlLinksTypestylesCss(html, href, fileName)) {
201
- return;
202
- }
203
- return [
204
- {
205
- tag: "link",
206
- attrs: {
207
- rel: "stylesheet",
208
- href
209
- },
210
- injectTo: "head"
211
- }
212
- ];
213
- }
214
- },
215
- async generateBundle() {
216
- if (!isBuildCommand) return;
217
- if (resolvedMode === "runtime") return;
218
- if (!resolvedExtractModules.length) return;
219
- if (!resolvedConfig) return;
220
- const root = resolvedConfig.root ?? process.cwd();
221
- const fileName = extract?.fileName ?? "typestyles.css";
222
- try {
223
- const css = await (0, import_build_runner.runTypestylesBuild)({
224
- root,
225
- modules: resolvedExtractModules
226
- });
227
- this.emitFile({
228
- type: "asset",
229
- fileName,
230
- source: css
231
- });
232
- } catch (err) {
233
- this.error(
234
- `[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`
235
- );
236
- }
237
- }
238
- };
147
+ return {
148
+ code: hmrImports + overrideBootstrap + code + hmrCode,
149
+ map: null
150
+ };
151
+ },
152
+ transformIndexHtml: {
153
+ order: "pre",
154
+ handler(html) {
155
+ if (resolvedExtractModules.length === 0) return;
156
+ if (resolvedMode === "runtime") return;
157
+ if (!resolvedConfig) return;
158
+ const fileName = extract?.fileName ?? "typestyles.css";
159
+ const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
160
+ if (htmlLinksTypestylesCss(html, href, fileName)) return;
161
+ return [{
162
+ tag: "link",
163
+ attrs: {
164
+ rel: "stylesheet",
165
+ href
166
+ },
167
+ injectTo: "head"
168
+ }];
169
+ }
170
+ },
171
+ async generateBundle() {
172
+ if (!isBuildCommand) return;
173
+ if (resolvedMode === "runtime") return;
174
+ if (!resolvedExtractModules.length) return;
175
+ if (!resolvedConfig) return;
176
+ const root = resolvedConfig.root ?? process.cwd();
177
+ const fileName = extract?.fileName ?? "typestyles.css";
178
+ if (coverage && recipeModules.size > 0) {
179
+ let missing = [];
180
+ try {
181
+ missing = await (0, _typestyles_build_runner.findUnextractedRecipes)({
182
+ root,
183
+ extractEntries: resolvedExtractModules,
184
+ recipeModules: [...recipeModules.entries()].map(([id, names]) => ({
185
+ id,
186
+ names
187
+ }))
188
+ });
189
+ } catch (err) {
190
+ this.error(`[typestyles] Failed to check extract coverage: ${err instanceof Error ? err.message : String(err)}`);
191
+ return;
192
+ }
193
+ if (missing.length > 0) {
194
+ this.error(formatUnextractedRecipeError(missing, resolvedExtractModules));
195
+ return;
196
+ }
197
+ }
198
+ 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
+ });
208
+ } catch (err) {
209
+ this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
210
+ }
211
+ }
212
+ };
239
213
  }
240
- // Annotate the CommonJS export names for ESM import in node:
241
- 0 && (module.exports = {
242
- DEFAULT_EXTRACT_MODULE_CANDIDATES,
243
- discoverDefaultExtractModules,
244
- extractNamespaces,
245
- htmlLinksTypestylesCss,
246
- moduleNeedsOverrideHmr,
247
- resolveTypestylesCssHref
214
+ //#endregion
215
+ Object.defineProperty(exports, "DEFAULT_EXTRACT_MODULE_CANDIDATES", {
216
+ enumerable: true,
217
+ get: function() {
218
+ return _typestyles_build_runner.DEFAULT_EXTRACT_MODULE_CANDIDATES;
219
+ }
220
+ });
221
+ exports.default = typestylesPlugin;
222
+ Object.defineProperty(exports, "discoverDefaultExtractModules", {
223
+ enumerable: true,
224
+ get: function() {
225
+ return _typestyles_build_runner.discoverDefaultExtractModules;
226
+ }
227
+ });
228
+ Object.defineProperty(exports, "extractNamespaces", {
229
+ enumerable: true,
230
+ get: function() {
231
+ return _typestyles_build_runner.extractNamespaces;
232
+ }
233
+ });
234
+ exports.htmlLinksTypestylesCss = htmlLinksTypestylesCss;
235
+ Object.defineProperty(exports, "moduleNeedsOverrideHmr", {
236
+ enumerable: true,
237
+ get: function() {
238
+ return _typestyles_build_runner.moduleNeedsOverrideHmr;
239
+ }
248
240
  });
241
+ exports.resolveTypestylesCssHref = resolveTypestylesCssHref;
package/dist/index.d.cts CHANGED
@@ -1,7 +1,6 @@
1
- import { Plugin } from 'vite';
2
- import { TypestylesIntegrationMode, TypestylesExtractOptions } from '@typestyles/build-runner';
3
- export { DEFAULT_EXTRACT_MODULE_CANDIDATES, TypestylesExtractOptions, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr } from '@typestyles/build-runner';
4
-
1
+ import { Plugin } from "vite";
2
+ import { DEFAULT_EXTRACT_MODULE_CANDIDATES, TypestylesExtractOptions, TypestylesIntegrationMode, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr } from "@typestyles/build-runner";
3
+ //#region src/index.d.ts
5
4
  /**
6
5
  * Regex patterns to extract namespace strings from typestyles API calls.
7
6
  *
@@ -15,39 +14,46 @@ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, TypestylesExtractOptions, discoverDe
15
14
  * global.rule('body', ...) → prefix "body"
16
15
  * global.fontFace('Inter', ...) → prefix "font-face:Inter"
17
16
  */
18
- interface TypestylesPluginOptions {
19
- /**
20
- * When true (default), fail the build if the same logical `styles.component` / `styles.class`
21
- * namespace appears in more than one module. Set to `false` to skip this check.
22
- */
23
- warnDuplicates?: boolean;
24
- /**
25
- * Mode for typestyles integration:
26
- * - `"runtime"`: HMR only, no build-time extraction.
27
- * - `"build"`: emit a static CSS asset on `vite build` and disable client injection there.
28
- * - `"hybrid"`: extract on build and keep runtime-compatible behavior.
29
- *
30
- * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
31
- * discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
32
- * injection + HMR (runtime is only disabled during `vite build`), serves the same extracted CSS
33
- * at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA fallback
34
- * returning HTML for that URL), and production emits the CSS file. If no modules are resolved,
35
- * defaults to `"runtime"`.
36
- */
37
- mode?: TypestylesIntegrationMode;
38
- /**
39
- * Options for build-time CSS extraction when mode is "build" or "hybrid".
40
- *
41
- * Omitted entirely: discover a convention entry under the project root (see
42
- * {@link discoverDefaultExtractModules}); if none exist, stays in runtime-only mode.
43
- */
44
- extract?: TypestylesExtractOptions;
17
+ export interface TypestylesPluginOptions {
18
+ /**
19
+ * When true (default), fail the build if the same logical `styles.component` / `styles.class`
20
+ * namespace appears in more than one module. Set to `false` to skip this check.
21
+ */
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;
31
+ /**
32
+ * Mode for typestyles integration:
33
+ * - `"runtime"`: HMR only, no build-time extraction.
34
+ * - `"build"`: emit a static CSS asset on `vite build` and disable client injection there.
35
+ * - `"hybrid"`: extract on build and keep runtime-compatible behavior.
36
+ *
37
+ * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
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"`.
43
+ */
44
+ mode?: TypestylesIntegrationMode;
45
+ /**
46
+ * Options for build-time CSS extraction when mode is "build" or "hybrid".
47
+ *
48
+ * Omitted entirely: discover a convention entry under the project root (see
49
+ * {@link discoverDefaultExtractModules}); if none exist, stays in runtime-only mode.
50
+ */
51
+ extract?: TypestylesExtractOptions;
45
52
  }
46
53
  /** Public URL path for the extracted CSS asset (respects Vite `base`). */
47
- declare function resolveTypestylesCssHref(base: string, fileName: string): string;
54
+ export declare function resolveTypestylesCssHref(base: string, fileName: string): string;
48
55
  /** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
49
- declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
50
-
56
+ export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
51
57
  /**
52
58
  * Vite plugin for typestyles HMR support.
53
59
  *
@@ -56,6 +62,6 @@ declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName:
56
62
  * before re-execution. Files may import from a local re-export such as `./typestyles` rather
57
63
  * than `from 'typestyles'` directly — we key off API call patterns in the source, not the import path.
58
64
  */
59
- declare function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
60
-
61
- export { type TypestylesPluginOptions, typestylesPlugin as default, htmlLinksTypestylesCss, resolveTypestylesCssHref };
65
+ export default function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
66
+ //#endregion
67
+ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, type TypestylesExtractOptions, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { Plugin } from 'vite';
2
- import { TypestylesIntegrationMode, TypestylesExtractOptions } from '@typestyles/build-runner';
3
- export { DEFAULT_EXTRACT_MODULE_CANDIDATES, TypestylesExtractOptions, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr } from '@typestyles/build-runner';
4
-
1
+ import { DEFAULT_EXTRACT_MODULE_CANDIDATES, TypestylesExtractOptions, TypestylesIntegrationMode, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr } from "@typestyles/build-runner";
2
+ import { Plugin } from "vite";
3
+ //#region src/index.d.ts
5
4
  /**
6
5
  * Regex patterns to extract namespace strings from typestyles API calls.
7
6
  *
@@ -15,39 +14,46 @@ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, TypestylesExtractOptions, discoverDe
15
14
  * global.rule('body', ...) → prefix "body"
16
15
  * global.fontFace('Inter', ...) → prefix "font-face:Inter"
17
16
  */
18
- interface TypestylesPluginOptions {
19
- /**
20
- * When true (default), fail the build if the same logical `styles.component` / `styles.class`
21
- * namespace appears in more than one module. Set to `false` to skip this check.
22
- */
23
- warnDuplicates?: boolean;
24
- /**
25
- * Mode for typestyles integration:
26
- * - `"runtime"`: HMR only, no build-time extraction.
27
- * - `"build"`: emit a static CSS asset on `vite build` and disable client injection there.
28
- * - `"hybrid"`: extract on build and keep runtime-compatible behavior.
29
- *
30
- * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
31
- * discovered convention entry file), defaults to `"build"`: `vite dev` keeps runtime
32
- * injection + HMR (runtime is only disabled during `vite build`), serves the same extracted CSS
33
- * at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA fallback
34
- * returning HTML for that URL), and production emits the CSS file. If no modules are resolved,
35
- * defaults to `"runtime"`.
36
- */
37
- mode?: TypestylesIntegrationMode;
38
- /**
39
- * Options for build-time CSS extraction when mode is "build" or "hybrid".
40
- *
41
- * Omitted entirely: discover a convention entry under the project root (see
42
- * {@link discoverDefaultExtractModules}); if none exist, stays in runtime-only mode.
43
- */
44
- extract?: TypestylesExtractOptions;
17
+ export interface TypestylesPluginOptions {
18
+ /**
19
+ * When true (default), fail the build if the same logical `styles.component` / `styles.class`
20
+ * namespace appears in more than one module. Set to `false` to skip this check.
21
+ */
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;
31
+ /**
32
+ * Mode for typestyles integration:
33
+ * - `"runtime"`: HMR only, no build-time extraction.
34
+ * - `"build"`: emit a static CSS asset on `vite build` and disable client injection there.
35
+ * - `"hybrid"`: extract on build and keep runtime-compatible behavior.
36
+ *
37
+ * When omitted and at least one extraction module is resolved (explicit `extract.modules`, or a
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"`.
43
+ */
44
+ mode?: TypestylesIntegrationMode;
45
+ /**
46
+ * Options for build-time CSS extraction when mode is "build" or "hybrid".
47
+ *
48
+ * Omitted entirely: discover a convention entry under the project root (see
49
+ * {@link discoverDefaultExtractModules}); if none exist, stays in runtime-only mode.
50
+ */
51
+ extract?: TypestylesExtractOptions;
45
52
  }
46
53
  /** Public URL path for the extracted CSS asset (respects Vite `base`). */
47
- declare function resolveTypestylesCssHref(base: string, fileName: string): string;
54
+ export declare function resolveTypestylesCssHref(base: string, fileName: string): string;
48
55
  /** True when `html` already links the extracted stylesheet (avoids duplicate injection). */
49
- declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
50
-
56
+ export declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName: string): boolean;
51
57
  /**
52
58
  * Vite plugin for typestyles HMR support.
53
59
  *
@@ -56,6 +62,6 @@ declare function htmlLinksTypestylesCss(html: string, cssHref: string, fileName:
56
62
  * before re-execution. Files may import from a local re-export such as `./typestyles` rather
57
63
  * than `from 'typestyles'` directly — we key off API call patterns in the source, not the import path.
58
64
  */
59
- declare function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
60
-
61
- export { type TypestylesPluginOptions, typestylesPlugin as default, htmlLinksTypestylesCss, resolveTypestylesCssHref };
65
+ export default function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
66
+ //#endregion
67
+ export { DEFAULT_EXTRACT_MODULE_CANDIDATES, type TypestylesExtractOptions, discoverDefaultExtractModules, extractNamespaces, moduleNeedsOverrideHmr };
package/dist/index.js CHANGED
@@ -1,228 +1,211 @@
1
- // src/index.ts
2
- import { resolve as resolvePath } from "path";
3
- import {
4
- extractNamespaces,
5
- moduleNeedsOverrideHmr,
6
- reportDuplicateNamespaces,
7
- resolveExtractMode,
8
- resolveExtractModules,
9
- runTypestylesBuild
10
- } from "@typestyles/build-runner";
11
- import {
12
- DEFAULT_EXTRACT_MODULE_CANDIDATES,
13
- discoverDefaultExtractModules
14
- } from "@typestyles/build-runner";
15
- import { moduleNeedsOverrideHmr as moduleNeedsOverrideHmr2 } from "@typestyles/build-runner";
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";
3
+ //#region src/index.ts
16
4
  function resolveExtractModulesForVite(root, extract) {
17
- return resolveExtractModules(root, extract);
5
+ return resolveExtractModules(root, extract);
18
6
  }
19
7
  function resolveTypestylesCssHref(base, fileName) {
20
- const normalizedFileName = fileName.replace(/^\//, "");
21
- const normalizedBase = base.replace(/\/$/, "") || "";
22
- if (normalizedBase === "" || normalizedBase === "/") {
23
- return `/${normalizedFileName}`;
24
- }
25
- return `${normalizedBase}/${normalizedFileName}`;
8
+ const normalizedFileName = fileName.replace(/^\//, "");
9
+ const normalizedBase = base.replace(/\/$/, "") || "";
10
+ if (normalizedBase === "" || normalizedBase === "/") return `/${normalizedFileName}`;
11
+ return `${normalizedBase}/${normalizedFileName}`;
26
12
  }
27
13
  function htmlLinksTypestylesCss(html, cssHref, fileName) {
28
- const bareName = fileName.replace(/^\//, "");
29
- const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
30
- const hrefPattern = /\bhref=["']([^"']+)["']/i;
31
- for (const match of html.matchAll(linkPattern)) {
32
- const hrefMatch = match[0].match(hrefPattern);
33
- const href = hrefMatch?.[1];
34
- if (!href) continue;
35
- if (href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) {
36
- return true;
37
- }
38
- }
39
- return false;
14
+ const bareName = fileName.replace(/^\//, "");
15
+ const linkPattern = /<link\b[^>]*\brel=["']stylesheet["'][^>]*>/gi;
16
+ const hrefPattern = /\bhref=["']([^"']+)["']/i;
17
+ for (const match of html.matchAll(linkPattern)) {
18
+ const href = match[0].match(hrefPattern)?.[1];
19
+ if (!href) continue;
20
+ if (href === cssHref || href.endsWith(`/${bareName}`) || href === bareName || href === `./${bareName}`) return true;
21
+ }
22
+ return false;
23
+ }
24
+ function formatUnextractedRecipeError(missing, extractEntries) {
25
+ const entries = extractEntries.map((entry) => entry.replace(/\\/g, "/")).join(", ");
26
+ return [
27
+ "[typestyles] Production extract is missing app recipes:",
28
+ ...missing.map((item) => {
29
+ const quoted = item.names.map((name) => `"${name}"`).join(", ");
30
+ return ` ${item.names.length === 1 ? "recipe" : "recipes"} ${quoted} in ${item.modulePath}`;
31
+ }),
32
+ `These modules are reachable from the app and missing from the extract entry (${entries}).`,
33
+ "Import them from the extract entry, or set coverage: false to extract a subset."
34
+ ].join("\n");
40
35
  }
41
36
  function typestylesPlugin(options = {}) {
42
- const { warnDuplicates = true, extract } = options;
43
- let resolvedExtractModules = [];
44
- let resolvedMode = "runtime";
45
- const moduleNamespaces = /* @__PURE__ */ new Map();
46
- let resolvedConfig = null;
47
- let isBuildCommand = false;
48
- let isServe = false;
49
- let devExtractCss = null;
50
- let devExtractInFlight = null;
51
- return {
52
- name: "typestyles",
53
- enforce: "pre",
54
- config(config, env) {
55
- isBuildCommand = env.command === "build";
56
- const root = resolvePath(config.root ?? process.cwd());
57
- resolvedExtractModules = resolveExtractModulesForVite(root, extract);
58
- resolvedMode = resolveExtractMode(options.mode, resolvedExtractModules);
59
- if (env.command === "build" && (resolvedMode === "build" || resolvedMode === "hybrid")) {
60
- config.define = {
61
- ...config.define ?? {},
62
- // Inlined by the bundler so typestyles sheet skips creating <style> in production
63
- __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
64
- };
65
- }
66
- return config;
67
- },
68
- configResolved(config) {
69
- resolvedConfig = config;
70
- isServe = config.command === "serve";
71
- },
72
- configureServer(server) {
73
- if (resolvedExtractModules.length === 0) return;
74
- if (resolvedMode === "runtime") return;
75
- const fileName = extract?.fileName ?? "typestyles.css";
76
- const invalidateDevExtract = () => {
77
- devExtractCss = null;
78
- devExtractInFlight = null;
79
- };
80
- server.watcher.on("change", invalidateDevExtract);
81
- server.watcher.on("add", invalidateDevExtract);
82
- server.watcher.on("unlink", invalidateDevExtract);
83
- server.middlewares.use(async (req, res, next) => {
84
- if (req.method !== "GET" && req.method !== "HEAD") {
85
- next();
86
- return;
87
- }
88
- const config = resolvedConfig;
89
- if (!config) {
90
- next();
91
- return;
92
- }
93
- const url = req.url?.split("?")[0] ?? "";
94
- const base = config.base.replace(/\/$/, "") || "";
95
- const expectedPath = base === "" || base === "/" ? `/${fileName.replace(/^\//, "")}` : `${base}/${fileName.replace(/^\//, "")}`;
96
- if (url !== expectedPath) {
97
- next();
98
- return;
99
- }
100
- const root = config.root ?? process.cwd();
101
- try {
102
- if (devExtractCss !== null) {
103
- res.statusCode = 200;
104
- res.setHeader("Content-Type", "text/css; charset=utf-8");
105
- res.setHeader("Cache-Control", "no-cache");
106
- res.end(devExtractCss);
107
- return;
108
- }
109
- if (!devExtractInFlight) {
110
- devExtractInFlight = runTypestylesBuild({
111
- root,
112
- modules: resolvedExtractModules
113
- }).then((css2) => {
114
- devExtractCss = css2;
115
- return css2;
116
- }).finally(() => {
117
- devExtractInFlight = null;
118
- });
119
- }
120
- const css = await devExtractInFlight;
121
- res.statusCode = 200;
122
- res.setHeader("Content-Type", "text/css; charset=utf-8");
123
- res.setHeader("Cache-Control", "no-cache");
124
- res.end(css);
125
- } catch (err) {
126
- next(err);
127
- }
128
- });
129
- },
130
- transform(code, id) {
131
- if (!/\.[jt]sx?$/.test(id)) return null;
132
- if (id.includes("node_modules")) return null;
133
- const { keys, prefixes } = extractNamespaces(code);
134
- const overrideHmr = moduleNeedsOverrideHmr(code);
135
- if (keys.length === 0 && prefixes.length === 0 && !overrideHmr) return null;
136
- if (warnDuplicates && prefixes.length > 0) {
137
- reportDuplicateNamespaces(moduleNamespaces, id, prefixes, this);
138
- }
139
- if (keys.length > 0 || prefixes.length > 0) {
140
- moduleNamespaces.set(id, { keys, prefixes });
141
- }
142
- if (!isServe) {
143
- return null;
144
- }
145
- const keysJSON = JSON.stringify(keys);
146
- const prefixesJSON = JSON.stringify(prefixes);
147
- const hmrImports = overrideHmr ? `import { invalidateKeys as __typestylesInvalidateKeys, createOverrideHmrSlot as __tsCreateOvHmr } from 'typestyles/hmr';
148
- ` : `import { invalidateKeys as __typestylesInvalidateKeys } from 'typestyles/hmr';
149
- `;
150
- const overrideBootstrap = overrideHmr ? `const __tsOvHmr = __tsCreateOvHmr();
151
- __tsOvHmr.activate();
152
- ` : "";
153
- const overrideTeardown = overrideHmr ? `
154
- __tsOvHmr.deactivate();
155
- ` : "";
156
- const disposeBody = [
157
- keys.length > 0 || prefixes.length > 0 ? `__typestylesInvalidateKeys(${keysJSON}, ${prefixesJSON});` : null,
158
- overrideHmr ? `__tsOvHmr.dispose();` : null
159
- ].filter(Boolean).join("\n ");
160
- const hmrCode = `${overrideTeardown}
37
+ const { warnDuplicates = true, coverage = true, extract } = options;
38
+ let resolvedExtractModules = [];
39
+ let resolvedMode = "runtime";
40
+ const moduleNamespaces = new Map();
41
+ let resolvedConfig = null;
42
+ let isBuildCommand = false;
43
+ let isServe = false;
44
+ const recipeModules = new Map();
45
+ let devExtractCss = null;
46
+ let devExtractInFlight = null;
47
+ return {
48
+ name: "typestyles",
49
+ enforce: "pre",
50
+ config(config, env) {
51
+ isBuildCommand = env.command === "build";
52
+ resolvedExtractModules = resolveExtractModulesForVite(resolve(config.root ?? process.cwd()), extract);
53
+ resolvedMode = resolveExtractMode(options.mode, resolvedExtractModules);
54
+ if (env.command === "build" && (resolvedMode === "build" || resolvedMode === "hybrid")) config.define = {
55
+ ...config.define ?? {},
56
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
57
+ };
58
+ return config;
59
+ },
60
+ configResolved(config) {
61
+ resolvedConfig = config;
62
+ isServe = config.command === "serve";
63
+ },
64
+ configureServer(server) {
65
+ if (resolvedExtractModules.length === 0) return;
66
+ if (resolvedMode === "runtime") return;
67
+ const fileName = extract?.fileName ?? "typestyles.css";
68
+ const invalidateDevExtract = () => {
69
+ devExtractCss = null;
70
+ devExtractInFlight = null;
71
+ };
72
+ server.watcher.on("change", invalidateDevExtract);
73
+ server.watcher.on("add", invalidateDevExtract);
74
+ server.watcher.on("unlink", invalidateDevExtract);
75
+ server.middlewares.use(async (req, res, next) => {
76
+ if (req.method !== "GET" && req.method !== "HEAD") {
77
+ next();
78
+ return;
79
+ }
80
+ const config = resolvedConfig;
81
+ if (!config) {
82
+ next();
83
+ return;
84
+ }
85
+ const url = req.url?.split("?")[0] ?? "";
86
+ const base = config.base.replace(/\/$/, "") || "";
87
+ if (url !== (base === "" || base === "/" ? `/${fileName.replace(/^\//, "")}` : `${base}/${fileName.replace(/^\//, "")}`)) {
88
+ next();
89
+ return;
90
+ }
91
+ const root = config.root ?? process.cwd();
92
+ try {
93
+ if (devExtractCss !== null) {
94
+ res.statusCode = 200;
95
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
96
+ res.setHeader("Cache-Control", "no-cache");
97
+ res.end(devExtractCss);
98
+ return;
99
+ }
100
+ if (!devExtractInFlight) devExtractInFlight = runTypestylesBuild({
101
+ root,
102
+ modules: resolvedExtractModules
103
+ }).then((css) => {
104
+ devExtractCss = css;
105
+ return css;
106
+ }).finally(() => {
107
+ devExtractInFlight = null;
108
+ });
109
+ const css = await devExtractInFlight;
110
+ res.statusCode = 200;
111
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
112
+ res.setHeader("Cache-Control", "no-cache");
113
+ res.end(css);
114
+ } catch (err) {
115
+ next(err);
116
+ }
117
+ });
118
+ },
119
+ transform(code, id) {
120
+ if (!/\.[jt]sx?$/.test(id)) return null;
121
+ if (id.includes("node_modules")) return null;
122
+ const { keys, prefixes, recipeNames } = extractNamespaces(code);
123
+ const overrideHmr = moduleNeedsOverrideHmr$1(code);
124
+ if (coverage && isBuildCommand && resolvedMode !== "runtime" && resolvedExtractModules.length > 0 && recipeNames.length > 0) recipeModules.set(id, recipeNames);
125
+ if (keys.length === 0 && prefixes.length === 0 && !overrideHmr) return null;
126
+ if (warnDuplicates && prefixes.length > 0) reportDuplicateNamespaces(moduleNamespaces, id, prefixes, this);
127
+ if (keys.length > 0 || prefixes.length > 0) moduleNamespaces.set(id, {
128
+ keys,
129
+ prefixes
130
+ });
131
+ if (!isServe) return null;
132
+ const keysJSON = JSON.stringify(keys);
133
+ const prefixesJSON = JSON.stringify(prefixes);
134
+ const hmrImports = overrideHmr ? `import { invalidateKeys as __typestylesInvalidateKeys, createOverrideHmrSlot as __tsCreateOvHmr } from 'typestyles/hmr';\n` : `import { invalidateKeys as __typestylesInvalidateKeys } from 'typestyles/hmr';\n`;
135
+ const overrideBootstrap = overrideHmr ? `const __tsOvHmr = __tsCreateOvHmr();\n__tsOvHmr.activate();\n` : "";
136
+ const hmrCode = `${overrideHmr ? `\n__tsOvHmr.deactivate();\n` : ""}
161
137
  if (import.meta.hot) {
162
138
  import.meta.hot.accept();
163
139
  import.meta.hot.dispose(() => {
164
- ${disposeBody}
140
+ ${[keys.length > 0 || prefixes.length > 0 ? `__typestylesInvalidateKeys(${keysJSON}, ${prefixesJSON});` : null, overrideHmr ? `__tsOvHmr.dispose();` : null].filter(Boolean).join("\n ")}
165
141
  });
166
142
  }`;
167
- return {
168
- code: hmrImports + overrideBootstrap + code + hmrCode,
169
- map: null
170
- };
171
- },
172
- transformIndexHtml: {
173
- order: "pre",
174
- handler(html) {
175
- if (resolvedExtractModules.length === 0) return;
176
- if (resolvedMode === "runtime") return;
177
- if (!resolvedConfig) return;
178
- const fileName = extract?.fileName ?? "typestyles.css";
179
- const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
180
- if (htmlLinksTypestylesCss(html, href, fileName)) {
181
- return;
182
- }
183
- return [
184
- {
185
- tag: "link",
186
- attrs: {
187
- rel: "stylesheet",
188
- href
189
- },
190
- injectTo: "head"
191
- }
192
- ];
193
- }
194
- },
195
- async generateBundle() {
196
- if (!isBuildCommand) return;
197
- if (resolvedMode === "runtime") return;
198
- if (!resolvedExtractModules.length) return;
199
- if (!resolvedConfig) return;
200
- const root = resolvedConfig.root ?? process.cwd();
201
- const fileName = extract?.fileName ?? "typestyles.css";
202
- try {
203
- const css = await runTypestylesBuild({
204
- root,
205
- modules: resolvedExtractModules
206
- });
207
- this.emitFile({
208
- type: "asset",
209
- fileName,
210
- source: css
211
- });
212
- } catch (err) {
213
- this.error(
214
- `[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`
215
- );
216
- }
217
- }
218
- };
143
+ return {
144
+ code: hmrImports + overrideBootstrap + code + hmrCode,
145
+ map: null
146
+ };
147
+ },
148
+ transformIndexHtml: {
149
+ order: "pre",
150
+ handler(html) {
151
+ if (resolvedExtractModules.length === 0) return;
152
+ if (resolvedMode === "runtime") return;
153
+ if (!resolvedConfig) return;
154
+ const fileName = extract?.fileName ?? "typestyles.css";
155
+ const href = resolveTypestylesCssHref(resolvedConfig.base, fileName);
156
+ if (htmlLinksTypestylesCss(html, href, fileName)) return;
157
+ return [{
158
+ tag: "link",
159
+ attrs: {
160
+ rel: "stylesheet",
161
+ href
162
+ },
163
+ injectTo: "head"
164
+ }];
165
+ }
166
+ },
167
+ async generateBundle() {
168
+ if (!isBuildCommand) return;
169
+ if (resolvedMode === "runtime") return;
170
+ if (!resolvedExtractModules.length) return;
171
+ if (!resolvedConfig) return;
172
+ const root = resolvedConfig.root ?? process.cwd();
173
+ const fileName = extract?.fileName ?? "typestyles.css";
174
+ if (coverage && recipeModules.size > 0) {
175
+ let missing = [];
176
+ try {
177
+ missing = await findUnextractedRecipes({
178
+ root,
179
+ extractEntries: resolvedExtractModules,
180
+ recipeModules: [...recipeModules.entries()].map(([id, names]) => ({
181
+ id,
182
+ names
183
+ }))
184
+ });
185
+ } catch (err) {
186
+ this.error(`[typestyles] Failed to check extract coverage: ${err instanceof Error ? err.message : String(err)}`);
187
+ return;
188
+ }
189
+ if (missing.length > 0) {
190
+ this.error(formatUnextractedRecipeError(missing, resolvedExtractModules));
191
+ return;
192
+ }
193
+ }
194
+ try {
195
+ const css = await runTypestylesBuild({
196
+ root,
197
+ modules: resolvedExtractModules
198
+ });
199
+ this.emitFile({
200
+ type: "asset",
201
+ fileName,
202
+ source: css
203
+ });
204
+ } catch (err) {
205
+ this.error(`[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`);
206
+ }
207
+ }
208
+ };
219
209
  }
220
- export {
221
- DEFAULT_EXTRACT_MODULE_CANDIDATES,
222
- typestylesPlugin as default,
223
- discoverDefaultExtractModules,
224
- extractNamespaces,
225
- htmlLinksTypestylesCss,
226
- moduleNeedsOverrideHmr2 as moduleNeedsOverrideHmr,
227
- resolveTypestylesCssHref
228
- };
210
+ //#endregion
211
+ 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.2",
3
+ "version": "0.5.4",
4
4
  "description": "Vite plugin for typestyles HMR support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -38,20 +38,17 @@
38
38
  "vite": ">=5.0.0"
39
39
  },
40
40
  "devDependencies": {
41
- "eslint": "^9.39.2",
42
- "tsup": "^8.0.0",
43
- "typescript": "^5.4.0",
44
- "vite": "^6.0.0",
45
- "vitest": "^3.0.0",
46
- "typestyles": "0.32.2"
41
+ "typescript": "^6.0.0",
42
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0",
43
+ "vite-plus": "1.3.0",
44
+ "typestyles": "0.33.0"
47
45
  },
48
46
  "dependencies": {
49
- "@typestyles/build-runner": "0.6.2"
47
+ "@typestyles/build-runner": "0.6.4"
50
48
  },
51
49
  "scripts": {
52
- "build": "tsup src/index.ts --format esm,cjs --dts --clean --external typestyles,@typestyles/build-runner",
53
- "test": "vitest run",
54
- "lint": "eslint .",
50
+ "build": "vp pack",
51
+ "test": "vp test run",
55
52
  "typecheck": "tsc --noEmit"
56
53
  }
57
54
  }