Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@vanilla-extract/vite-plugin

Package Overview
Dependencies
Maintainers
4
Versions
131
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vanilla-extract/vite-plugin - npm Package Compare versions

Comparing version 0.0.0-babel-modern-20231227140935 to 0.0.0-const-regexes-20240813051516

7

dist/vanilla-extract-vite-plugin.cjs.d.ts
import { Plugin } from 'vite';
import { IdentifierOption, CompileOptions } from '@vanilla-extract/integration';
import { IdentifierOption } from '@vanilla-extract/integration';
interface Options {
identifiers?: IdentifierOption;
emitCssInSsr?: boolean;
esbuildOptions?: CompileOptions['esbuildOptions'];
unstable_mode?: 'transform' | 'emitCss';
}
declare function vanillaExtractPlugin({ identifiers, emitCssInSsr, esbuildOptions, }?: Options): Plugin;
declare function vanillaExtractPlugin({ identifiers, unstable_mode: mode, }?: Options): Plugin;
export { vanillaExtractPlugin };

@@ -6,3 +6,2 @@ 'use strict';

var path = require('path');
var outdent = require('outdent');
var integration = require('@vanilla-extract/integration');

@@ -13,66 +12,66 @@

var path__default = /*#__PURE__*/_interopDefault(path);
var outdent__default = /*#__PURE__*/_interopDefault(outdent);
// Mostly copied from vite's implementation
// https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
const resolvePostcssConfig = async config => {
// inline postcss config via vite config
const inlineOptions = config.css?.postcss;
const inlineOptionsIsString = typeof inlineOptions === 'string';
if (inlineOptions && !inlineOptionsIsString) {
const options = {
...inlineOptions
};
delete options.plugins;
return {
options,
plugins: inlineOptions.plugins || []
};
} else {
try {
const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
const postCssConfig = await (await import('postcss-load-config')).default({}, searchPath);
return {
options: postCssConfig.options,
plugins: postCssConfig.plugins
};
} catch (e) {
if (!/No PostCSS Config found/.test(e.message)) {
throw e;
}
return null;
}
}
};
const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
const virtualExtCss = '.vanilla.css';
const virtualExtJs = '.vanilla.js';
const isVirtualId = id => id.endsWith(virtualExtCss);
const fileIdToVirtualId = id => `${id}${virtualExtCss}`;
const virtualIdToFileId = virtualId => virtualId.slice(0, -virtualExtCss.length);
const removeIncompatiblePlugins = plugin => typeof plugin === 'object' && plugin !== null && 'name' in plugin &&
// Prevent an infinite loop where the compiler creates a new instance of the plugin,
// which creates a new compiler, which creates a new instance of the plugin, etc.
plugin.name !== 'vanilla-extract' &&
// Skip Remix because it throws an error if it's not loaded with a config file.
// If it _is_ loaded with a config file, it will create an infinite loop because it
// also has a child compiler which uses the same mechanism to load the config file.
// https://github.com/remix-run/remix/pull/7990#issuecomment-1809356626
// Additionally, some internal Remix plugins rely on a `ctx` object to be initialized by
// the main Remix plugin, and may not function correctly without it. To address this, we
// filter out all Remix-related plugins.
!plugin.name.startsWith('remix');
function vanillaExtractPlugin({
identifiers,
emitCssInSsr,
esbuildOptions
unstable_mode: mode = 'emitCss'
} = {}) {
let config;
let configEnv;
let server;
let postCssConfig;
// We lazily load this utility from Vite
let normalizePath;
const cssMap = new Map();
const hasEmitCssOverride = typeof emitCssInSsr === 'boolean';
let resolvedEmitCssInSsr = hasEmitCssOverride ? emitCssInSsr : !!process.env.VITE_RSC_BUILD;
let packageName;
const getAbsoluteVirtualFileId = source => normalizePath(path__default["default"].join(config.root, source));
let compiler;
const vitePromise = import('vite');
const getIdentOption = () => identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
const getAbsoluteId = filePath => {
let resolvedId = filePath;
if (filePath.startsWith(config.root) ||
// In monorepos the absolute path will be outside of config.root, so we check that they have the same root on the file system
// Paths from vite are always normalized, so we have to use the posix path separator
path__default["default"].isAbsolute(filePath) && filePath.split(path__default["default"].posix.sep)[1] === config.root.split(path__default["default"].posix.sep)[1]) {
resolvedId = filePath;
} else {
// In SSR mode we can have paths like /app/styles.css.ts
resolvedId = path__default["default"].join(config.root, filePath);
}
return integration.normalizePath(resolvedId);
};
function invalidateModule(absoluteId) {
if (!server) return;
const {
moduleGraph
} = server;
const modules = moduleGraph.getModulesByFile(absoluteId);
if (modules) {
for (const module of modules) {
moduleGraph.invalidateModule(module);
// Vite uses this timestamp to add `?t=` query string automatically for HMR.
module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
}
}
}
return {
name: 'vanilla-extract',
enforce: 'pre',
configureServer(_server) {
server = _server;
},
config(_userConfig, env) {
const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
config(_userConfig, _configEnv) {
configEnv = _configEnv;
return {
optimizeDeps: {
include
},
ssr: {

@@ -83,63 +82,53 @@ external: ['@vanilla-extract/css', '@vanilla-extract/css/fileScope', '@vanilla-extract/css/adapter']

},
async configResolved(resolvedConfig) {
config = resolvedConfig;
async configResolved(_resolvedConfig) {
config = _resolvedConfig;
packageName = integration.getPackageInfo(config.root).name;
normalizePath = (await import('vite')).normalizePath;
if (config.command === 'serve') {
postCssConfig = await resolvePostcssConfig(config);
}
if (!hasEmitCssOverride && config.plugins.some(plugin => ['astro:build', 'remix', 'solid-start-server', 'vite-plugin-qwik', 'vite-plugin-svelte'].includes(plugin.name))) {
resolvedEmitCssInSsr = true;
}
},
resolveId(source) {
const [validId, query] = source.split('?');
if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
return;
}
async buildStart() {
// Ensure we re-use the compiler instance between builds, e.g. in watch mode
if (mode !== 'transform' && !compiler) {
var _configForViteCompile;
const {
loadConfigFromFile
} = await vitePromise;
let configForViteCompiler;
// Absolute paths seem to occur often in monorepos, where files are
// imported from outside the config root.
const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
// There should always be an entry in the `cssMap` here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
if (cssMap.has(absoluteId)) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
// The user has a vite config file
if (config.configFile) {
const configFile = await loadConfigFromFile({
command: config.command,
mode: config.mode,
isSsrBuild: configEnv.isSsrBuild
}, config.configFile);
configForViteCompiler = configFile === null || configFile === void 0 ? void 0 : configFile.config;
}
// The user is using a vite-based framework that has a custom config file
else {
configForViteCompiler = config.inlineConfig;
}
const viteConfig = {
...configForViteCompiler,
plugins: (_configForViteCompile = configForViteCompiler) === null || _configForViteCompile === void 0 || (_configForViteCompile = _configForViteCompile.plugins) === null || _configForViteCompile === void 0 ? void 0 : _configForViteCompile.flat().filter(removeIncompatiblePlugins)
};
compiler = integration.createCompiler({
root: config.root,
identifiers: getIdentOption(),
cssImportSpecifier: fileIdToVirtualId,
viteConfig
});
}
},
load(id) {
const [validId] = id.split('?');
if (!cssMap.has(validId)) {
return;
buildEnd() {
// When using the rollup watcher, we don't want to close the compiler after every build.
// Instead, we close it when the watcher is closed via the closeWatcher hook.
if (!config.build.watch) {
var _compiler;
(_compiler = compiler) === null || _compiler === void 0 || _compiler.close();
}
const css = cssMap.get(validId);
if (typeof css !== 'string') {
return;
}
if (validId.endsWith(virtualExtCss)) {
return css;
}
return outdent__default["default"]`
import { injectStyles } from '@vanilla-extract/css/injectStyles';
const inject = (css) => injectStyles({
fileScope: ${JSON.stringify({
filePath: validId
})},
css
});
inject(${JSON.stringify(css)});
if (import.meta.hot) {
import.meta.hot.on('${styleUpdateEvent(validId)}', (css) => {
inject(css);
});
}
`;
},
async transform(code, id, ssrParam) {
closeWatcher() {
var _compiler2;
return (_compiler2 = compiler) === null || _compiler2 === void 0 ? void 0 : _compiler2.close();
},
async transform(code, id) {
const [validId] = id.split('?');

@@ -149,13 +138,7 @@ if (!integration.cssFileFilter.test(validId)) {

}
const identOption = identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
let ssr;
if (typeof ssrParam === 'boolean') {
ssr = ssrParam;
} else {
ssr = ssrParam?.ssr;
}
if (ssr && !resolvedEmitCssInSsr) {
const identOption = getIdentOption();
if (mode === 'transform') {
return integration.transform({
source: code,
filePath: normalizePath(validId),
filePath: integration.normalizePath(validId),
rootPath: config.root,

@@ -166,69 +149,57 @@ packageName,

}
const {
source,
watchFiles
} = await integration.compile({
filePath: validId,
cwd: config.root,
esbuildOptions,
identOption
});
for (const file of watchFiles) {
// In start mode, we need to prevent the file from rewatching itself.
// If it's a `build --watch`, it needs to watch everything.
if (config.command === 'build' || normalizePath(file) !== validId) {
this.addWatchFile(file);
if (compiler) {
const absoluteId = getAbsoluteId(validId);
const {
source,
watchFiles
} = await compiler.processVanillaFile(absoluteId, {
outputCss: true
});
const result = {
code: source,
map: {
mappings: ''
}
};
// We don't need to watch files in build mode
if (config.command === 'build' && !config.build.watch) {
return result;
}
}
const output = await integration.processVanillaFile({
source,
filePath: validId,
identOption,
serializeVirtualCssPath: async ({
fileScope,
source
}) => {
const rootRelativeId = `${fileScope.filePath}${config.command === 'build' || ssr && resolvedEmitCssInSsr ? virtualExtCss : virtualExtJs}`;
const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
let cssSource = source;
if (postCssConfig) {
const postCssResult = await (await import('postcss')).default(postCssConfig.plugins).process(source, {
...postCssConfig.options,
from: undefined,
map: false
});
cssSource = postCssResult.css;
for (const file of watchFiles) {
if (!file.includes('node_modules') && integration.normalizePath(file) !== absoluteId) {
this.addWatchFile(file);
}
if (server && cssMap.has(absoluteId) && cssMap.get(absoluteId) !== cssSource) {
const {
moduleGraph
} = server;
const modules = Array.from(moduleGraph.getModulesByFile(absoluteId) || []);
for (const module of modules) {
if (module) {
moduleGraph.invalidateModule(module);
// Vite uses this timestamp to add `?t=` query string automatically for HMR.
module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
}
}
server.ws.send({
type: 'custom',
event: styleUpdateEvent(absoluteId),
data: cssSource
});
// We have to invalidate the virtual module & deps, not the real one we just transformed
// The deps have to be invalidated in case one of them changing was the trigger causing
// the current transformation
if (file.endsWith('.css.ts')) {
invalidateModule(fileIdToVirtualId(file));
}
cssMap.set(absoluteId, cssSource);
// We use the root relative id here to ensure file contents (content-hashes)
// are consistent across build machines
return `import "${rootRelativeId}";`;
}
});
return {
code: output,
map: {
mappings: ''
}
};
return result;
}
},
resolveId(source) {
var _compiler3;
const [validId, query] = source.split('?');
if (!isVirtualId(validId)) return;
const absoluteId = getAbsoluteId(validId);
if ( // We should always have CSS for a file here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
(_compiler3 = compiler) !== null && _compiler3 !== void 0 && _compiler3.getCssForFile(virtualIdToFileId(absoluteId))) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
}
},
load(id) {
const [validId] = id.split('?');
if (!isVirtualId(validId) || !compiler) return;
const absoluteId = getAbsoluteId(validId);
const {
css
} = compiler.getCssForFile(virtualIdToFileId(absoluteId));
return css;
}

@@ -235,0 +206,0 @@ };

@@ -6,3 +6,2 @@ 'use strict';

var path = require('path');
var outdent = require('outdent');
var integration = require('@vanilla-extract/integration');

@@ -13,66 +12,66 @@

var path__default = /*#__PURE__*/_interopDefault(path);
var outdent__default = /*#__PURE__*/_interopDefault(outdent);
// Mostly copied from vite's implementation
// https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
const resolvePostcssConfig = async config => {
// inline postcss config via vite config
const inlineOptions = config.css?.postcss;
const inlineOptionsIsString = typeof inlineOptions === 'string';
if (inlineOptions && !inlineOptionsIsString) {
const options = {
...inlineOptions
};
delete options.plugins;
return {
options,
plugins: inlineOptions.plugins || []
};
} else {
try {
const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
const postCssConfig = await (await import('postcss-load-config')).default({}, searchPath);
return {
options: postCssConfig.options,
plugins: postCssConfig.plugins
};
} catch (e) {
if (!/No PostCSS Config found/.test(e.message)) {
throw e;
}
return null;
}
}
};
const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
const virtualExtCss = '.vanilla.css';
const virtualExtJs = '.vanilla.js';
const isVirtualId = id => id.endsWith(virtualExtCss);
const fileIdToVirtualId = id => `${id}${virtualExtCss}`;
const virtualIdToFileId = virtualId => virtualId.slice(0, -virtualExtCss.length);
const removeIncompatiblePlugins = plugin => typeof plugin === 'object' && plugin !== null && 'name' in plugin &&
// Prevent an infinite loop where the compiler creates a new instance of the plugin,
// which creates a new compiler, which creates a new instance of the plugin, etc.
plugin.name !== 'vanilla-extract' &&
// Skip Remix because it throws an error if it's not loaded with a config file.
// If it _is_ loaded with a config file, it will create an infinite loop because it
// also has a child compiler which uses the same mechanism to load the config file.
// https://github.com/remix-run/remix/pull/7990#issuecomment-1809356626
// Additionally, some internal Remix plugins rely on a `ctx` object to be initialized by
// the main Remix plugin, and may not function correctly without it. To address this, we
// filter out all Remix-related plugins.
!plugin.name.startsWith('remix');
function vanillaExtractPlugin({
identifiers,
emitCssInSsr,
esbuildOptions
unstable_mode: mode = 'emitCss'
} = {}) {
let config;
let configEnv;
let server;
let postCssConfig;
// We lazily load this utility from Vite
let normalizePath;
const cssMap = new Map();
const hasEmitCssOverride = typeof emitCssInSsr === 'boolean';
let resolvedEmitCssInSsr = hasEmitCssOverride ? emitCssInSsr : !!process.env.VITE_RSC_BUILD;
let packageName;
const getAbsoluteVirtualFileId = source => normalizePath(path__default["default"].join(config.root, source));
let compiler;
const vitePromise = import('vite');
const getIdentOption = () => identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
const getAbsoluteId = filePath => {
let resolvedId = filePath;
if (filePath.startsWith(config.root) ||
// In monorepos the absolute path will be outside of config.root, so we check that they have the same root on the file system
// Paths from vite are always normalized, so we have to use the posix path separator
path__default["default"].isAbsolute(filePath) && filePath.split(path__default["default"].posix.sep)[1] === config.root.split(path__default["default"].posix.sep)[1]) {
resolvedId = filePath;
} else {
// In SSR mode we can have paths like /app/styles.css.ts
resolvedId = path__default["default"].join(config.root, filePath);
}
return integration.normalizePath(resolvedId);
};
function invalidateModule(absoluteId) {
if (!server) return;
const {
moduleGraph
} = server;
const modules = moduleGraph.getModulesByFile(absoluteId);
if (modules) {
for (const module of modules) {
moduleGraph.invalidateModule(module);
// Vite uses this timestamp to add `?t=` query string automatically for HMR.
module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
}
}
}
return {
name: 'vanilla-extract',
enforce: 'pre',
configureServer(_server) {
server = _server;
},
config(_userConfig, env) {
const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
config(_userConfig, _configEnv) {
configEnv = _configEnv;
return {
optimizeDeps: {
include
},
ssr: {

@@ -83,63 +82,53 @@ external: ['@vanilla-extract/css', '@vanilla-extract/css/fileScope', '@vanilla-extract/css/adapter']

},
async configResolved(resolvedConfig) {
config = resolvedConfig;
async configResolved(_resolvedConfig) {
config = _resolvedConfig;
packageName = integration.getPackageInfo(config.root).name;
normalizePath = (await import('vite')).normalizePath;
if (config.command === 'serve') {
postCssConfig = await resolvePostcssConfig(config);
}
if (!hasEmitCssOverride && config.plugins.some(plugin => ['astro:build', 'remix', 'solid-start-server', 'vite-plugin-qwik', 'vite-plugin-svelte'].includes(plugin.name))) {
resolvedEmitCssInSsr = true;
}
},
resolveId(source) {
const [validId, query] = source.split('?');
if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
return;
}
async buildStart() {
// Ensure we re-use the compiler instance between builds, e.g. in watch mode
if (mode !== 'transform' && !compiler) {
var _configForViteCompile;
const {
loadConfigFromFile
} = await vitePromise;
let configForViteCompiler;
// Absolute paths seem to occur often in monorepos, where files are
// imported from outside the config root.
const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
// There should always be an entry in the `cssMap` here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
if (cssMap.has(absoluteId)) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
// The user has a vite config file
if (config.configFile) {
const configFile = await loadConfigFromFile({
command: config.command,
mode: config.mode,
isSsrBuild: configEnv.isSsrBuild
}, config.configFile);
configForViteCompiler = configFile === null || configFile === void 0 ? void 0 : configFile.config;
}
// The user is using a vite-based framework that has a custom config file
else {
configForViteCompiler = config.inlineConfig;
}
const viteConfig = {
...configForViteCompiler,
plugins: (_configForViteCompile = configForViteCompiler) === null || _configForViteCompile === void 0 || (_configForViteCompile = _configForViteCompile.plugins) === null || _configForViteCompile === void 0 ? void 0 : _configForViteCompile.flat().filter(removeIncompatiblePlugins)
};
compiler = integration.createCompiler({
root: config.root,
identifiers: getIdentOption(),
cssImportSpecifier: fileIdToVirtualId,
viteConfig
});
}
},
load(id) {
const [validId] = id.split('?');
if (!cssMap.has(validId)) {
return;
buildEnd() {
// When using the rollup watcher, we don't want to close the compiler after every build.
// Instead, we close it when the watcher is closed via the closeWatcher hook.
if (!config.build.watch) {
var _compiler;
(_compiler = compiler) === null || _compiler === void 0 || _compiler.close();
}
const css = cssMap.get(validId);
if (typeof css !== 'string') {
return;
}
if (validId.endsWith(virtualExtCss)) {
return css;
}
return outdent__default["default"]`
import { injectStyles } from '@vanilla-extract/css/injectStyles';
const inject = (css) => injectStyles({
fileScope: ${JSON.stringify({
filePath: validId
})},
css
});
inject(${JSON.stringify(css)});
if (import.meta.hot) {
import.meta.hot.on('${styleUpdateEvent(validId)}', (css) => {
inject(css);
});
}
`;
},
async transform(code, id, ssrParam) {
closeWatcher() {
var _compiler2;
return (_compiler2 = compiler) === null || _compiler2 === void 0 ? void 0 : _compiler2.close();
},
async transform(code, id) {
const [validId] = id.split('?');

@@ -149,13 +138,7 @@ if (!integration.cssFileFilter.test(validId)) {

}
const identOption = identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
let ssr;
if (typeof ssrParam === 'boolean') {
ssr = ssrParam;
} else {
ssr = ssrParam?.ssr;
}
if (ssr && !resolvedEmitCssInSsr) {
const identOption = getIdentOption();
if (mode === 'transform') {
return integration.transform({
source: code,
filePath: normalizePath(validId),
filePath: integration.normalizePath(validId),
rootPath: config.root,

@@ -166,69 +149,57 @@ packageName,

}
const {
source,
watchFiles
} = await integration.compile({
filePath: validId,
cwd: config.root,
esbuildOptions,
identOption
});
for (const file of watchFiles) {
// In start mode, we need to prevent the file from rewatching itself.
// If it's a `build --watch`, it needs to watch everything.
if (config.command === 'build' || normalizePath(file) !== validId) {
this.addWatchFile(file);
if (compiler) {
const absoluteId = getAbsoluteId(validId);
const {
source,
watchFiles
} = await compiler.processVanillaFile(absoluteId, {
outputCss: true
});
const result = {
code: source,
map: {
mappings: ''
}
};
// We don't need to watch files in build mode
if (config.command === 'build' && !config.build.watch) {
return result;
}
}
const output = await integration.processVanillaFile({
source,
filePath: validId,
identOption,
serializeVirtualCssPath: async ({
fileScope,
source
}) => {
const rootRelativeId = `${fileScope.filePath}${config.command === 'build' || ssr && resolvedEmitCssInSsr ? virtualExtCss : virtualExtJs}`;
const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
let cssSource = source;
if (postCssConfig) {
const postCssResult = await (await import('postcss')).default(postCssConfig.plugins).process(source, {
...postCssConfig.options,
from: undefined,
map: false
});
cssSource = postCssResult.css;
for (const file of watchFiles) {
if (!file.includes('node_modules') && integration.normalizePath(file) !== absoluteId) {
this.addWatchFile(file);
}
if (server && cssMap.has(absoluteId) && cssMap.get(absoluteId) !== cssSource) {
const {
moduleGraph
} = server;
const modules = Array.from(moduleGraph.getModulesByFile(absoluteId) || []);
for (const module of modules) {
if (module) {
moduleGraph.invalidateModule(module);
// Vite uses this timestamp to add `?t=` query string automatically for HMR.
module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
}
}
server.ws.send({
type: 'custom',
event: styleUpdateEvent(absoluteId),
data: cssSource
});
// We have to invalidate the virtual module & deps, not the real one we just transformed
// The deps have to be invalidated in case one of them changing was the trigger causing
// the current transformation
if (file.endsWith('.css.ts')) {
invalidateModule(fileIdToVirtualId(file));
}
cssMap.set(absoluteId, cssSource);
// We use the root relative id here to ensure file contents (content-hashes)
// are consistent across build machines
return `import "${rootRelativeId}";`;
}
});
return {
code: output,
map: {
mappings: ''
}
};
return result;
}
},
resolveId(source) {
var _compiler3;
const [validId, query] = source.split('?');
if (!isVirtualId(validId)) return;
const absoluteId = getAbsoluteId(validId);
if ( // We should always have CSS for a file here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
(_compiler3 = compiler) !== null && _compiler3 !== void 0 && _compiler3.getCssForFile(virtualIdToFileId(absoluteId))) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
}
},
load(id) {
const [validId] = id.split('?');
if (!isVirtualId(validId) || !compiler) return;
const absoluteId = getAbsoluteId(validId);
const {
css
} = compiler.getCssForFile(virtualIdToFileId(absoluteId));
return css;
}

@@ -235,0 +206,0 @@ };

import path from 'path';
import outdent from 'outdent';
import { getPackageInfo, cssFileFilter, transform, compile, processVanillaFile } from '@vanilla-extract/integration';
import { getPackageInfo, createCompiler, cssFileFilter, transform, normalizePath } from '@vanilla-extract/integration';
// Mostly copied from vite's implementation
// https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
const resolvePostcssConfig = async config => {
// inline postcss config via vite config
const inlineOptions = config.css?.postcss;
const inlineOptionsIsString = typeof inlineOptions === 'string';
if (inlineOptions && !inlineOptionsIsString) {
const options = {
...inlineOptions
};
delete options.plugins;
return {
options,
plugins: inlineOptions.plugins || []
};
} else {
try {
const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
const postCssConfig = await (await import('postcss-load-config')).default({}, searchPath);
return {
options: postCssConfig.options,
plugins: postCssConfig.plugins
};
} catch (e) {
if (!/No PostCSS Config found/.test(e.message)) {
throw e;
}
return null;
}
}
};
const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
const virtualExtCss = '.vanilla.css';
const virtualExtJs = '.vanilla.js';
const isVirtualId = id => id.endsWith(virtualExtCss);
const fileIdToVirtualId = id => `${id}${virtualExtCss}`;
const virtualIdToFileId = virtualId => virtualId.slice(0, -virtualExtCss.length);
const removeIncompatiblePlugins = plugin => typeof plugin === 'object' && plugin !== null && 'name' in plugin &&
// Prevent an infinite loop where the compiler creates a new instance of the plugin,
// which creates a new compiler, which creates a new instance of the plugin, etc.
plugin.name !== 'vanilla-extract' &&
// Skip Remix because it throws an error if it's not loaded with a config file.
// If it _is_ loaded with a config file, it will create an infinite loop because it
// also has a child compiler which uses the same mechanism to load the config file.
// https://github.com/remix-run/remix/pull/7990#issuecomment-1809356626
// Additionally, some internal Remix plugins rely on a `ctx` object to be initialized by
// the main Remix plugin, and may not function correctly without it. To address this, we
// filter out all Remix-related plugins.
!plugin.name.startsWith('remix');
function vanillaExtractPlugin({
identifiers,
emitCssInSsr,
esbuildOptions
unstable_mode: mode = 'emitCss'
} = {}) {
let config;
let configEnv;
let server;
let postCssConfig;
// We lazily load this utility from Vite
let normalizePath;
const cssMap = new Map();
const hasEmitCssOverride = typeof emitCssInSsr === 'boolean';
let resolvedEmitCssInSsr = hasEmitCssOverride ? emitCssInSsr : !!process.env.VITE_RSC_BUILD;
let packageName;
const getAbsoluteVirtualFileId = source => normalizePath(path.join(config.root, source));
let compiler;
const vitePromise = import('vite');
const getIdentOption = () => identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
const getAbsoluteId = filePath => {
let resolvedId = filePath;
if (filePath.startsWith(config.root) ||
// In monorepos the absolute path will be outside of config.root, so we check that they have the same root on the file system
// Paths from vite are always normalized, so we have to use the posix path separator
path.isAbsolute(filePath) && filePath.split(path.posix.sep)[1] === config.root.split(path.posix.sep)[1]) {
resolvedId = filePath;
} else {
// In SSR mode we can have paths like /app/styles.css.ts
resolvedId = path.join(config.root, filePath);
}
return normalizePath(resolvedId);
};
function invalidateModule(absoluteId) {
if (!server) return;
const {
moduleGraph
} = server;
const modules = moduleGraph.getModulesByFile(absoluteId);
if (modules) {
for (const module of modules) {
moduleGraph.invalidateModule(module);
// Vite uses this timestamp to add `?t=` query string automatically for HMR.
module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
}
}
}
return {
name: 'vanilla-extract',
enforce: 'pre',
configureServer(_server) {
server = _server;
},
config(_userConfig, env) {
const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
config(_userConfig, _configEnv) {
configEnv = _configEnv;
return {
optimizeDeps: {
include
},
ssr: {

@@ -72,63 +72,53 @@ external: ['@vanilla-extract/css', '@vanilla-extract/css/fileScope', '@vanilla-extract/css/adapter']

},
async configResolved(resolvedConfig) {
config = resolvedConfig;
async configResolved(_resolvedConfig) {
config = _resolvedConfig;
packageName = getPackageInfo(config.root).name;
normalizePath = (await import('vite')).normalizePath;
if (config.command === 'serve') {
postCssConfig = await resolvePostcssConfig(config);
}
if (!hasEmitCssOverride && config.plugins.some(plugin => ['astro:build', 'remix', 'solid-start-server', 'vite-plugin-qwik', 'vite-plugin-svelte'].includes(plugin.name))) {
resolvedEmitCssInSsr = true;
}
},
resolveId(source) {
const [validId, query] = source.split('?');
if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
return;
}
async buildStart() {
// Ensure we re-use the compiler instance between builds, e.g. in watch mode
if (mode !== 'transform' && !compiler) {
var _configForViteCompile;
const {
loadConfigFromFile
} = await vitePromise;
let configForViteCompiler;
// Absolute paths seem to occur often in monorepos, where files are
// imported from outside the config root.
const absoluteId = source.startsWith(config.root) ? source : getAbsoluteVirtualFileId(validId);
// There should always be an entry in the `cssMap` here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
if (cssMap.has(absoluteId)) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
// The user has a vite config file
if (config.configFile) {
const configFile = await loadConfigFromFile({
command: config.command,
mode: config.mode,
isSsrBuild: configEnv.isSsrBuild
}, config.configFile);
configForViteCompiler = configFile === null || configFile === void 0 ? void 0 : configFile.config;
}
// The user is using a vite-based framework that has a custom config file
else {
configForViteCompiler = config.inlineConfig;
}
const viteConfig = {
...configForViteCompiler,
plugins: (_configForViteCompile = configForViteCompiler) === null || _configForViteCompile === void 0 || (_configForViteCompile = _configForViteCompile.plugins) === null || _configForViteCompile === void 0 ? void 0 : _configForViteCompile.flat().filter(removeIncompatiblePlugins)
};
compiler = createCompiler({
root: config.root,
identifiers: getIdentOption(),
cssImportSpecifier: fileIdToVirtualId,
viteConfig
});
}
},
load(id) {
const [validId] = id.split('?');
if (!cssMap.has(validId)) {
return;
buildEnd() {
// When using the rollup watcher, we don't want to close the compiler after every build.
// Instead, we close it when the watcher is closed via the closeWatcher hook.
if (!config.build.watch) {
var _compiler;
(_compiler = compiler) === null || _compiler === void 0 || _compiler.close();
}
const css = cssMap.get(validId);
if (typeof css !== 'string') {
return;
}
if (validId.endsWith(virtualExtCss)) {
return css;
}
return outdent`
import { injectStyles } from '@vanilla-extract/css/injectStyles';
const inject = (css) => injectStyles({
fileScope: ${JSON.stringify({
filePath: validId
})},
css
});
inject(${JSON.stringify(css)});
if (import.meta.hot) {
import.meta.hot.on('${styleUpdateEvent(validId)}', (css) => {
inject(css);
});
}
`;
},
async transform(code, id, ssrParam) {
closeWatcher() {
var _compiler2;
return (_compiler2 = compiler) === null || _compiler2 === void 0 ? void 0 : _compiler2.close();
},
async transform(code, id) {
const [validId] = id.split('?');

@@ -138,10 +128,4 @@ if (!cssFileFilter.test(validId)) {

}
const identOption = identifiers ?? (config.mode === 'production' ? 'short' : 'debug');
let ssr;
if (typeof ssrParam === 'boolean') {
ssr = ssrParam;
} else {
ssr = ssrParam?.ssr;
}
if (ssr && !resolvedEmitCssInSsr) {
const identOption = getIdentOption();
if (mode === 'transform') {
return transform({

@@ -155,69 +139,57 @@ source: code,

}
const {
source,
watchFiles
} = await compile({
filePath: validId,
cwd: config.root,
esbuildOptions,
identOption
});
for (const file of watchFiles) {
// In start mode, we need to prevent the file from rewatching itself.
// If it's a `build --watch`, it needs to watch everything.
if (config.command === 'build' || normalizePath(file) !== validId) {
this.addWatchFile(file);
if (compiler) {
const absoluteId = getAbsoluteId(validId);
const {
source,
watchFiles
} = await compiler.processVanillaFile(absoluteId, {
outputCss: true
});
const result = {
code: source,
map: {
mappings: ''
}
};
// We don't need to watch files in build mode
if (config.command === 'build' && !config.build.watch) {
return result;
}
}
const output = await processVanillaFile({
source,
filePath: validId,
identOption,
serializeVirtualCssPath: async ({
fileScope,
source
}) => {
const rootRelativeId = `${fileScope.filePath}${config.command === 'build' || ssr && resolvedEmitCssInSsr ? virtualExtCss : virtualExtJs}`;
const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
let cssSource = source;
if (postCssConfig) {
const postCssResult = await (await import('postcss')).default(postCssConfig.plugins).process(source, {
...postCssConfig.options,
from: undefined,
map: false
});
cssSource = postCssResult.css;
for (const file of watchFiles) {
if (!file.includes('node_modules') && normalizePath(file) !== absoluteId) {
this.addWatchFile(file);
}
if (server && cssMap.has(absoluteId) && cssMap.get(absoluteId) !== cssSource) {
const {
moduleGraph
} = server;
const modules = Array.from(moduleGraph.getModulesByFile(absoluteId) || []);
for (const module of modules) {
if (module) {
moduleGraph.invalidateModule(module);
// Vite uses this timestamp to add `?t=` query string automatically for HMR.
module.lastHMRTimestamp = module.lastInvalidationTimestamp || Date.now();
}
}
server.ws.send({
type: 'custom',
event: styleUpdateEvent(absoluteId),
data: cssSource
});
// We have to invalidate the virtual module & deps, not the real one we just transformed
// The deps have to be invalidated in case one of them changing was the trigger causing
// the current transformation
if (file.endsWith('.css.ts')) {
invalidateModule(fileIdToVirtualId(file));
}
cssMap.set(absoluteId, cssSource);
// We use the root relative id here to ensure file contents (content-hashes)
// are consistent across build machines
return `import "${rootRelativeId}";`;
}
});
return {
code: output,
map: {
mappings: ''
}
};
return result;
}
},
resolveId(source) {
var _compiler3;
const [validId, query] = source.split('?');
if (!isVirtualId(validId)) return;
const absoluteId = getAbsoluteId(validId);
if ( // We should always have CSS for a file here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
(_compiler3 = compiler) !== null && _compiler3 !== void 0 && _compiler3.getCssForFile(virtualIdToFileId(absoluteId))) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : '');
}
},
load(id) {
const [validId] = id.split('?');
if (!isVirtualId(validId) || !compiler) return;
const absoluteId = getAbsoluteId(validId);
const {
css
} = compiler.getCssForFile(virtualIdToFileId(absoluteId));
return css;
}

@@ -224,0 +196,0 @@ };

{
"name": "@vanilla-extract/vite-plugin",
"version": "0.0.0-babel-modern-20231227140935",
"version": "0.0.0-const-regexes-20240813051516",
"description": "Zero-runtime Stylesheets-in-TypeScript",
"main": "dist/vanilla-extract-vite-plugin.cjs.js",
"module": "dist/vanilla-extract-vite-plugin.esm.js",
"types": "dist/vanilla-extract-vite-plugin.cjs.d.ts",
"files": [

@@ -18,13 +19,10 @@ "/dist"

"dependencies": {
"@vanilla-extract/integration": "0.0.0-babel-modern-20231227140935",
"outdent": "^0.8.0",
"postcss": "^8.3.6",
"postcss-load-config": "^4.0.1"
"@vanilla-extract/integration": "^0.0.0-const-regexes-20240813051516"
},
"devDependencies": {
"vite": "npm:vite@^2.7.0"
"vite": "^5.0.11"
},
"peerDependencies": {
"vite": "^2.2.3 || ^3.0.0 || ^4.0.3 || ^5.0.0"
"vite": "^4.0.3 || ^5.0.0"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc