@vanilla-extract/vite-plugin 0.0.0-inline-prototype-2023326232811 → 0.0.0-master-20240201234045

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.
@@ -1,11 +1,10 @@
1
1
  import { Plugin } from 'vite';
2
- import { IdentifierOption, CompileOptions } from '@vanilla-extract/integration';
2
+ import { IdentifierOption } from '@vanilla-extract/integration';
3
3
 
4
4
  interface Options {
5
5
  identifiers?: IdentifierOption;
6
- emitCssInSsr?: boolean;
7
- esbuildOptions?: CompileOptions['esbuildOptions'];
6
+ unstable_mode?: 'transform' | 'emitCss';
8
7
  }
9
- declare function vanillaExtractPlugin({ identifiers, emitCssInSsr, esbuildOptions, }?: Options): Plugin;
8
+ declare function vanillaExtractPlugin({ identifiers, unstable_mode: mode, }?: Options): Plugin;
10
9
 
11
10
  export { vanillaExtractPlugin };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vanilla-extract-vite-plugin.cjs.d.ts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}
@@ -3,95 +3,72 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var path = require('path');
6
- var vite = require('vite');
7
- var outdent = require('outdent');
8
6
  var integration = require('@vanilla-extract/integration');
9
7
 
10
8
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
9
 
12
- function _interopNamespace(e) {
13
- if (e && e.__esModule) return e;
14
- var n = Object.create(null);
15
- if (e) {
16
- Object.keys(e).forEach(function (k) {
17
- if (k !== 'default') {
18
- var d = Object.getOwnPropertyDescriptor(e, k);
19
- Object.defineProperty(n, k, d.get ? d : {
20
- enumerable: true,
21
- get: function () { return e[k]; }
22
- });
23
- }
24
- });
25
- }
26
- n["default"] = e;
27
- return Object.freeze(n);
28
- }
29
-
30
10
  var path__default = /*#__PURE__*/_interopDefault(path);
31
- var outdent__default = /*#__PURE__*/_interopDefault(outdent);
32
11
 
33
- // Mostly copied from vite's implementation
34
- // https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
35
- const resolvePostcssConfig = async config => {
36
- var _config$css;
37
- // inline postcss config via vite config
38
- const inlineOptions = (_config$css = config.css) === null || _config$css === void 0 ? void 0 : _config$css.postcss;
39
- const inlineOptionsIsString = typeof inlineOptions === 'string';
40
- if (inlineOptions && !inlineOptionsIsString) {
41
- const options = {
42
- ...inlineOptions
43
- };
44
- delete options.plugins;
45
- return {
46
- options,
47
- plugins: inlineOptions.plugins || []
48
- };
49
- } else {
50
- try {
51
- const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
52
- const postCssConfig = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss-load-config')); })).default({}, searchPath);
53
- return {
54
- options: postCssConfig.options,
55
- // @ts-expect-error - The postcssrc options don't agree with real postcss, but it should be ok
56
- plugins: postCssConfig.plugins
57
- };
58
- } catch (e) {
59
- if (!/No PostCSS Config found/.test(e.message)) {
60
- throw e;
61
- }
62
- return null;
63
- }
64
- }
65
- };
66
-
67
- const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
68
12
  const virtualExtCss = '.vanilla.css';
69
- const virtualExtJs = '.vanilla.js';
13
+ const isVirtualId = id => id.endsWith(virtualExtCss);
14
+ const fileIdToVirtualId = id => `${id}${virtualExtCss}`;
15
+ const virtualIdToFileId = virtualId => virtualId.slice(0, -virtualExtCss.length);
70
16
  function vanillaExtractPlugin({
71
17
  identifiers,
72
- emitCssInSsr,
73
- esbuildOptions
18
+ unstable_mode: mode = 'emitCss'
74
19
  } = {}) {
75
20
  let config;
21
+ let userConfig;
76
22
  let server;
77
- let postCssConfig;
78
- const cssMap = new Map();
79
- const hasEmitCssOverride = typeof emitCssInSsr === 'boolean';
80
- let resolvedEmitCssInSsr = hasEmitCssOverride ? emitCssInSsr : !!process.env.VITE_RSC_BUILD;
81
23
  let packageName;
82
- const getAbsoluteVirtualFileId = source => vite.normalizePath(path__default["default"].join(config.root, source));
24
+ let compiler;
25
+ const getIdentOption = () => identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
26
+ const getAbsoluteId = filePath => {
27
+ let resolvedId = filePath;
28
+ if (filePath.startsWith(config.root) ||
29
+ // In monorepos the absolute path will be outside of config.root, so we check that they have the same root on the file system
30
+ path__default["default"].isAbsolute(filePath) && filePath.split(path__default["default"].sep)[1] === config.root.split(path__default["default"].sep)[1]) {
31
+ resolvedId = filePath;
32
+ } else {
33
+ // In SSR mode we can have paths like /app/styles.css.ts
34
+ resolvedId = path__default["default"].join(config.root, filePath);
35
+ }
36
+ return integration.normalizePath(resolvedId);
37
+ };
38
+ function invalidateModule(absoluteId) {
39
+ if (!server) return;
40
+ const {
41
+ moduleGraph
42
+ } = server;
43
+ const modules = moduleGraph.getModulesByFile(absoluteId);
44
+ if (modules) {
45
+ for (const module of modules) {
46
+ moduleGraph.invalidateModule(module);
47
+
48
+ // Vite uses this timestamp to add `?t=` query string automatically for HMR.
49
+ module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
50
+ }
51
+ }
52
+ }
53
+ function addWatchFiles(fromId, files) {
54
+ // We don't need to watch files in build mode
55
+ if (config.command === 'build' && !config.build.watch) {
56
+ return;
57
+ }
58
+ for (const file of files) {
59
+ if (!file.includes('node_modules') && integration.normalizePath(file) !== fromId) {
60
+ this.addWatchFile(file);
61
+ }
62
+ }
63
+ }
83
64
  return {
84
65
  name: 'vanilla-extract',
85
- enforce: 'pre',
86
66
  configureServer(_server) {
87
67
  server = _server;
88
68
  },
89
- config(_userConfig, env) {
90
- const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
69
+ config(viteUserConfig) {
70
+ userConfig = viteUserConfig;
91
71
  return {
92
- optimizeDeps: {
93
- include
94
- },
95
72
  ssr: {
96
73
  external: ['@vanilla-extract/css', '@vanilla-extract/css/fileScope', '@vanilla-extract/css/adapter']
97
74
  }
@@ -100,150 +77,82 @@ function vanillaExtractPlugin({
100
77
  async configResolved(resolvedConfig) {
101
78
  config = resolvedConfig;
102
79
  packageName = integration.getPackageInfo(config.root).name;
103
- if (config.command === 'serve') {
104
- postCssConfig = await resolvePostcssConfig(config);
105
- }
106
- if (!hasEmitCssOverride && config.plugins.some(plugin => ['astro:build', 'solid-start-server', 'vite-plugin-qwik', 'vite-plugin-svelte'].includes(plugin.name))) {
107
- resolvedEmitCssInSsr = true;
108
- }
109
- },
110
- resolveId(source) {
111
- const [validId, query] = source.split('?');
112
- if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
113
- return;
114
- }
115
-
116
- // Absolute paths seem to occur often in monorepos, where files are
117
- // imported from outside the config root.
118
- const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
119
-
120
- // There should always be an entry in the `cssMap` here.
121
- // The only valid scenario for a missing one is if someone had written
122
- // a file in their app using the .vanilla.js/.vanilla.css extension
123
- if (cssMap.has(absoluteId)) {
124
- // Keep the original query string for HMR.
125
- return absoluteId + (query ? `?${query}` : '');
80
+ if (mode !== 'transform') {
81
+ var _userConfig$plugins;
82
+ compiler = integration.createCompiler({
83
+ root: config.root,
84
+ identifiers: getIdentOption(),
85
+ cssImportSpecifier: fileIdToVirtualId,
86
+ viteResolve: config.resolve,
87
+ vitePlugins: (_userConfig$plugins = userConfig.plugins) === null || _userConfig$plugins === void 0 ? void 0 : _userConfig$plugins.flat().filter(plugin => typeof plugin === 'object' && plugin !== null && 'name' in plugin &&
88
+ // Prevent an infinite loop where the compiler creates a new instance of the plugin,
89
+ // which creates a new compiler, which creates a new instance of the plugin, etc.
90
+ plugin.name !== 'vanilla-extract' &&
91
+ // Skip Vitest plugins
92
+ plugin.name !== 'vitest' && !plugin.name.startsWith('vitest:'))
93
+ });
126
94
  }
127
95
  },
128
- load(id) {
129
- const [validId] = id.split('?');
130
- if (!cssMap.has(validId)) {
131
- return;
132
- }
133
- const css = cssMap.get(validId);
134
- if (typeof css !== 'string') {
135
- return;
136
- }
137
- if (validId.endsWith(virtualExtCss)) {
138
- return css;
139
- }
140
- return outdent__default["default"]`
141
- import { injectStyles } from '@vanilla-extract/css/injectStyles';
142
-
143
- const inject = (css) => injectStyles({
144
- fileScope: ${JSON.stringify({
145
- filePath: validId
146
- })},
147
- css
148
- });
149
-
150
- inject(${JSON.stringify(css)});
151
-
152
- if (import.meta.hot) {
153
- import.meta.hot.on('${styleUpdateEvent(validId)}', (css) => {
154
- inject(css);
155
- });
156
- }
157
- `;
96
+ buildEnd() {
97
+ var _compiler;
98
+ (_compiler = compiler) === null || _compiler === void 0 ? void 0 : _compiler.close();
158
99
  },
159
- async transform(code, id, ssrParam) {
100
+ async transform(code, id) {
160
101
  const [validId] = id.split('?');
161
102
  if (!integration.cssFileFilter.test(validId)) {
162
103
  return null;
163
104
  }
164
- const identOption = identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
165
- let ssr;
166
- if (typeof ssrParam === 'boolean') {
167
- ssr = ssrParam;
168
- } else {
169
- ssr = ssrParam === null || ssrParam === void 0 ? void 0 : ssrParam.ssr;
170
- }
171
- if (ssr && !resolvedEmitCssInSsr) {
105
+ const identOption = getIdentOption();
106
+ if (mode === 'transform') {
172
107
  return integration.transform({
173
108
  source: code,
174
- filePath: vite.normalizePath(validId),
109
+ filePath: integration.normalizePath(validId),
175
110
  rootPath: config.root,
176
111
  packageName,
177
112
  identOption
178
113
  });
179
114
  }
180
- const {
181
- source,
182
- watchFiles
183
- } = await integration.compile({
184
- filePath: validId,
185
- cwd: config.root,
186
- esbuildOptions,
187
- identOption
188
- });
189
- for (const file of watchFiles) {
190
- // In start mode, we need to prevent the file from rewatching itself.
191
- // If it's a `build --watch`, it needs to watch everything.
192
- if (config.command === 'build' || file !== validId) {
193
- this.addWatchFile(file);
194
- }
195
- }
196
- const output = await integration.processVanillaFile({
197
- source,
198
- filePath: validId,
199
- identOption,
200
- serializeVirtualCssPath: async ({
201
- fileScope,
202
- source
203
- }) => {
204
- const rootRelativeId = `${fileScope.filePath}${config.command === 'build' || ssr && resolvedEmitCssInSsr ? virtualExtCss : virtualExtJs}`;
205
- const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
206
- let cssSource = source;
207
- if (postCssConfig) {
208
- const postCssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); })).default(postCssConfig.plugins).process(source, {
209
- ...postCssConfig.options,
210
- from: undefined,
211
- map: false
212
- });
213
- cssSource = postCssResult.css;
214
- }
215
- if (server && cssMap.has(absoluteId) && cssMap.get(absoluteId) !== source) {
216
- const {
217
- moduleGraph
218
- } = server;
219
- const modules = Array.from(moduleGraph.getModulesByFile(absoluteId) || []);
220
- for (const module of modules) {
221
- if (module) {
222
- moduleGraph.invalidateModule(module);
115
+ if (compiler) {
116
+ const absoluteId = getAbsoluteId(validId);
117
+ const {
118
+ source,
119
+ watchFiles
120
+ } = await compiler.processVanillaFile(absoluteId, {
121
+ outputCss: true
122
+ });
123
+ addWatchFiles.call(this, absoluteId, watchFiles);
223
124
 
224
- // Vite uses this timestamp to add `?t=` query string automatically for HMR.
225
- module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
226
- }
227
- }
228
- server.ws.send({
229
- type: 'custom',
230
- event: styleUpdateEvent(absoluteId),
231
- data: cssSource
232
- });
125
+ // We have to invalidate the virtual module, not the real one we just transformed
126
+ invalidateModule(fileIdToVirtualId(absoluteId));
127
+ return {
128
+ code: source,
129
+ map: {
130
+ mappings: ''
233
131
  }
234
- cssMap.set(absoluteId, cssSource);
235
-
236
- // We use the root relative id here to ensure file contents (content-hashes)
237
- // are consistent across build machines
238
- return `import "${rootRelativeId}";`;
239
- }
240
- });
241
- return {
242
- code: output,
243
- map: {
244
- mappings: ''
245
- }
246
- };
132
+ };
133
+ }
134
+ },
135
+ resolveId(source) {
136
+ var _compiler2;
137
+ const [validId, query] = source.split('?');
138
+ if (!isVirtualId(validId)) return;
139
+ const absoluteId = getAbsoluteId(validId);
140
+ if ( // We should always have CSS for a file here.
141
+ // The only valid scenario for a missing one is if someone had written
142
+ // a file in their app using the .vanilla.js/.vanilla.css extension
143
+ (_compiler2 = compiler) !== null && _compiler2 !== void 0 && _compiler2.getCssForFile(virtualIdToFileId(absoluteId))) {
144
+ // Keep the original query string for HMR.
145
+ return absoluteId + (query ? `?${query}` : '');
146
+ }
147
+ },
148
+ load(id) {
149
+ const [validId] = id.split('?');
150
+ if (!isVirtualId(validId) || !compiler) return;
151
+ const absoluteId = getAbsoluteId(validId);
152
+ const {
153
+ css
154
+ } = compiler.getCssForFile(virtualIdToFileId(absoluteId));
155
+ return css;
247
156
  }
248
157
  };
249
158
  }
@@ -3,95 +3,72 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var path = require('path');
6
- var vite = require('vite');
7
- var outdent = require('outdent');
8
6
  var integration = require('@vanilla-extract/integration');
9
7
 
10
8
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
9
 
12
- function _interopNamespace(e) {
13
- if (e && e.__esModule) return e;
14
- var n = Object.create(null);
15
- if (e) {
16
- Object.keys(e).forEach(function (k) {
17
- if (k !== 'default') {
18
- var d = Object.getOwnPropertyDescriptor(e, k);
19
- Object.defineProperty(n, k, d.get ? d : {
20
- enumerable: true,
21
- get: function () { return e[k]; }
22
- });
23
- }
24
- });
25
- }
26
- n["default"] = e;
27
- return Object.freeze(n);
28
- }
29
-
30
10
  var path__default = /*#__PURE__*/_interopDefault(path);
31
- var outdent__default = /*#__PURE__*/_interopDefault(outdent);
32
11
 
33
- // Mostly copied from vite's implementation
34
- // https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
35
- const resolvePostcssConfig = async config => {
36
- var _config$css;
37
- // inline postcss config via vite config
38
- const inlineOptions = (_config$css = config.css) === null || _config$css === void 0 ? void 0 : _config$css.postcss;
39
- const inlineOptionsIsString = typeof inlineOptions === 'string';
40
- if (inlineOptions && !inlineOptionsIsString) {
41
- const options = {
42
- ...inlineOptions
43
- };
44
- delete options.plugins;
45
- return {
46
- options,
47
- plugins: inlineOptions.plugins || []
48
- };
49
- } else {
50
- try {
51
- const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
52
- const postCssConfig = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss-load-config')); })).default({}, searchPath);
53
- return {
54
- options: postCssConfig.options,
55
- // @ts-expect-error - The postcssrc options don't agree with real postcss, but it should be ok
56
- plugins: postCssConfig.plugins
57
- };
58
- } catch (e) {
59
- if (!/No PostCSS Config found/.test(e.message)) {
60
- throw e;
61
- }
62
- return null;
63
- }
64
- }
65
- };
66
-
67
- const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
68
12
  const virtualExtCss = '.vanilla.css';
69
- const virtualExtJs = '.vanilla.js';
13
+ const isVirtualId = id => id.endsWith(virtualExtCss);
14
+ const fileIdToVirtualId = id => `${id}${virtualExtCss}`;
15
+ const virtualIdToFileId = virtualId => virtualId.slice(0, -virtualExtCss.length);
70
16
  function vanillaExtractPlugin({
71
17
  identifiers,
72
- emitCssInSsr,
73
- esbuildOptions
18
+ unstable_mode: mode = 'emitCss'
74
19
  } = {}) {
75
20
  let config;
21
+ let userConfig;
76
22
  let server;
77
- let postCssConfig;
78
- const cssMap = new Map();
79
- const hasEmitCssOverride = typeof emitCssInSsr === 'boolean';
80
- let resolvedEmitCssInSsr = hasEmitCssOverride ? emitCssInSsr : !!process.env.VITE_RSC_BUILD;
81
23
  let packageName;
82
- const getAbsoluteVirtualFileId = source => vite.normalizePath(path__default["default"].join(config.root, source));
24
+ let compiler;
25
+ const getIdentOption = () => identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
26
+ const getAbsoluteId = filePath => {
27
+ let resolvedId = filePath;
28
+ if (filePath.startsWith(config.root) ||
29
+ // In monorepos the absolute path will be outside of config.root, so we check that they have the same root on the file system
30
+ path__default["default"].isAbsolute(filePath) && filePath.split(path__default["default"].sep)[1] === config.root.split(path__default["default"].sep)[1]) {
31
+ resolvedId = filePath;
32
+ } else {
33
+ // In SSR mode we can have paths like /app/styles.css.ts
34
+ resolvedId = path__default["default"].join(config.root, filePath);
35
+ }
36
+ return integration.normalizePath(resolvedId);
37
+ };
38
+ function invalidateModule(absoluteId) {
39
+ if (!server) return;
40
+ const {
41
+ moduleGraph
42
+ } = server;
43
+ const modules = moduleGraph.getModulesByFile(absoluteId);
44
+ if (modules) {
45
+ for (const module of modules) {
46
+ moduleGraph.invalidateModule(module);
47
+
48
+ // Vite uses this timestamp to add `?t=` query string automatically for HMR.
49
+ module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
50
+ }
51
+ }
52
+ }
53
+ function addWatchFiles(fromId, files) {
54
+ // We don't need to watch files in build mode
55
+ if (config.command === 'build' && !config.build.watch) {
56
+ return;
57
+ }
58
+ for (const file of files) {
59
+ if (!file.includes('node_modules') && integration.normalizePath(file) !== fromId) {
60
+ this.addWatchFile(file);
61
+ }
62
+ }
63
+ }
83
64
  return {
84
65
  name: 'vanilla-extract',
85
- enforce: 'pre',
86
66
  configureServer(_server) {
87
67
  server = _server;
88
68
  },
89
- config(_userConfig, env) {
90
- const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
69
+ config(viteUserConfig) {
70
+ userConfig = viteUserConfig;
91
71
  return {
92
- optimizeDeps: {
93
- include
94
- },
95
72
  ssr: {
96
73
  external: ['@vanilla-extract/css', '@vanilla-extract/css/fileScope', '@vanilla-extract/css/adapter']
97
74
  }
@@ -100,150 +77,82 @@ function vanillaExtractPlugin({
100
77
  async configResolved(resolvedConfig) {
101
78
  config = resolvedConfig;
102
79
  packageName = integration.getPackageInfo(config.root).name;
103
- if (config.command === 'serve') {
104
- postCssConfig = await resolvePostcssConfig(config);
105
- }
106
- if (!hasEmitCssOverride && config.plugins.some(plugin => ['astro:build', 'solid-start-server', 'vite-plugin-qwik', 'vite-plugin-svelte'].includes(plugin.name))) {
107
- resolvedEmitCssInSsr = true;
108
- }
109
- },
110
- resolveId(source) {
111
- const [validId, query] = source.split('?');
112
- if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
113
- return;
114
- }
115
-
116
- // Absolute paths seem to occur often in monorepos, where files are
117
- // imported from outside the config root.
118
- const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
119
-
120
- // There should always be an entry in the `cssMap` here.
121
- // The only valid scenario for a missing one is if someone had written
122
- // a file in their app using the .vanilla.js/.vanilla.css extension
123
- if (cssMap.has(absoluteId)) {
124
- // Keep the original query string for HMR.
125
- return absoluteId + (query ? `?${query}` : '');
80
+ if (mode !== 'transform') {
81
+ var _userConfig$plugins;
82
+ compiler = integration.createCompiler({
83
+ root: config.root,
84
+ identifiers: getIdentOption(),
85
+ cssImportSpecifier: fileIdToVirtualId,
86
+ viteResolve: config.resolve,
87
+ vitePlugins: (_userConfig$plugins = userConfig.plugins) === null || _userConfig$plugins === void 0 ? void 0 : _userConfig$plugins.flat().filter(plugin => typeof plugin === 'object' && plugin !== null && 'name' in plugin &&
88
+ // Prevent an infinite loop where the compiler creates a new instance of the plugin,
89
+ // which creates a new compiler, which creates a new instance of the plugin, etc.
90
+ plugin.name !== 'vanilla-extract' &&
91
+ // Skip Vitest plugins
92
+ plugin.name !== 'vitest' && !plugin.name.startsWith('vitest:'))
93
+ });
126
94
  }
127
95
  },
128
- load(id) {
129
- const [validId] = id.split('?');
130
- if (!cssMap.has(validId)) {
131
- return;
132
- }
133
- const css = cssMap.get(validId);
134
- if (typeof css !== 'string') {
135
- return;
136
- }
137
- if (validId.endsWith(virtualExtCss)) {
138
- return css;
139
- }
140
- return outdent__default["default"]`
141
- import { injectStyles } from '@vanilla-extract/css/injectStyles';
142
-
143
- const inject = (css) => injectStyles({
144
- fileScope: ${JSON.stringify({
145
- filePath: validId
146
- })},
147
- css
148
- });
149
-
150
- inject(${JSON.stringify(css)});
151
-
152
- if (import.meta.hot) {
153
- import.meta.hot.on('${styleUpdateEvent(validId)}', (css) => {
154
- inject(css);
155
- });
156
- }
157
- `;
96
+ buildEnd() {
97
+ var _compiler;
98
+ (_compiler = compiler) === null || _compiler === void 0 ? void 0 : _compiler.close();
158
99
  },
159
- async transform(code, id, ssrParam) {
100
+ async transform(code, id) {
160
101
  const [validId] = id.split('?');
161
102
  if (!integration.cssFileFilter.test(validId)) {
162
103
  return null;
163
104
  }
164
- const identOption = identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
165
- let ssr;
166
- if (typeof ssrParam === 'boolean') {
167
- ssr = ssrParam;
168
- } else {
169
- ssr = ssrParam === null || ssrParam === void 0 ? void 0 : ssrParam.ssr;
170
- }
171
- if (ssr && !resolvedEmitCssInSsr) {
105
+ const identOption = getIdentOption();
106
+ if (mode === 'transform') {
172
107
  return integration.transform({
173
108
  source: code,
174
- filePath: vite.normalizePath(validId),
109
+ filePath: integration.normalizePath(validId),
175
110
  rootPath: config.root,
176
111
  packageName,
177
112
  identOption
178
113
  });
179
114
  }
180
- const {
181
- source,
182
- watchFiles
183
- } = await integration.compile({
184
- filePath: validId,
185
- cwd: config.root,
186
- esbuildOptions,
187
- identOption
188
- });
189
- for (const file of watchFiles) {
190
- // In start mode, we need to prevent the file from rewatching itself.
191
- // If it's a `build --watch`, it needs to watch everything.
192
- if (config.command === 'build' || file !== validId) {
193
- this.addWatchFile(file);
194
- }
195
- }
196
- const output = await integration.processVanillaFile({
197
- source,
198
- filePath: validId,
199
- identOption,
200
- serializeVirtualCssPath: async ({
201
- fileScope,
202
- source
203
- }) => {
204
- const rootRelativeId = `${fileScope.filePath}${config.command === 'build' || ssr && resolvedEmitCssInSsr ? virtualExtCss : virtualExtJs}`;
205
- const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
206
- let cssSource = source;
207
- if (postCssConfig) {
208
- const postCssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); })).default(postCssConfig.plugins).process(source, {
209
- ...postCssConfig.options,
210
- from: undefined,
211
- map: false
212
- });
213
- cssSource = postCssResult.css;
214
- }
215
- if (server && cssMap.has(absoluteId) && cssMap.get(absoluteId) !== source) {
216
- const {
217
- moduleGraph
218
- } = server;
219
- const modules = Array.from(moduleGraph.getModulesByFile(absoluteId) || []);
220
- for (const module of modules) {
221
- if (module) {
222
- moduleGraph.invalidateModule(module);
115
+ if (compiler) {
116
+ const absoluteId = getAbsoluteId(validId);
117
+ const {
118
+ source,
119
+ watchFiles
120
+ } = await compiler.processVanillaFile(absoluteId, {
121
+ outputCss: true
122
+ });
123
+ addWatchFiles.call(this, absoluteId, watchFiles);
223
124
 
224
- // Vite uses this timestamp to add `?t=` query string automatically for HMR.
225
- module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
226
- }
227
- }
228
- server.ws.send({
229
- type: 'custom',
230
- event: styleUpdateEvent(absoluteId),
231
- data: cssSource
232
- });
125
+ // We have to invalidate the virtual module, not the real one we just transformed
126
+ invalidateModule(fileIdToVirtualId(absoluteId));
127
+ return {
128
+ code: source,
129
+ map: {
130
+ mappings: ''
233
131
  }
234
- cssMap.set(absoluteId, cssSource);
235
-
236
- // We use the root relative id here to ensure file contents (content-hashes)
237
- // are consistent across build machines
238
- return `import "${rootRelativeId}";`;
239
- }
240
- });
241
- return {
242
- code: output,
243
- map: {
244
- mappings: ''
245
- }
246
- };
132
+ };
133
+ }
134
+ },
135
+ resolveId(source) {
136
+ var _compiler2;
137
+ const [validId, query] = source.split('?');
138
+ if (!isVirtualId(validId)) return;
139
+ const absoluteId = getAbsoluteId(validId);
140
+ if ( // We should always have CSS for a file here.
141
+ // The only valid scenario for a missing one is if someone had written
142
+ // a file in their app using the .vanilla.js/.vanilla.css extension
143
+ (_compiler2 = compiler) !== null && _compiler2 !== void 0 && _compiler2.getCssForFile(virtualIdToFileId(absoluteId))) {
144
+ // Keep the original query string for HMR.
145
+ return absoluteId + (query ? `?${query}` : '');
146
+ }
147
+ },
148
+ load(id) {
149
+ const [validId] = id.split('?');
150
+ if (!isVirtualId(validId) || !compiler) return;
151
+ const absoluteId = getAbsoluteId(validId);
152
+ const {
153
+ css
154
+ } = compiler.getCssForFile(virtualIdToFileId(absoluteId));
155
+ return css;
247
156
  }
248
157
  };
249
158
  }
@@ -1,70 +1,66 @@
1
1
  import path from 'path';
2
- import { normalizePath } from 'vite';
3
- import outdent from 'outdent';
4
- import { getPackageInfo, cssFileFilter, transform, compile, processVanillaFile } from '@vanilla-extract/integration';
2
+ import { getPackageInfo, createCompiler, cssFileFilter, transform, normalizePath } from '@vanilla-extract/integration';
5
3
 
6
- // Mostly copied from vite's implementation
7
- // https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
8
- const resolvePostcssConfig = async config => {
9
- var _config$css;
10
- // inline postcss config via vite config
11
- const inlineOptions = (_config$css = config.css) === null || _config$css === void 0 ? void 0 : _config$css.postcss;
12
- const inlineOptionsIsString = typeof inlineOptions === 'string';
13
- if (inlineOptions && !inlineOptionsIsString) {
14
- const options = {
15
- ...inlineOptions
16
- };
17
- delete options.plugins;
18
- return {
19
- options,
20
- plugins: inlineOptions.plugins || []
21
- };
22
- } else {
23
- try {
24
- const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
25
- const postCssConfig = await (await import('postcss-load-config')).default({}, searchPath);
26
- return {
27
- options: postCssConfig.options,
28
- // @ts-expect-error - The postcssrc options don't agree with real postcss, but it should be ok
29
- plugins: postCssConfig.plugins
30
- };
31
- } catch (e) {
32
- if (!/No PostCSS Config found/.test(e.message)) {
33
- throw e;
34
- }
35
- return null;
36
- }
37
- }
38
- };
39
-
40
- const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
41
4
  const virtualExtCss = '.vanilla.css';
42
- const virtualExtJs = '.vanilla.js';
5
+ const isVirtualId = id => id.endsWith(virtualExtCss);
6
+ const fileIdToVirtualId = id => `${id}${virtualExtCss}`;
7
+ const virtualIdToFileId = virtualId => virtualId.slice(0, -virtualExtCss.length);
43
8
  function vanillaExtractPlugin({
44
9
  identifiers,
45
- emitCssInSsr,
46
- esbuildOptions
10
+ unstable_mode: mode = 'emitCss'
47
11
  } = {}) {
48
12
  let config;
13
+ let userConfig;
49
14
  let server;
50
- let postCssConfig;
51
- const cssMap = new Map();
52
- const hasEmitCssOverride = typeof emitCssInSsr === 'boolean';
53
- let resolvedEmitCssInSsr = hasEmitCssOverride ? emitCssInSsr : !!process.env.VITE_RSC_BUILD;
54
15
  let packageName;
55
- const getAbsoluteVirtualFileId = source => normalizePath(path.join(config.root, source));
16
+ let compiler;
17
+ const getIdentOption = () => identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
18
+ const getAbsoluteId = filePath => {
19
+ let resolvedId = filePath;
20
+ if (filePath.startsWith(config.root) ||
21
+ // In monorepos the absolute path will be outside of config.root, so we check that they have the same root on the file system
22
+ path.isAbsolute(filePath) && filePath.split(path.sep)[1] === config.root.split(path.sep)[1]) {
23
+ resolvedId = filePath;
24
+ } else {
25
+ // In SSR mode we can have paths like /app/styles.css.ts
26
+ resolvedId = path.join(config.root, filePath);
27
+ }
28
+ return normalizePath(resolvedId);
29
+ };
30
+ function invalidateModule(absoluteId) {
31
+ if (!server) return;
32
+ const {
33
+ moduleGraph
34
+ } = server;
35
+ const modules = moduleGraph.getModulesByFile(absoluteId);
36
+ if (modules) {
37
+ for (const module of modules) {
38
+ moduleGraph.invalidateModule(module);
39
+
40
+ // Vite uses this timestamp to add `?t=` query string automatically for HMR.
41
+ module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
42
+ }
43
+ }
44
+ }
45
+ function addWatchFiles(fromId, files) {
46
+ // We don't need to watch files in build mode
47
+ if (config.command === 'build' && !config.build.watch) {
48
+ return;
49
+ }
50
+ for (const file of files) {
51
+ if (!file.includes('node_modules') && normalizePath(file) !== fromId) {
52
+ this.addWatchFile(file);
53
+ }
54
+ }
55
+ }
56
56
  return {
57
57
  name: 'vanilla-extract',
58
- enforce: 'pre',
59
58
  configureServer(_server) {
60
59
  server = _server;
61
60
  },
62
- config(_userConfig, env) {
63
- const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
61
+ config(viteUserConfig) {
62
+ userConfig = viteUserConfig;
64
63
  return {
65
- optimizeDeps: {
66
- include
67
- },
68
64
  ssr: {
69
65
  external: ['@vanilla-extract/css', '@vanilla-extract/css/fileScope', '@vanilla-extract/css/adapter']
70
66
  }
@@ -73,75 +69,33 @@ function vanillaExtractPlugin({
73
69
  async configResolved(resolvedConfig) {
74
70
  config = resolvedConfig;
75
71
  packageName = getPackageInfo(config.root).name;
76
- if (config.command === 'serve') {
77
- postCssConfig = await resolvePostcssConfig(config);
78
- }
79
- if (!hasEmitCssOverride && config.plugins.some(plugin => ['astro:build', 'solid-start-server', 'vite-plugin-qwik', 'vite-plugin-svelte'].includes(plugin.name))) {
80
- resolvedEmitCssInSsr = true;
72
+ if (mode !== 'transform') {
73
+ var _userConfig$plugins;
74
+ compiler = createCompiler({
75
+ root: config.root,
76
+ identifiers: getIdentOption(),
77
+ cssImportSpecifier: fileIdToVirtualId,
78
+ viteResolve: config.resolve,
79
+ vitePlugins: (_userConfig$plugins = userConfig.plugins) === null || _userConfig$plugins === void 0 ? void 0 : _userConfig$plugins.flat().filter(plugin => typeof plugin === 'object' && plugin !== null && 'name' in plugin &&
80
+ // Prevent an infinite loop where the compiler creates a new instance of the plugin,
81
+ // which creates a new compiler, which creates a new instance of the plugin, etc.
82
+ plugin.name !== 'vanilla-extract' &&
83
+ // Skip Vitest plugins
84
+ plugin.name !== 'vitest' && !plugin.name.startsWith('vitest:'))
85
+ });
81
86
  }
82
87
  },
83
- resolveId(source) {
84
- const [validId, query] = source.split('?');
85
- if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
86
- return;
87
- }
88
-
89
- // Absolute paths seem to occur often in monorepos, where files are
90
- // imported from outside the config root.
91
- const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
92
-
93
- // There should always be an entry in the `cssMap` here.
94
- // The only valid scenario for a missing one is if someone had written
95
- // a file in their app using the .vanilla.js/.vanilla.css extension
96
- if (cssMap.has(absoluteId)) {
97
- // Keep the original query string for HMR.
98
- return absoluteId + (query ? `?${query}` : '');
99
- }
88
+ buildEnd() {
89
+ var _compiler;
90
+ (_compiler = compiler) === null || _compiler === void 0 ? void 0 : _compiler.close();
100
91
  },
101
- load(id) {
102
- const [validId] = id.split('?');
103
- if (!cssMap.has(validId)) {
104
- return;
105
- }
106
- const css = cssMap.get(validId);
107
- if (typeof css !== 'string') {
108
- return;
109
- }
110
- if (validId.endsWith(virtualExtCss)) {
111
- return css;
112
- }
113
- return outdent`
114
- import { injectStyles } from '@vanilla-extract/css/injectStyles';
115
-
116
- const inject = (css) => injectStyles({
117
- fileScope: ${JSON.stringify({
118
- filePath: validId
119
- })},
120
- css
121
- });
122
-
123
- inject(${JSON.stringify(css)});
124
-
125
- if (import.meta.hot) {
126
- import.meta.hot.on('${styleUpdateEvent(validId)}', (css) => {
127
- inject(css);
128
- });
129
- }
130
- `;
131
- },
132
- async transform(code, id, ssrParam) {
92
+ async transform(code, id) {
133
93
  const [validId] = id.split('?');
134
94
  if (!cssFileFilter.test(validId)) {
135
95
  return null;
136
96
  }
137
- const identOption = identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
138
- let ssr;
139
- if (typeof ssrParam === 'boolean') {
140
- ssr = ssrParam;
141
- } else {
142
- ssr = ssrParam === null || ssrParam === void 0 ? void 0 : ssrParam.ssr;
143
- }
144
- if (ssr && !resolvedEmitCssInSsr) {
97
+ const identOption = getIdentOption();
98
+ if (mode === 'transform') {
145
99
  return transform({
146
100
  source: code,
147
101
  filePath: normalizePath(validId),
@@ -150,73 +104,47 @@ function vanillaExtractPlugin({
150
104
  identOption
151
105
  });
152
106
  }
153
- const {
154
- source,
155
- watchFiles
156
- } = await compile({
157
- filePath: validId,
158
- cwd: config.root,
159
- esbuildOptions,
160
- identOption
161
- });
162
- for (const file of watchFiles) {
163
- // In start mode, we need to prevent the file from rewatching itself.
164
- // If it's a `build --watch`, it needs to watch everything.
165
- if (config.command === 'build' || file !== validId) {
166
- this.addWatchFile(file);
167
- }
168
- }
169
- const output = await processVanillaFile({
170
- source,
171
- filePath: validId,
172
- identOption,
173
- serializeVirtualCssPath: async ({
174
- fileScope,
175
- source
176
- }) => {
177
- const rootRelativeId = `${fileScope.filePath}${config.command === 'build' || ssr && resolvedEmitCssInSsr ? virtualExtCss : virtualExtJs}`;
178
- const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
179
- let cssSource = source;
180
- if (postCssConfig) {
181
- const postCssResult = await (await import('postcss')).default(postCssConfig.plugins).process(source, {
182
- ...postCssConfig.options,
183
- from: undefined,
184
- map: false
185
- });
186
- cssSource = postCssResult.css;
187
- }
188
- if (server && cssMap.has(absoluteId) && cssMap.get(absoluteId) !== source) {
189
- const {
190
- moduleGraph
191
- } = server;
192
- const modules = Array.from(moduleGraph.getModulesByFile(absoluteId) || []);
193
- for (const module of modules) {
194
- if (module) {
195
- moduleGraph.invalidateModule(module);
107
+ if (compiler) {
108
+ const absoluteId = getAbsoluteId(validId);
109
+ const {
110
+ source,
111
+ watchFiles
112
+ } = await compiler.processVanillaFile(absoluteId, {
113
+ outputCss: true
114
+ });
115
+ addWatchFiles.call(this, absoluteId, watchFiles);
196
116
 
197
- // Vite uses this timestamp to add `?t=` query string automatically for HMR.
198
- module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
199
- }
200
- }
201
- server.ws.send({
202
- type: 'custom',
203
- event: styleUpdateEvent(absoluteId),
204
- data: cssSource
205
- });
117
+ // We have to invalidate the virtual module, not the real one we just transformed
118
+ invalidateModule(fileIdToVirtualId(absoluteId));
119
+ return {
120
+ code: source,
121
+ map: {
122
+ mappings: ''
206
123
  }
207
- cssMap.set(absoluteId, cssSource);
208
-
209
- // We use the root relative id here to ensure file contents (content-hashes)
210
- // are consistent across build machines
211
- return `import "${rootRelativeId}";`;
212
- }
213
- });
214
- return {
215
- code: output,
216
- map: {
217
- mappings: ''
218
- }
219
- };
124
+ };
125
+ }
126
+ },
127
+ resolveId(source) {
128
+ var _compiler2;
129
+ const [validId, query] = source.split('?');
130
+ if (!isVirtualId(validId)) return;
131
+ const absoluteId = getAbsoluteId(validId);
132
+ if ( // We should always have CSS for a file here.
133
+ // The only valid scenario for a missing one is if someone had written
134
+ // a file in their app using the .vanilla.js/.vanilla.css extension
135
+ (_compiler2 = compiler) !== null && _compiler2 !== void 0 && _compiler2.getCssForFile(virtualIdToFileId(absoluteId))) {
136
+ // Keep the original query string for HMR.
137
+ return absoluteId + (query ? `?${query}` : '');
138
+ }
139
+ },
140
+ load(id) {
141
+ const [validId] = id.split('?');
142
+ if (!isVirtualId(validId) || !compiler) return;
143
+ const absoluteId = getAbsoluteId(validId);
144
+ const {
145
+ css
146
+ } = compiler.getCssForFile(virtualIdToFileId(absoluteId));
147
+ return css;
220
148
  }
221
149
  };
222
150
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vanilla-extract/vite-plugin",
3
- "version": "0.0.0-inline-prototype-2023326232811",
3
+ "version": "0.0.0-master-20240201234045",
4
4
  "description": "Zero-runtime Stylesheets-in-TypeScript",
5
5
  "main": "dist/vanilla-extract-vite-plugin.cjs.js",
6
6
  "module": "dist/vanilla-extract-vite-plugin.esm.js",
@@ -15,15 +15,12 @@
15
15
  "author": "SEEK",
16
16
  "license": "MIT",
17
17
  "dependencies": {
18
- "@vanilla-extract/integration": "^0.0.0-inline-prototype-2023326232811",
19
- "outdent": "^0.8.0",
20
- "postcss": "^8.3.6",
21
- "postcss-load-config": "^3.1.0"
18
+ "@vanilla-extract/integration": "0.0.0-master-20240201234045"
22
19
  },
23
20
  "devDependencies": {
24
- "vite": "npm:vite@^2.7.0"
21
+ "vite": "npm:vite@^5.0.11"
25
22
  },
26
23
  "peerDependencies": {
27
- "vite": "^2.2.3 || ^3.0.0 || ^4.0.3"
24
+ "vite": "^4.0.3 || ^5.0.0"
28
25
  }
29
26
  }