@typestyles/vite 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -24,20 +24,16 @@ __export(index_exports, {
24
24
  extractNamespaces: () => extractNamespaces
25
25
  });
26
26
  module.exports = __toCommonJS(index_exports);
27
- var STYLES_CREATE_RE = /styles\.create\(\s*['"]([^'"]+)['"]/g;
27
+ var import_build_runner = require("@typestyles/build-runner");
28
28
  var STYLES_COMPONENT_RE = /styles\.component\(\s*['"]([^'"]+)['"]/g;
29
29
  var TOKENS_CREATE_RE = /tokens\.create\(\s*['"]([^'"]+)['"]/g;
30
30
  var CREATE_THEME_RE = /(?:tokens\.)?createTheme\(\s*['"]([^'"]+)['"]/g;
31
31
  var KEYFRAMES_CREATE_RE = /keyframes\.create\(\s*['"]([^'"]+)['"]/g;
32
32
  var GLOBAL_STYLE_RE = /global\.style\(\s*['"]([^'"]+)['"]/g;
33
33
  var GLOBAL_FONT_FACE_RE = /global\.fontFace\(\s*['"]([^'"]+)['"]/g;
34
- var TYPESTYLES_IMPORT_RE = /(?:from\s+|import\s+|require\s*\(\s*)['"]typestyles['"]/;
35
34
  function extractNamespaces(code) {
36
35
  const keys = [];
37
36
  const prefixes = [];
38
- for (const match of code.matchAll(STYLES_CREATE_RE)) {
39
- prefixes.push(`.${match[1]}-`);
40
- }
41
37
  for (const match of code.matchAll(STYLES_COMPONENT_RE)) {
42
38
  prefixes.push(`.${match[1]}-`);
43
39
  }
@@ -59,15 +55,94 @@ function extractNamespaces(code) {
59
55
  return { keys, prefixes };
60
56
  }
61
57
  function typestylesPlugin(options = {}) {
62
- const { warnDuplicates = true } = options;
58
+ const { warnDuplicates = true, extract } = options;
59
+ const extractModules = extract?.modules ?? [];
60
+ const mode = options.mode ?? (extractModules.length > 0 ? "build" : "runtime");
63
61
  const moduleNamespaces = /* @__PURE__ */ new Map();
62
+ let resolvedConfig = null;
63
+ let isBuildCommand = false;
64
+ let isServe = false;
65
+ let devExtractCss = null;
66
+ let devExtractInFlight = null;
64
67
  return {
65
68
  name: "typestyles",
66
69
  enforce: "pre",
70
+ config(config, env) {
71
+ isBuildCommand = env.command === "build";
72
+ if (env.command === "build" && (mode === "build" || mode === "hybrid")) {
73
+ config.define = {
74
+ ...config.define ?? {},
75
+ // Inlined by the bundler so typestyles sheet skips creating <style> in production
76
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
77
+ };
78
+ }
79
+ return config;
80
+ },
81
+ configResolved(config) {
82
+ resolvedConfig = config;
83
+ isServe = config.command === "serve";
84
+ },
85
+ configureServer(server) {
86
+ if (!extract || extractModules.length === 0) return;
87
+ if (mode === "runtime") return;
88
+ const fileName = extract.fileName ?? "typestyles.css";
89
+ const invalidateDevExtract = () => {
90
+ devExtractCss = null;
91
+ devExtractInFlight = null;
92
+ };
93
+ server.watcher.on("change", invalidateDevExtract);
94
+ server.watcher.on("add", invalidateDevExtract);
95
+ server.watcher.on("unlink", invalidateDevExtract);
96
+ server.middlewares.use(async (req, res, next) => {
97
+ if (req.method !== "GET" && req.method !== "HEAD") {
98
+ next();
99
+ return;
100
+ }
101
+ const config = resolvedConfig;
102
+ if (!config) {
103
+ next();
104
+ return;
105
+ }
106
+ const url = req.url?.split("?")[0] ?? "";
107
+ const base = config.base.replace(/\/$/, "") || "";
108
+ const expectedPath = base === "" || base === "/" ? `/${fileName.replace(/^\//, "")}` : `${base}/${fileName.replace(/^\//, "")}`;
109
+ if (url !== expectedPath) {
110
+ next();
111
+ return;
112
+ }
113
+ const root = config.root ?? process.cwd();
114
+ try {
115
+ if (devExtractCss !== null) {
116
+ res.statusCode = 200;
117
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
118
+ res.setHeader("Cache-Control", "no-cache");
119
+ res.end(devExtractCss);
120
+ return;
121
+ }
122
+ if (!devExtractInFlight) {
123
+ devExtractInFlight = (0, import_build_runner.runTypestylesBuild)({
124
+ root,
125
+ modules: extractModules
126
+ }).then((css2) => {
127
+ devExtractCss = css2;
128
+ return css2;
129
+ }).finally(() => {
130
+ devExtractInFlight = null;
131
+ });
132
+ }
133
+ const css = await devExtractInFlight;
134
+ res.statusCode = 200;
135
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
136
+ res.setHeader("Cache-Control", "no-cache");
137
+ res.end(css);
138
+ } catch (err) {
139
+ next(err);
140
+ }
141
+ });
142
+ },
67
143
  transform(code, id) {
68
144
  if (!/\.[jt]sx?$/.test(id)) return null;
69
145
  if (id.includes("node_modules")) return null;
70
- if (!TYPESTYLES_IMPORT_RE.test(code)) return null;
71
146
  const { keys, prefixes } = extractNamespaces(code);
72
147
  if (keys.length === 0 && prefixes.length === 0) return null;
73
148
  if (warnDuplicates) {
@@ -84,21 +159,47 @@ function typestylesPlugin(options = {}) {
84
159
  }
85
160
  }
86
161
  moduleNamespaces.set(id, { keys, prefixes });
162
+ if (!isServe) {
163
+ return null;
164
+ }
87
165
  const keysJSON = JSON.stringify(keys);
88
166
  const prefixesJSON = JSON.stringify(prefixes);
167
+ const hmrImport = `import { invalidateKeys as __typestylesInvalidateKeys } from 'typestyles/hmr';
168
+ `;
89
169
  const hmrCode = `
90
170
  if (import.meta.hot) {
91
- import('typestyles/hmr').then(({ invalidateKeys: __typestyles_invalidateKeys }) => {
92
- import.meta.hot.accept();
93
- import.meta.hot.dispose(() => {
94
- __typestyles_invalidateKeys(${keysJSON}, ${prefixesJSON});
95
- });
171
+ import.meta.hot.accept();
172
+ import.meta.hot.dispose(() => {
173
+ __typestylesInvalidateKeys(${keysJSON}, ${prefixesJSON});
96
174
  });
97
175
  }`;
98
176
  return {
99
- code: code + hmrCode,
177
+ code: hmrImport + code + hmrCode,
100
178
  map: null
101
179
  };
180
+ },
181
+ async generateBundle() {
182
+ if (!isBuildCommand) return;
183
+ if (mode === "runtime") return;
184
+ if (!extract || !extractModules.length) return;
185
+ if (!resolvedConfig) return;
186
+ const root = resolvedConfig.root ?? process.cwd();
187
+ const fileName = extract.fileName ?? "typestyles.css";
188
+ try {
189
+ const css = await (0, import_build_runner.runTypestylesBuild)({
190
+ root,
191
+ modules: extractModules
192
+ });
193
+ this.emitFile({
194
+ type: "asset",
195
+ fileName,
196
+ source: css
197
+ });
198
+ } catch (err) {
199
+ this.error(
200
+ `[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`
201
+ );
202
+ }
102
203
  }
103
204
  };
104
205
  }
package/dist/index.d.cts CHANGED
@@ -1,8 +1,36 @@
1
1
  import { Plugin } from 'vite';
2
2
 
3
+ interface TypestylesExtractOptions {
4
+ /**
5
+ * Modules that should be imported during build to register styles.
6
+ * Paths are resolved relative to Vite's project root.
7
+ */
8
+ modules: string[];
9
+ /**
10
+ * Output CSS filename (in the build assets). Defaults to "typestyles.css".
11
+ */
12
+ fileName?: string;
13
+ }
3
14
  interface TypestylesPluginOptions {
4
15
  /** Warn about duplicate namespaces across modules. Defaults to true. */
5
16
  warnDuplicates?: boolean;
17
+ /**
18
+ * Mode for typestyles integration:
19
+ * - `"runtime"`: HMR only, no build-time extraction.
20
+ * - `"build"`: emit a static CSS asset on `vite build` and disable client injection there.
21
+ * - `"hybrid"`: extract on build and keep runtime-compatible behavior.
22
+ *
23
+ * When omitted and `extract.modules` is non-empty, defaults to `"build"`: `vite dev` keeps
24
+ * runtime injection + HMR (runtime is only disabled during `vite build`), serves the same
25
+ * extracted CSS at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA
26
+ * fallback returning HTML for that URL), and production emits the CSS file. With no `extract`
27
+ * config, defaults to `"runtime"`.
28
+ */
29
+ mode?: 'runtime' | 'build' | 'hybrid';
30
+ /**
31
+ * Options for build-time CSS extraction when mode is "build" or "hybrid".
32
+ */
33
+ extract?: TypestylesExtractOptions;
6
34
  }
7
35
  /**
8
36
  * Extract namespace information from source code.
@@ -15,10 +43,11 @@ declare function extractNamespaces(code: string): {
15
43
  /**
16
44
  * Vite plugin for typestyles HMR support.
17
45
  *
18
- * When a module that uses typestyles is edited, this plugin injects HMR
19
- * accept/dispose handlers that invalidate the module's style registrations
20
- * before re-execution — so updated CSS takes effect without a full reload.
46
+ * When a module that registers typestyles (e.g. `styles.component`, `tokens.create`) is edited,
47
+ * this plugin injects HMR accept/dispose handlers that invalidate that module's registrations
48
+ * before re-execution. Files may import from a local re-export such as `./typestyles` rather
49
+ * than `from 'typestyles'` directly — we key off API call patterns in the source, not the import path.
21
50
  */
22
51
  declare function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
23
52
 
24
- export { type TypestylesPluginOptions, typestylesPlugin as default, extractNamespaces };
53
+ export { type TypestylesExtractOptions, type TypestylesPluginOptions, typestylesPlugin as default, extractNamespaces };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,36 @@
1
1
  import { Plugin } from 'vite';
2
2
 
3
+ interface TypestylesExtractOptions {
4
+ /**
5
+ * Modules that should be imported during build to register styles.
6
+ * Paths are resolved relative to Vite's project root.
7
+ */
8
+ modules: string[];
9
+ /**
10
+ * Output CSS filename (in the build assets). Defaults to "typestyles.css".
11
+ */
12
+ fileName?: string;
13
+ }
3
14
  interface TypestylesPluginOptions {
4
15
  /** Warn about duplicate namespaces across modules. Defaults to true. */
5
16
  warnDuplicates?: boolean;
17
+ /**
18
+ * Mode for typestyles integration:
19
+ * - `"runtime"`: HMR only, no build-time extraction.
20
+ * - `"build"`: emit a static CSS asset on `vite build` and disable client injection there.
21
+ * - `"hybrid"`: extract on build and keep runtime-compatible behavior.
22
+ *
23
+ * When omitted and `extract.modules` is non-empty, defaults to `"build"`: `vite dev` keeps
24
+ * runtime injection + HMR (runtime is only disabled during `vite build`), serves the same
25
+ * extracted CSS at `extract.fileName` so `<link href="/typestyles.css">` is valid (avoids SPA
26
+ * fallback returning HTML for that URL), and production emits the CSS file. With no `extract`
27
+ * config, defaults to `"runtime"`.
28
+ */
29
+ mode?: 'runtime' | 'build' | 'hybrid';
30
+ /**
31
+ * Options for build-time CSS extraction when mode is "build" or "hybrid".
32
+ */
33
+ extract?: TypestylesExtractOptions;
6
34
  }
7
35
  /**
8
36
  * Extract namespace information from source code.
@@ -15,10 +43,11 @@ declare function extractNamespaces(code: string): {
15
43
  /**
16
44
  * Vite plugin for typestyles HMR support.
17
45
  *
18
- * When a module that uses typestyles is edited, this plugin injects HMR
19
- * accept/dispose handlers that invalidate the module's style registrations
20
- * before re-execution — so updated CSS takes effect without a full reload.
46
+ * When a module that registers typestyles (e.g. `styles.component`, `tokens.create`) is edited,
47
+ * this plugin injects HMR accept/dispose handlers that invalidate that module's registrations
48
+ * before re-execution. Files may import from a local re-export such as `./typestyles` rather
49
+ * than `from 'typestyles'` directly — we key off API call patterns in the source, not the import path.
21
50
  */
22
51
  declare function typestylesPlugin(options?: TypestylesPluginOptions): Plugin;
23
52
 
24
- export { type TypestylesPluginOptions, typestylesPlugin as default, extractNamespaces };
53
+ export { type TypestylesExtractOptions, type TypestylesPluginOptions, typestylesPlugin as default, extractNamespaces };
package/dist/index.js CHANGED
@@ -1,18 +1,14 @@
1
1
  // src/index.ts
2
- var STYLES_CREATE_RE = /styles\.create\(\s*['"]([^'"]+)['"]/g;
2
+ import { runTypestylesBuild } from "@typestyles/build-runner";
3
3
  var STYLES_COMPONENT_RE = /styles\.component\(\s*['"]([^'"]+)['"]/g;
4
4
  var TOKENS_CREATE_RE = /tokens\.create\(\s*['"]([^'"]+)['"]/g;
5
5
  var CREATE_THEME_RE = /(?:tokens\.)?createTheme\(\s*['"]([^'"]+)['"]/g;
6
6
  var KEYFRAMES_CREATE_RE = /keyframes\.create\(\s*['"]([^'"]+)['"]/g;
7
7
  var GLOBAL_STYLE_RE = /global\.style\(\s*['"]([^'"]+)['"]/g;
8
8
  var GLOBAL_FONT_FACE_RE = /global\.fontFace\(\s*['"]([^'"]+)['"]/g;
9
- var TYPESTYLES_IMPORT_RE = /(?:from\s+|import\s+|require\s*\(\s*)['"]typestyles['"]/;
10
9
  function extractNamespaces(code) {
11
10
  const keys = [];
12
11
  const prefixes = [];
13
- for (const match of code.matchAll(STYLES_CREATE_RE)) {
14
- prefixes.push(`.${match[1]}-`);
15
- }
16
12
  for (const match of code.matchAll(STYLES_COMPONENT_RE)) {
17
13
  prefixes.push(`.${match[1]}-`);
18
14
  }
@@ -34,15 +30,94 @@ function extractNamespaces(code) {
34
30
  return { keys, prefixes };
35
31
  }
36
32
  function typestylesPlugin(options = {}) {
37
- const { warnDuplicates = true } = options;
33
+ const { warnDuplicates = true, extract } = options;
34
+ const extractModules = extract?.modules ?? [];
35
+ const mode = options.mode ?? (extractModules.length > 0 ? "build" : "runtime");
38
36
  const moduleNamespaces = /* @__PURE__ */ new Map();
37
+ let resolvedConfig = null;
38
+ let isBuildCommand = false;
39
+ let isServe = false;
40
+ let devExtractCss = null;
41
+ let devExtractInFlight = null;
39
42
  return {
40
43
  name: "typestyles",
41
44
  enforce: "pre",
45
+ config(config, env) {
46
+ isBuildCommand = env.command === "build";
47
+ if (env.command === "build" && (mode === "build" || mode === "hybrid")) {
48
+ config.define = {
49
+ ...config.define ?? {},
50
+ // Inlined by the bundler so typestyles sheet skips creating <style> in production
51
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify("true")
52
+ };
53
+ }
54
+ return config;
55
+ },
56
+ configResolved(config) {
57
+ resolvedConfig = config;
58
+ isServe = config.command === "serve";
59
+ },
60
+ configureServer(server) {
61
+ if (!extract || extractModules.length === 0) return;
62
+ if (mode === "runtime") return;
63
+ const fileName = extract.fileName ?? "typestyles.css";
64
+ const invalidateDevExtract = () => {
65
+ devExtractCss = null;
66
+ devExtractInFlight = null;
67
+ };
68
+ server.watcher.on("change", invalidateDevExtract);
69
+ server.watcher.on("add", invalidateDevExtract);
70
+ server.watcher.on("unlink", invalidateDevExtract);
71
+ server.middlewares.use(async (req, res, next) => {
72
+ if (req.method !== "GET" && req.method !== "HEAD") {
73
+ next();
74
+ return;
75
+ }
76
+ const config = resolvedConfig;
77
+ if (!config) {
78
+ next();
79
+ return;
80
+ }
81
+ const url = req.url?.split("?")[0] ?? "";
82
+ const base = config.base.replace(/\/$/, "") || "";
83
+ const expectedPath = base === "" || base === "/" ? `/${fileName.replace(/^\//, "")}` : `${base}/${fileName.replace(/^\//, "")}`;
84
+ if (url !== expectedPath) {
85
+ next();
86
+ return;
87
+ }
88
+ const root = config.root ?? process.cwd();
89
+ try {
90
+ if (devExtractCss !== null) {
91
+ res.statusCode = 200;
92
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
93
+ res.setHeader("Cache-Control", "no-cache");
94
+ res.end(devExtractCss);
95
+ return;
96
+ }
97
+ if (!devExtractInFlight) {
98
+ devExtractInFlight = runTypestylesBuild({
99
+ root,
100
+ modules: extractModules
101
+ }).then((css2) => {
102
+ devExtractCss = css2;
103
+ return css2;
104
+ }).finally(() => {
105
+ devExtractInFlight = null;
106
+ });
107
+ }
108
+ const css = await devExtractInFlight;
109
+ res.statusCode = 200;
110
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
111
+ res.setHeader("Cache-Control", "no-cache");
112
+ res.end(css);
113
+ } catch (err) {
114
+ next(err);
115
+ }
116
+ });
117
+ },
42
118
  transform(code, id) {
43
119
  if (!/\.[jt]sx?$/.test(id)) return null;
44
120
  if (id.includes("node_modules")) return null;
45
- if (!TYPESTYLES_IMPORT_RE.test(code)) return null;
46
121
  const { keys, prefixes } = extractNamespaces(code);
47
122
  if (keys.length === 0 && prefixes.length === 0) return null;
48
123
  if (warnDuplicates) {
@@ -59,21 +134,47 @@ function typestylesPlugin(options = {}) {
59
134
  }
60
135
  }
61
136
  moduleNamespaces.set(id, { keys, prefixes });
137
+ if (!isServe) {
138
+ return null;
139
+ }
62
140
  const keysJSON = JSON.stringify(keys);
63
141
  const prefixesJSON = JSON.stringify(prefixes);
142
+ const hmrImport = `import { invalidateKeys as __typestylesInvalidateKeys } from 'typestyles/hmr';
143
+ `;
64
144
  const hmrCode = `
65
145
  if (import.meta.hot) {
66
- import('typestyles/hmr').then(({ invalidateKeys: __typestyles_invalidateKeys }) => {
67
- import.meta.hot.accept();
68
- import.meta.hot.dispose(() => {
69
- __typestyles_invalidateKeys(${keysJSON}, ${prefixesJSON});
70
- });
146
+ import.meta.hot.accept();
147
+ import.meta.hot.dispose(() => {
148
+ __typestylesInvalidateKeys(${keysJSON}, ${prefixesJSON});
71
149
  });
72
150
  }`;
73
151
  return {
74
- code: code + hmrCode,
152
+ code: hmrImport + code + hmrCode,
75
153
  map: null
76
154
  };
155
+ },
156
+ async generateBundle() {
157
+ if (!isBuildCommand) return;
158
+ if (mode === "runtime") return;
159
+ if (!extract || !extractModules.length) return;
160
+ if (!resolvedConfig) return;
161
+ const root = resolvedConfig.root ?? process.cwd();
162
+ const fileName = extract.fileName ?? "typestyles.css";
163
+ try {
164
+ const css = await runTypestylesBuild({
165
+ root,
166
+ modules: extractModules
167
+ });
168
+ this.emitFile({
169
+ type: "asset",
170
+ fileName,
171
+ source: css
172
+ });
173
+ } catch (err) {
174
+ this.error(
175
+ `[typestyles] Failed to extract CSS: ${err instanceof Error ? err.message : String(err)}`
176
+ );
177
+ }
77
178
  }
78
179
  };
79
180
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typestyles/vite",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Vite plugin for typestyles HMR support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -38,14 +38,20 @@
38
38
  "vite": ">=5.0.0"
39
39
  },
40
40
  "devDependencies": {
41
+ "eslint": "^9.39.2",
41
42
  "tsup": "^8.0.0",
42
43
  "typescript": "^5.4.0",
43
44
  "vite": "^6.0.0",
44
- "vitest": "^3.0.0"
45
+ "vitest": "^3.0.0",
46
+ "typestyles": "0.5.0"
47
+ },
48
+ "dependencies": {
49
+ "@typestyles/build-runner": "0.3.0"
45
50
  },
46
51
  "scripts": {
47
- "build": "tsup src/index.ts --format esm,cjs --dts --clean",
52
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean --external typestyles,@typestyles/build-runner",
48
53
  "test": "vitest run",
54
+ "lint": "eslint .",
49
55
  "typecheck": "tsc --noEmit"
50
56
  }
51
57
  }