@fastkit/plugboy-vanilla-extract-plugin 4.0.0-next.8 → 4.0.0-next.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # @fastkit/plugboy-vanilla-extract-plugin
2
+
3
+ 🌐 English | [日本語](https://github.com/dadajam4/fastkit/blob/main/packages/plugboy-vanilla-extract-plugin/README-ja.md)
4
+
5
+ A plugin that integrates [Vanilla Extract](https://vanilla-extract.style/) into [Plugboy](https://github.com/dadajam4/fastkit/blob/main/packages/plugboy/README.md) builds. It bundles the CSS extracted from `.css.ts` files into a single stylesheet per package, ships a Vite plugin for development, and provides helpers for working with cascade layers.
6
+
7
+ ## Features
8
+
9
+ - **Single CSS output**: Combines the styles extracted from a package's `.css.ts` files into one `dist/<package>.css`.
10
+ - **Automatic merge with plain CSS**: Merges tsdown's output for plain `.css` / `.scss` with the Vanilla Extract output into a single file (preventing the style loss caused by a file-name collision between the two).
11
+ - **Vite integration**: Ships a Vite plugin for use in dev servers, Storybook, and similar environments.
12
+ - **Layer helpers**: `@fastkit/plugboy-vanilla-extract-plugin/css` exposes utilities for defining cascade layers in a type-safe way.
13
+
14
+ > [!NOTE]
15
+ > Preserving external `@import`s (e.g. `@import url('material-symbols/rounded.css') layer(...)`) and ordering `@layer` declarations are handled by [Plugboy](https://github.com/dadajam4/fastkit/blob/main/packages/plugboy/README.md) itself, and apply to the CSS this plugin combines as well.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install -D @fastkit/plugboy-vanilla-extract-plugin
21
+ # or
22
+ pnpm add -D @fastkit/plugboy-vanilla-extract-plugin
23
+ ```
24
+
25
+ > [!NOTE]
26
+ > Requires `@fastkit/plugboy` (and `vite`, when using the Vite integration) as peer dependencies.
27
+
28
+ ## Usage
29
+
30
+ ### 1. Register in the build
31
+
32
+ Add it to the `plugins` of `plugboy.project.ts` (project-wide) or a per-workspace `plugboy.workspace.ts`. It activates automatically for packages that contain `.css.ts` files.
33
+
34
+ ```typescript
35
+ import { defineProjectConfig } from '@fastkit/plugboy';
36
+ import { createVanillaExtractPlugin } from '@fastkit/plugboy-vanilla-extract-plugin';
37
+
38
+ export default defineProjectConfig({
39
+ plugins: [
40
+ createVanillaExtractPlugin({
41
+ // Identifier format for class names etc. ('short' recommended for production)
42
+ identifiers: 'short',
43
+ }),
44
+ ],
45
+ });
46
+ ```
47
+
48
+ On build, the package styles are combined into `dist/<package>.css`.
49
+
50
+ ### 2. Use with Vite (dev / Storybook, etc.)
51
+
52
+ For environments that resolve Vanilla Extract without a Plugboy build (Vite dev server, Storybook, etc.), use the Vite plugin.
53
+
54
+ ```typescript
55
+ import { defineConfig } from 'vite';
56
+ import { ViteVanillaExtractPlugin } from '@fastkit/plugboy-vanilla-extract-plugin';
57
+
58
+ export default defineConfig({
59
+ plugins: [
60
+ ViteVanillaExtractPlugin({
61
+ identifiers: 'debug',
62
+ }),
63
+ ],
64
+ });
65
+ ```
66
+
67
+ ### 3. Cascade layer helpers (`/css`)
68
+
69
+ `@fastkit/plugboy-vanilla-extract-plugin/css` lets you define nestable cascade layers in a type-safe way.
70
+
71
+ ```typescript
72
+ import { defineLayerStyle } from '@fastkit/plugboy-vanilla-extract-plugin/css';
73
+
74
+ export const framework = defineLayerStyle({ globalName: 'my-ui' });
75
+
76
+ export const base = framework.defineNestedLayer({ globalName: 'base' });
77
+ export const component = framework.defineNestedLayer({ globalName: 'component' });
78
+ ```
79
+
80
+ ## Options
81
+
82
+ The main options accepted by `createVanillaExtractPlugin(options)` / `ViteVanillaExtractPlugin(options)`.
83
+
84
+ | Option | Type | Description |
85
+ | --- | --- | --- |
86
+ | `identifiers` | `'short' \| 'debug' \| ((meta) => string)` | Format of generated identifiers such as class names. Use `'short'` for production builds and `'debug'` while debugging. |
87
+ | `esbuildOptions` | `EsbuildOptions` | Options forwarded to esbuild when compiling `.css.ts` files. |
88
+
89
+ ## License
90
+
91
+ [MIT](https://github.com/dadajam4/fastkit/blob/main/LICENSE)
@@ -5,17 +5,7 @@ import { Plugin as Plugin$1 } from "vite";
5
5
 
6
6
  //#region src/types.d.ts
7
7
  type VanillaExtractPluginOptions = Omit<NonNullable<Parameters<typeof vanillaExtractPlugin>[0]>, 'extract'>;
8
- type PrependFnResultValue = string | void;
9
- type PrependFn = (ctx: {
10
- cssFileName: string;
11
- }) => PrependFnResultValue | Promise<PrependFnResultValue>;
12
- interface PluginOptions extends Pick<VanillaExtractPluginOptions, 'identifiers' | 'esbuildOptions'> {
13
- /**
14
- * Inserts arbitrary code at the beginning of the generated CSS bundle.
15
- * This is useful for injecting global directives or comments.
16
- */
17
- prepend?: string | PrependFn;
18
- }
8
+ type PluginOptions = Pick<VanillaExtractPluginOptions, 'identifiers' | 'esbuildOptions'>;
19
9
  declare const PLUGIN_NAME = "plugboy-vanilla-extract";
20
10
  interface VanillaExtractPlugin extends Plugin {
21
11
  name: typeof PLUGIN_NAME;
@@ -35,5 +25,5 @@ type VanillaExtractVitePluginOptions = NonNullable<Parameters<typeof vanillaExtr
35
25
  interface ViteVanillaExtractPluginOptions extends VanillaExtractVitePluginOptions {}
36
26
  declare function ViteVanillaExtractPlugin(options?: ViteVanillaExtractPluginOptions): Promise<Plugin$1[]>;
37
27
  //#endregion
38
- export { PLUGIN_NAME, PluginOptions, PrependFn, PrependFnResultValue, VanillaExtractPlugin, ViteVanillaExtractPlugin, ViteVanillaExtractPluginOptions, createVanillaExtractPlugin };
28
+ export { PLUGIN_NAME, PluginOptions, VanillaExtractPlugin, ViteVanillaExtractPlugin, ViteVanillaExtractPluginOptions, createVanillaExtractPlugin };
39
29
  //# sourceMappingURL=plugboy-vanilla-extract-plugin.d.mts.map
@@ -1,3 +1,5 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
1
3
  import { definePlugin, findFile, findProjectPlugin } from "@fastkit/plugboy";
2
4
  import { vanillaExtractPlugin } from "@vanilla-extract/rollup-plugin";
3
5
  import { vanillaExtractPlugin as vanillaExtractPlugin$1 } from "@vanilla-extract/vite-plugin";
@@ -17,7 +19,7 @@ const PLUGIN_NAME = "plugboy-vanilla-extract";
17
19
  * (`FILE_NAME_CONFLICT` — one silently overwrites the other, dropping all of
18
20
  * the vanilla-extract component CSS). To avoid that we route tsdown's CSS to
19
21
  * this temporary name and merge it into the vanilla-extract bundle in
20
- * `generateBundle`.
22
+ * `writeBundle`.
21
23
  */
22
24
  const TSDOWN_CSS_FILE_NAME = "__ve-tsdown__.css";
23
25
  async function createVanillaExtractPlugin(options = {}) {
@@ -27,12 +29,12 @@ async function createVanillaExtractPlugin(options = {}) {
27
29
  hooks: { async setupWorkspace(ctx, getWorkspace) {
28
30
  const entryIds = Object.keys(ctx.config.entries);
29
31
  const cssFileName = `${entryIds.includes(".") ? ctx.dir.basename : entryIds[0] ?? ctx.dir.basename}.css`;
32
+ ctx.mergeExternals(/@vanilla-extract/);
33
+ ctx.meta.hasVanillaExtract = !!await findFile(ctx.dirs.src.value, /\.css\.ts$/);
30
34
  ctx.css = {
31
35
  splitting: false,
32
- fileName: TSDOWN_CSS_FILE_NAME
36
+ fileName: ctx.meta.hasVanillaExtract ? TSDOWN_CSS_FILE_NAME : cssFileName
33
37
  };
34
- ctx.mergeExternals(/@vanilla-extract/);
35
- ctx.meta.hasVanillaExtract = !!await findFile(ctx.dirs.src.value, /\.css\.ts$/);
36
38
  if (ctx.meta.hasVanillaExtract) {
37
39
  const originalPlugin = vanillaExtractPlugin({
38
40
  ...options,
@@ -53,18 +55,20 @@ async function createVanillaExtractPlugin(options = {}) {
53
55
  };
54
56
  return opts;
55
57
  },
56
- generateBundle(_opts, bundle) {
58
+ async writeBundle(outputOptions, bundle) {
57
59
  const tmp = bundle[TSDOWN_CSS_FILE_NAME];
58
- const tmpCss = tmp && tmp.type === "asset" ? tmp.source.toString() : "";
59
- if (tmp) delete bundle[TSDOWN_CSS_FILE_NAME];
60
- if (!tmpCss) return;
61
- const veAsset = bundle[cssFileName];
62
- if (veAsset && veAsset.type === "asset") veAsset.source = `${tmpCss}\n${veAsset.source.toString()}`;
63
- else this.emitFile({
64
- type: "asset",
65
- fileName: cssFileName,
66
- source: tmpCss
67
- });
60
+ if (!tmp) return;
61
+ const tmpCss = tmp.type === "asset" ? tmp.source.toString() : "";
62
+ const dir = outputOptions.dir ?? ".";
63
+ const tmpPath = path.join(dir, TSDOWN_CSS_FILE_NAME);
64
+ const targetPath = path.join(dir, cssFileName);
65
+ let targetCss = "";
66
+ try {
67
+ targetCss = await fs.readFile(targetPath, "utf8");
68
+ } catch {}
69
+ const merged = tmpCss ? targetCss ? `${tmpCss}\n${targetCss}` : tmpCss : targetCss;
70
+ if (merged) await fs.writeFile(targetPath, merged);
71
+ await fs.rm(tmpPath, { force: true });
68
72
  }
69
73
  });
70
74
  }
@@ -1 +1 @@
1
- {"version":3,"file":"plugboy-vanilla-extract-plugin.mjs","names":["vanillaExtractPlugin"],"sources":["../src/types.ts","../src/plugin.ts","../src/vite.ts"],"sourcesContent":["import { Plugin } from '@fastkit/plugboy';\nimport type { vanillaExtractPlugin as rollupPlugin } from '@vanilla-extract/rollup-plugin';\n\ntype VanillaExtractPluginOptions = Omit<\n NonNullable<Parameters<typeof rollupPlugin>[0]>,\n 'extract'\n>;\n\nexport type PrependFnResultValue = string | void;\n\nexport type PrependFn = (ctx: {\n cssFileName: string;\n}) => PrependFnResultValue | Promise<PrependFnResultValue>;\n\nexport interface PluginOptions extends Pick<\n VanillaExtractPluginOptions,\n 'identifiers' | 'esbuildOptions'\n> {\n /**\n * Inserts arbitrary code at the beginning of the generated CSS bundle.\n * This is useful for injecting global directives or comments.\n */\n prepend?: string | PrependFn;\n}\n\nexport const PLUGIN_NAME = 'plugboy-vanilla-extract';\n\nexport interface VanillaExtractPlugin extends Plugin {\n name: typeof PLUGIN_NAME;\n _options: PluginOptions;\n}\n","import { definePlugin, findFile, type Plugin } from '@fastkit/plugboy';\nimport { vanillaExtractPlugin } from '@vanilla-extract/rollup-plugin';\nimport { VanillaExtractPlugin, PluginOptions, PLUGIN_NAME } from './types';\n\ndeclare module '@fastkit/plugboy' {\n export interface WorkspaceMeta {\n hasVanillaExtract: boolean;\n }\n}\n\n/**\n * Temporary file name for the CSS that tsdown's own CSS pipeline emits.\n *\n * A package can have two independent sources of CSS:\n * - tsdown's built-in CSS handling, for plain `.css` / `.scss` imports.\n * - `@vanilla-extract/rollup-plugin`, for `.css.ts` files (extracted into a\n * single bundle named after the package).\n *\n * If both are pointed at the same final file name they collide\n * (`FILE_NAME_CONFLICT` — one silently overwrites the other, dropping all of\n * the vanilla-extract component CSS). To avoid that we route tsdown's CSS to\n * this temporary name and merge it into the vanilla-extract bundle in\n * `generateBundle`.\n */\nconst TSDOWN_CSS_FILE_NAME = '__ve-tsdown__.css';\n\nexport async function createVanillaExtractPlugin(options: PluginOptions = {}) {\n return definePlugin<VanillaExtractPlugin>({\n name: PLUGIN_NAME,\n _options: options,\n hooks: {\n async setupWorkspace(ctx, getWorkspace) {\n // Derive the final CSS file name from the workspace entry, mirroring the\n // way plugboy names the JS output: the main entry (`.`) maps to the\n // package directory name (e.g. `vue-app-layout`), other entries keep\n // their id. Since `splitting: false` produces a single combined CSS for\n // the package, we base it on the main entry (falling back to the first).\n // Result: `dist/vue-app-layout.css` instead of `dist/__ve-tmp__.css`.\n const entryIds = Object.keys(ctx.config.entries);\n const cssBaseName = entryIds.includes('.')\n ? ctx.dir.basename\n : (entryIds[0] ?? ctx.dir.basename);\n const cssFileName = `${cssBaseName}.css`;\n\n // Keep tsdown's own CSS out of `cssFileName` so it doesn't collide with\n // the vanilla-extract bundle that also targets `cssFileName`. The two\n // are merged into a single `cssFileName` later (see the merge hook).\n ctx.css = {\n splitting: false,\n fileName: TSDOWN_CSS_FILE_NAME,\n };\n\n ctx.mergeExternals(/@vanilla-extract/);\n\n ctx.meta.hasVanillaExtract = !!(await findFile(\n ctx.dirs.src.value,\n /\\.css\\.ts$/,\n ));\n\n if (ctx.meta.hasVanillaExtract) {\n const originalPlugin = vanillaExtractPlugin({\n ...options,\n extract: {\n name: cssFileName,\n sourcemap: false,\n },\n });\n\n // `@vanilla-extract/rollup-plugin` returns a rollup `Plugin`, but\n // plugboy's `ctx.plugins` expects a tsdown (rolldown) `Plugin`. The two\n // are structurally almost identical, but hooks like `outputOptions`\n // type `this` as rollup's `PluginContext` vs rolldown's\n // `MinimalPluginContext`, which makes them unassignable (the `this`\n // type is contravariant). rolldown accepts rollup plugins at runtime,\n // so this is harmless — cast to work around the type mismatch.\n ctx.plugins.push(originalPlugin as unknown as Plugin);\n\n // `@vanilla-extract/rollup-plugin` emits the extracted CSS via\n // `emitFile({ type: 'asset', name: cssFileName })`. Because it uses\n // `name` (a hint) rather than `fileName`, rolldown runs it through the\n // default `assetFileNames` pattern (`assets/[name]-[hash][extname]`),\n // producing e.g. `dist/assets/vue-app-layout-dry0z-1l.css`.\n //\n // We can't *rename* an asset in `generateBundle` because rolldown\n // ignores mutations to a bundle entry's `fileName`. Instead, override\n // `assetFileNames` via the `outputOptions` hook so this single CSS\n // asset keeps its derived name verbatim (no hash, no `assets/` dir)\n // while every other asset keeps its original naming.\n ctx.plugins.push({\n name: `${PLUGIN_NAME}:rename-css`,\n outputOptions(opts) {\n const original = opts.assetFileNames;\n opts.assetFileNames = (assetInfo) => {\n if (assetInfo.names.includes(cssFileName)) {\n return cssFileName;\n }\n if (typeof original === 'function') return original(assetInfo);\n return original ?? 'assets/[name]-[hash][extname]';\n };\n return opts;\n },\n // Merge tsdown's own CSS (emitted to `TSDOWN_CSS_FILE_NAME`) into the\n // vanilla-extract bundle so the package ships a single `cssFileName`.\n // tsdown's CSS comes first so its `@layer` declarations / resets are\n // established before the extracted component styles. Unlike renaming,\n // mutating an asset's `source` IS honored by rolldown.\n generateBundle(_opts, bundle) {\n const tmp = bundle[TSDOWN_CSS_FILE_NAME];\n const tmpCss =\n tmp && tmp.type === 'asset' ? tmp.source.toString() : '';\n if (tmp) delete bundle[TSDOWN_CSS_FILE_NAME];\n if (!tmpCss) return;\n\n const veAsset = bundle[cssFileName];\n if (veAsset && veAsset.type === 'asset') {\n veAsset.source = `${tmpCss}\\n${veAsset.source.toString()}`;\n } else {\n // No vanilla-extract output (e.g. `.css.ts` produced no rules) —\n // promote tsdown's CSS to the final file name.\n this.emitFile({\n type: 'asset',\n fileName: cssFileName,\n source: tmpCss,\n });\n }\n },\n });\n }\n },\n },\n });\n}\n","import { findProjectPlugin } from '@fastkit/plugboy';\nimport { Plugin as VitePlugin } from 'vite';\nimport { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';\nimport { PLUGIN_NAME, VanillaExtractPlugin } from './types';\n\ntype VanillaExtractVitePluginOptions = NonNullable<\n Parameters<typeof vanillaExtractPlugin>[0]\n>;\n\nexport interface ViteVanillaExtractPluginOptions extends VanillaExtractVitePluginOptions {}\n\nexport async function ViteVanillaExtractPlugin(\n options: ViteVanillaExtractPluginOptions = {},\n): Promise<VitePlugin[]> {\n const plugin = await findProjectPlugin<VanillaExtractPlugin>(PLUGIN_NAME);\n const { identifiers: baseIdentifiers } = plugin?._options || {};\n\n return [\n ...vanillaExtractPlugin({\n identifiers: baseIdentifiers,\n ...options,\n }),\n // @MEMO\n // Plugin to prevent file scope mismatches when utilities using vanilla-extract\n // functions are placed in external files\n {\n name: 'vanilla-extract-fix-file-scope',\n config(viteConfig) {\n viteConfig.resolve ??= {};\n viteConfig.resolve.dedupe ??= [];\n viteConfig.resolve.dedupe.push(\n '@vanilla-extract/css',\n '@vanilla-extract/css/fileScope',\n );\n },\n },\n ];\n}\n"],"mappings":";;;;AAyBA,MAAa,cAAc;;;;;;;;;;;;;;;;;ACD3B,MAAM,uBAAuB;AAE7B,eAAsB,2BAA2B,UAAyB,CAAC,GAAG;CAC5E,OAAO,aAAmC;EACxC,MAAM;EACN,UAAU;EACV,OAAO,EACL,MAAM,eAAe,KAAK,cAAc;GAOtC,MAAM,WAAW,OAAO,KAAK,IAAI,OAAO,OAAO;GAI/C,MAAM,cAAc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,MAAM;EACN,OAAO,YAAY;GACjB,WAAW,YAAY,CAAC;GACxB,WAAW,QAAQ,WAAW,CAAC;GAC/B,WAAW,QAAQ,OAAO,KACxB,wBACA,gCACF;EACF;CACF,CACF;AACF"}
1
+ {"version":3,"file":"plugboy-vanilla-extract-plugin.mjs","names":["vanillaExtractPlugin"],"sources":["../src/types.ts","../src/plugin.ts","../src/vite.ts"],"sourcesContent":["import { Plugin } from '@fastkit/plugboy';\nimport type { vanillaExtractPlugin as rollupPlugin } from '@vanilla-extract/rollup-plugin';\n\ntype VanillaExtractPluginOptions = Omit<\n NonNullable<Parameters<typeof rollupPlugin>[0]>,\n 'extract'\n>;\n\nexport type PluginOptions = Pick<\n VanillaExtractPluginOptions,\n 'identifiers' | 'esbuildOptions'\n>;\n\nexport const PLUGIN_NAME = 'plugboy-vanilla-extract';\n\nexport interface VanillaExtractPlugin extends Plugin {\n name: typeof PLUGIN_NAME;\n _options: PluginOptions;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { definePlugin, findFile, type Plugin } from '@fastkit/plugboy';\nimport { vanillaExtractPlugin } from '@vanilla-extract/rollup-plugin';\nimport { VanillaExtractPlugin, PluginOptions, PLUGIN_NAME } from './types';\n\ndeclare module '@fastkit/plugboy' {\n export interface WorkspaceMeta {\n hasVanillaExtract: boolean;\n }\n}\n\n/**\n * Temporary file name for the CSS that tsdown's own CSS pipeline emits.\n *\n * A package can have two independent sources of CSS:\n * - tsdown's built-in CSS handling, for plain `.css` / `.scss` imports.\n * - `@vanilla-extract/rollup-plugin`, for `.css.ts` files (extracted into a\n * single bundle named after the package).\n *\n * If both are pointed at the same final file name they collide\n * (`FILE_NAME_CONFLICT` — one silently overwrites the other, dropping all of\n * the vanilla-extract component CSS). To avoid that we route tsdown's CSS to\n * this temporary name and merge it into the vanilla-extract bundle in\n * `writeBundle`.\n */\nconst TSDOWN_CSS_FILE_NAME = '__ve-tsdown__.css';\n\nexport async function createVanillaExtractPlugin(options: PluginOptions = {}) {\n return definePlugin<VanillaExtractPlugin>({\n name: PLUGIN_NAME,\n _options: options,\n hooks: {\n async setupWorkspace(ctx, getWorkspace) {\n // Derive the final CSS file name from the workspace entry, mirroring the\n // way plugboy names the JS output: the main entry (`.`) maps to the\n // package directory name (e.g. `vue-app-layout`), other entries keep\n // their id. Since `splitting: false` produces a single combined CSS for\n // the package, we base it on the main entry (falling back to the first).\n // Result: `dist/vue-app-layout.css` instead of `dist/__ve-tmp__.css`.\n const entryIds = Object.keys(ctx.config.entries);\n const cssBaseName = entryIds.includes('.')\n ? ctx.dir.basename\n : (entryIds[0] ?? ctx.dir.basename);\n const cssFileName = `${cssBaseName}.css`;\n\n ctx.mergeExternals(/@vanilla-extract/);\n\n ctx.meta.hasVanillaExtract = !!(await findFile(\n ctx.dirs.src.value,\n /\\.css\\.ts$/,\n ));\n\n // When vanilla-extract is in play, route tsdown's own CSS to a temporary\n // name so it doesn't collide with the vanilla-extract bundle that also\n // targets `cssFileName`; the two are merged into a single `cssFileName`\n // by the `writeBundle` hook below. Without vanilla-extract there is no\n // second producer, so tsdown emits `cssFileName` directly.\n ctx.css = {\n splitting: false,\n fileName: ctx.meta.hasVanillaExtract\n ? TSDOWN_CSS_FILE_NAME\n : cssFileName,\n };\n\n if (ctx.meta.hasVanillaExtract) {\n const originalPlugin = vanillaExtractPlugin({\n ...options,\n extract: {\n name: cssFileName,\n sourcemap: false,\n },\n });\n\n // `@vanilla-extract/rollup-plugin` returns a rollup `Plugin`, but\n // plugboy's `ctx.plugins` expects a tsdown (rolldown) `Plugin`. The two\n // are structurally almost identical, but hooks like `outputOptions`\n // type `this` as rollup's `PluginContext` vs rolldown's\n // `MinimalPluginContext`, which makes them unassignable (the `this`\n // type is contravariant). rolldown accepts rollup plugins at runtime,\n // so this is harmless — cast to work around the type mismatch.\n ctx.plugins.push(originalPlugin as unknown as Plugin);\n\n // `@vanilla-extract/rollup-plugin` emits the extracted CSS via\n // `emitFile({ type: 'asset', name: cssFileName })`. Because it uses\n // `name` (a hint) rather than `fileName`, rolldown runs it through the\n // default `assetFileNames` pattern (`assets/[name]-[hash][extname]`),\n // producing e.g. `dist/assets/vue-app-layout-dry0z-1l.css`.\n //\n // We can't *rename* an asset in `generateBundle` because rolldown\n // ignores mutations to a bundle entry's `fileName`. Instead, override\n // `assetFileNames` via the `outputOptions` hook so this single CSS\n // asset keeps its derived name verbatim (no hash, no `assets/` dir)\n // while every other asset keeps its original naming.\n ctx.plugins.push({\n name: `${PLUGIN_NAME}:rename-css`,\n outputOptions(opts) {\n const original = opts.assetFileNames;\n opts.assetFileNames = (assetInfo) => {\n if (assetInfo.names.includes(cssFileName)) {\n return cssFileName;\n }\n if (typeof original === 'function') return original(assetInfo);\n return original ?? 'assets/[name]-[hash][extname]';\n };\n return opts;\n },\n // Merge tsdown's own CSS (emitted to `TSDOWN_CSS_FILE_NAME`) into the\n // vanilla-extract bundle so the package ships a single `cssFileName`.\n //\n // This has to happen in `writeBundle`, not `generateBundle`: tsdown\n // emits its CSS in a separate output pass, so `TSDOWN_CSS_FILE_NAME`\n // is absent from the bundle our `generateBundle` sees but present\n // (alongside the vanilla-extract asset) by `writeBundle`. By then both\n // files are already on disk, so we merge on disk rather than mutating\n // bundle sources. tsdown's CSS goes first so its `@layer` declarations\n // / resets are established before the extracted component styles.\n async writeBundle(outputOptions, bundle) {\n // Only the output pass that emitted tsdown's CSS performs the merge\n // (it is the one whose `bundle` contains `TSDOWN_CSS_FILE_NAME`).\n // This also prevents a second output from re-injecting the imports.\n const tmp = bundle[TSDOWN_CSS_FILE_NAME];\n if (!tmp) return;\n\n const tmpCss = tmp.type === 'asset' ? tmp.source.toString() : '';\n const dir = outputOptions.dir ?? '.';\n const tmpPath = path.join(dir, TSDOWN_CSS_FILE_NAME);\n const targetPath = path.join(dir, cssFileName);\n\n let targetCss = '';\n try {\n targetCss = await fs.readFile(targetPath, 'utf8');\n } catch {\n // No vanilla-extract output file (e.g. `.css.ts` produced no\n // rules) — tsdown's CSS becomes the whole `cssFileName`.\n }\n\n const merged = tmpCss\n ? targetCss\n ? `${tmpCss}\\n${targetCss}`\n : tmpCss\n : targetCss;\n\n if (merged) await fs.writeFile(targetPath, merged);\n await fs.rm(tmpPath, { force: true });\n },\n });\n }\n },\n },\n });\n}\n","import { findProjectPlugin } from '@fastkit/plugboy';\nimport { Plugin as VitePlugin } from 'vite';\nimport { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';\nimport { PLUGIN_NAME, VanillaExtractPlugin } from './types';\n\ntype VanillaExtractVitePluginOptions = NonNullable<\n Parameters<typeof vanillaExtractPlugin>[0]\n>;\n\nexport interface ViteVanillaExtractPluginOptions extends VanillaExtractVitePluginOptions {}\n\nexport async function ViteVanillaExtractPlugin(\n options: ViteVanillaExtractPluginOptions = {},\n): Promise<VitePlugin[]> {\n const plugin = await findProjectPlugin<VanillaExtractPlugin>(PLUGIN_NAME);\n const { identifiers: baseIdentifiers } = plugin?._options || {};\n\n return [\n ...vanillaExtractPlugin({\n identifiers: baseIdentifiers,\n ...options,\n }),\n // @MEMO\n // Plugin to prevent file scope mismatches when utilities using vanilla-extract\n // functions are placed in external files\n {\n name: 'vanilla-extract-fix-file-scope',\n config(viteConfig) {\n viteConfig.resolve ??= {};\n viteConfig.resolve.dedupe ??= [];\n viteConfig.resolve.dedupe.push(\n '@vanilla-extract/css',\n '@vanilla-extract/css/fileScope',\n );\n },\n },\n ];\n}\n"],"mappings":";;;;;;AAaA,MAAa,cAAc;;;;;;;;;;;;;;;;;ACa3B,MAAM,uBAAuB;AAE7B,eAAsB,2BAA2B,UAAyB,CAAC,GAAG;CAC5E,OAAO,aAAmC;EACxC,MAAM;EACN,UAAU;EACV,OAAO,EACL,MAAM,eAAe,KAAK,cAAc;GAOtC,MAAM,WAAW,OAAO,KAAK,IAAI,OAAO,OAAO;GAI/C,MAAM,cAAc,GAHA,SAAS,SAAS,GAAG,IACrC,IAAI,IAAI,WACP,SAAS,MAAM,IAAI,IAAI,SACO;GAEnC,IA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A,EACvB,YAAY,CAAC;CAE9D,OAAO,CACL,GAAGA,uBAAqB;EACtB,aAAa;EACb,GAAG;CACL,CAAC,GAID;EACE,MAAM;EACN,OAAO,YAAY;GACjB,WAAW,YAAY,CAAC;GACxB,WAAW,QAAQ,WAAW,CAAC;GAC/B,WAAW,QAAQ,OAAO,KACxB,wBACA,gCACF;EACF;CACF,CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fastkit/plugboy-vanilla-extract-plugin",
3
- "version": "4.0.0-next.8",
3
+ "version": "4.0.0-next.9",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "repository": {
@@ -48,11 +48,11 @@
48
48
  },
49
49
  "devDependencies": {
50
50
  "vite": "^8.0.16",
51
- "@fastkit/plugboy": "^1.0.0-next.5"
51
+ "@fastkit/plugboy": "^1.0.0-next.6"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0",
55
- "@fastkit/plugboy": "^1.0.0-next.5"
55
+ "@fastkit/plugboy": "^1.0.0-next.6"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "@vanilla-extract/vite-plugin": {