@sanity/tsdown-config 0.13.1 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,7 +72,9 @@ export default defineConfig({
72
72
 
73
73
  The same `vanillaExtract` feature as `@sanity/pkg-utils` is available. It extracts the CSS from
74
74
  `.css.ts` files into a separate, `lightningcss`-optimized file (`dist/bundle.css` by default).
75
- Start by installing `@vanilla-extract/css` for authoring the `.css.ts` files:
75
+ Under the hood it uses [`@sanity/vanilla-extract-tsdown-plugin`](https://github.com/sanity-io/pkg-utils/tree/main/packages/%40sanity/vanilla-extract-tsdown-plugin#readme),
76
+ a tsdown-native port of `@vanilla-extract/rollup-plugin`, so enabling it doesn't pull `rollup`
77
+ into your project. Start by installing `@vanilla-extract/css` for authoring the `.css.ts` files:
76
78
 
77
79
  ```sh
78
80
  pnpm add --save-dev @vanilla-extract/css
@@ -87,10 +89,11 @@ export default defineConfig({
87
89
  })
88
90
  ```
89
91
 
90
- By default a compatibility mode is active that automatically wires up the conditional CSS export
91
- pattern:
92
+ By default (`inject: {nodeCompat: true}`) the conditional CSS export pattern is wired up
93
+ automatically:
92
94
 
93
- - injects the self-referential `import "<pkg>/bundle.css"` into the `index` entry chunk,
95
+ - injects the self-referential `import "<pkg>/bundle.css"` into the entry chunks that use
96
+ vanilla-extract styles,
94
97
  - emits a no-op `bundle.css.js` shim (plus `bundle.css.d.ts`) for runtimes that cannot import
95
98
  `.css` files, and
96
99
  - writes the conditional `"./bundle.css"` export to `package.json` (`browser`/`style` → the real
@@ -106,9 +109,10 @@ consumers by adding it to `sideEffects` in `package.json`:
106
109
  }
107
110
  ```
108
111
 
109
- Pass an options object instead of `true` to customize (e.g. `minify`, `browserslist`,
110
- `extract.name`), or set `extract.compatMode: false` to wire up the import, shim, and export
111
- yourself.
112
+ Pass an options object instead of `true` to customize - the options are modeled after the
113
+ [`css` options of `@tsdown/css`](https://tsdown.dev/options/css) (e.g. `fileName`, `minify`,
114
+ `target`). Set `inject: true` for a plain relative `import "./bundle.css"` instead of the
115
+ conditional export pattern, or `inject: false` to wire up the import, shim, and export yourself.
112
116
 
113
117
  ## dts
114
118
 
@@ -128,6 +132,38 @@ export default defineConfig({
128
132
  })
129
133
  ```
130
134
 
135
+ ## Isolated declarations
136
+
137
+ If you're using the [`@sanity/tsconfig/isolated-declarations`](https://github.com/sanity-io/pkg-utils/tree/main/packages/%40sanity/tsconfig#isolated-declarations-tsconfigjson)
138
+ preset — which makes tsdown generate the `.d.ts` files with oxc's fast isolated declarations
139
+ transform — annotate the default export of `tsdown.config.ts` with `satisfies Promise<UserConfig>`:
140
+
141
+ ```ts
142
+ import {defineConfig} from '@sanity/tsdown-config'
143
+ import type {UserConfig} from 'tsdown'
144
+
145
+ export default defineConfig() satisfies Promise<UserConfig>
146
+ ```
147
+
148
+ Without the annotation, type-checking `tsdown.config.ts` with the `@sanity/tsconfig` presets (they
149
+ enable `declaration`) fails with TS2883 in pnpm projects: the inferred type of the default export
150
+ can only be named through `@sanity/tsdown-config`'s own copy of `tsdown`, which isn't portable.
151
+ `satisfies Promise<UserConfig>` names the type through your own `tsdown` dependency instead.
152
+
153
+ Keep the `isolated-declarations` preset scoped to the tsconfig that tsdown builds with (e.g. a
154
+ `tsconfig.dist.json` that only includes `./src`). If `isolatedDeclarations` covers
155
+ `tsdown.config.ts` itself, the default export can't be inferred at all (TS9037), and the config has
156
+ to move into an explicitly annotated variable instead:
157
+
158
+ ```ts
159
+ import {defineConfig} from '@sanity/tsdown-config'
160
+ import type {UserConfig} from 'tsdown'
161
+
162
+ const config: Promise<UserConfig> = defineConfig()
163
+
164
+ export default config
165
+ ```
166
+
131
167
  ## define
132
168
 
133
169
  tsdown's `define` option is also passed through as-is. It replaces global identifiers with constant
@@ -141,3 +177,60 @@ export default defineConfig({
141
177
  define: {'process.env.NODE_ENV': JSON.stringify('production')},
142
178
  })
143
179
  ```
180
+
181
+ ## target
182
+
183
+ tsdown's [`target` option](https://tsdown.dev/options/target) is also passed through as-is. It
184
+ downlevels JS syntax for the given runtimes (esbuild-style target strings), and doubles as the
185
+ default CSS syntax lowering target when `vanillaExtract` is enabled (browserless targets like
186
+ `node20` don't affect the CSS - it falls back to `@sanity/browserslist-config`):
187
+
188
+ ```ts
189
+ import {defineConfig} from '@sanity/tsdown-config'
190
+
191
+ export default defineConfig({
192
+ tsconfig: 'tsconfig.dist.json',
193
+ target: ['chrome90', 'safari16'],
194
+ })
195
+ ```
196
+
197
+ ## exports
198
+
199
+ tsdown's [`exports` option](https://tsdown.dev/options/package-exports) is forwarded with
200
+ different defaults, suited for publishing Sanity libraries:
201
+
202
+ - `enabled: 'local-only'` - the `exports` map in `package.json` is generated during local builds
203
+ and skipped in CI, where the committed `package.json` is already up to date, and
204
+ - `devExports: true` when pnpm is detected - the local `exports` map points at the source files
205
+ (so monorepo siblings and editors resolve them directly), while `publishConfig.exports` receives
206
+ the built files. This default is omitted for other or unknown package managers because they do
207
+ not all reliably apply `publishConfig.exports` when publishing.
208
+
209
+ Userland values apply with tsdown's `mergeConfig` semantics: an object deep-merges over the
210
+ defaults (so individual fields can be overridden), while any other value - `false` to disable
211
+ exports generation, or a bare CI condition (`'ci-only'`/`'local-only'`) - replaces them entirely:
212
+
213
+ ```ts
214
+ import {defineConfig} from '@sanity/tsdown-config'
215
+
216
+ export default defineConfig({
217
+ tsconfig: 'tsconfig.dist.json',
218
+ exports: {all: true},
219
+ })
220
+ ```
221
+
222
+ ## Everything else: `mergeConfig`
223
+
224
+ `defineConfig` deliberately only exposes options you're likely to change. For anything else, merge
225
+ tsdown options over the returned config with tsdown's own `mergeConfig` - `defineConfig` returns a
226
+ promise, so `await` it first:
227
+
228
+ ```ts
229
+ import {defineConfig} from '@sanity/tsdown-config'
230
+ import {mergeConfig} from 'tsdown'
231
+
232
+ export default mergeConfig(await defineConfig({tsconfig: 'tsconfig.dist.json'}), {
233
+ // Any tsdown option, e.g. opting out of hashed chunk filenames:
234
+ hash: false,
235
+ })
236
+ ```
package/dist/index.d.mts CHANGED
@@ -1,57 +1,16 @@
1
1
  import { UserConfig } from "tsdown";
2
+ import { Options } from "@sanity/vanilla-extract-tsdown-plugin";
2
3
  import { PluginOptions } from "babel-plugin-react-compiler";
3
- import { Options } from "@vanilla-extract/rollup-plugin";
4
4
  /**
5
- * Options for the `@vanilla-extract/rollup-plugin` integration, including the same extensions as
6
- * `@sanity/pkg-utils` (`minify`, `browserslist`, and `extract.compatMode`).
5
+ * Options for the `vanillaExtract` option — the same options as
6
+ * `@sanity/vanilla-extract-tsdown-plugin` (`identifiers`, `fileName`, `minify`, `target`, and
7
+ * `inject`, all modeled after the `css` options of `@tsdown/css`), with one different default:
8
+ * `inject` defaults to `{nodeCompat: true}` (instead of the plugin's `false`), wiring up the
9
+ * conditional CSS export pattern that Sanity libraries ship with. Set `inject: true` for a plain
10
+ * relative CSS import, or `inject: false` to only extract the CSS.
7
11
  * @public
8
12
  */
9
- interface PackageVanillaExtractOptions extends Omit<Options, "extract"> {
10
- /**
11
- * Minify the extracted CSS with `lightningcss`.
12
- * @defaultValue true
13
- */
14
- minify?: boolean;
15
- /**
16
- * Browserslist query passed to `lightningcss` when optimizing the extracted CSS.
17
- * @defaultValue `@sanity/browserslist-config`
18
- */
19
- browserslist?: string | string[];
20
- /**
21
- * Different formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc).
22
- * @defaultValue "short"
23
- */
24
- identifiers?: Options["identifiers"];
25
- /**
26
- * Extract the CSS into a separate file. The CSS is always extracted, so this configures _how_.
27
- */
28
- extract?: {
29
- /**
30
- * Name of the emitted `.css` file (and, with `compatMode`, the `exports` subpath + shim base).
31
- * @defaultValue "bundle.css"
32
- */
33
- name?: string;
34
- /**
35
- * Generate a `.css.map` sourcemap file.
36
- * @defaultValue true
37
- */
38
- sourcemap?: boolean;
39
- /**
40
- * Compatibility mode automatically wires up the conditional CSS export pattern so userland does
41
- * not have to. When enabled, the config:
42
- *
43
- * - injects `import "<pkg-name>/<name>"` into the `index` entry chunk,
44
- * - emits a no-op `<name>.js` shim for runtimes that cannot import `.css` files, and
45
- * - writes the conditional `"./<name>"` export to `package.json`
46
- * (`browser`/`style` → the real CSS, `node`/`default` → the shim).
47
- *
48
- * The result is that `import "<pkg>/<name>"` resolves to the real CSS in bundlers/browsers and
49
- * to the no-op shim in Node and similar runtimes. Disable it to wire these up yourself.
50
- * @defaultValue true
51
- */
52
- compatMode?: boolean;
53
- };
54
- }
13
+ type PackageVanillaExtractOptions = Options;
55
14
  /**
56
15
  * Options for the `styled-components` transform, the same options as `babel-plugin-styled-components`.
57
16
  * @public
@@ -89,11 +48,26 @@ type ReactCompilerOptions = Partial<PluginOptions>;
89
48
  /**
90
49
  * @public
91
50
  */
92
- interface PackageOptions extends Pick<UserConfig, "tsconfig" | "entry" | "format" | "dts" | "define"> {
51
+ interface PackageOptions extends Pick<UserConfig, "tsconfig" | "entry" | "format" | "dts" | "define" | "target"> {
93
52
  /**
94
53
  * @defaultValue 'neutral'
95
54
  */
96
55
  platform?: UserConfig["platform"];
56
+ /**
57
+ * tsdown's `exports` option, with defaults suited for publishing Sanity libraries:
58
+ * `enabled: 'local-only'` generates the `exports` map during local builds and skips it in CI
59
+ * (where the committed `package.json` is already up to date). When pnpm is detected,
60
+ * `devExports: true` also keeps the local `exports` map pointing at source files while
61
+ * `publishConfig.exports` receives the built files.
62
+ *
63
+ * Userland values apply with tsdown's `mergeConfig` semantics: an object deep-merges over
64
+ * these defaults (so individual fields can be overridden), while any other value - `false`
65
+ * to disable exports generation, or a bare CI condition (`'ci-only'`/`'local-only'`) -
66
+ * replaces them entirely.
67
+ * @defaultValue `{enabled: 'local-only', devExports: true}` for pnpm projects;
68
+ * `{enabled: 'local-only'}` otherwise.
69
+ */
70
+ exports?: UserConfig["exports"];
97
71
  /**
98
72
  * Runs `babel-plugin-react-compiler` on the source files before they are bundled, so published
99
73
  * components are memoized automatically. Pass `true` to use the defaults, or an options object
@@ -113,10 +87,10 @@ interface PackageOptions extends Pick<UserConfig, "tsconfig" | "entry" | "format
113
87
  */
114
88
  styledComponents?: boolean | StyledComponentsOptions;
115
89
  /**
116
- * Enables `@vanilla-extract/rollup-plugin` to extract CSS into a separate file, with support for
117
- * minifying the extracted CSS. Pass `true` to use the defaults, or an object to customize.
90
+ * Enables `@sanity/vanilla-extract-tsdown-plugin` to extract CSS into a separate,
91
+ * `lightningcss`-optimized file. Pass `true` to use the defaults, or an object to customize.
118
92
  *
119
- * By default (`extract.compatMode: true`) the config also injects the self-referential
93
+ * By default (`inject: {nodeCompat: true}`) the plugin also injects the self-referential
120
94
  * `import "<pkg>/bundle.css"`, emits a `bundle.css.js` shim, and writes the conditional
121
95
  * `"./bundle.css"` export to `package.json` - see {@link PackageVanillaExtractOptions}.
122
96
  * This is the same feature as `rollup.vanillaExtract` in `@sanity/pkg-utils`.
@@ -128,5 +102,5 @@ interface PackageOptions extends Pick<UserConfig, "tsconfig" | "entry" | "format
128
102
  * @public
129
103
  */
130
104
  declare function defineConfig(options?: PackageOptions): Promise<UserConfig>;
131
- export { PackageOptions, type PackageVanillaExtractOptions, ReactCompilerOptions, StyledComponentsOptions, defineConfig };
105
+ export { PackageOptions, PackageVanillaExtractOptions, ReactCompilerOptions, StyledComponentsOptions, defineConfig };
132
106
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/vanillaExtract.ts","../src/index.ts"],"mappings":";;;;;;;;UAaiB,qCAAqC,KAAK;;;;;EAKzD;;;;;EAKA;;;;;EAKA,cAAc;;;;EAId;;;;;IAKE;;;;;IAKA;;;;;;;;;;;;;;IAcA;;;;;;;UCzCa;;EAEf;;;;;EAKA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;;;;;;;;;KAUU,uBAAuB,QAAQ;;;;UAK1B,uBAAuB,KACtC;;;;EAMA,WAAW;;;;;;;;;;EAUX,0BAA0B;;;;;;;;EAQ1B,6BAA6B;;;;;;;;;;;EAW7B,2BAA2B;;;;;iBAoCP,aAAa,UAAS,iBAAsB,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;KAmBY,+BAA+B;;;;;UAM1B;;EAEf;;;;;EAKA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA;;;;;;;;;KAUU,uBAAuB,QAAQ;;;;UAK1B,uBAAuB,KACtC;;;;EAMA,WAAW;;;;;;;;;;;;;;;EAeX,UAAU;;;;;;;;;;EAUV,0BAA0B;;;;;;;;EAQ1B,6BAA6B;;;;;;;;;;;EAW7B,2BAA2B;;;;;iBAMP,aAAa,UAAS,iBAAsB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,26 +1,10 @@
1
- import { defineConfig as defineConfig$1 } from "tsdown";
2
- /**
3
- * Emits shared (non-entry) chunks into subfolders per output flavor, following the same naming
4
- * convention as `@sanity/pkg-utils` (`_chunks-es`, `_chunks-cjs` and `_chunks-dts`), instead of
5
- * rolldown's default of placing chunks at the root of the output directory next to the entries.
6
- * A chunk can otherwise be named like an entry (e.g. code shared between `index` and `theme`
7
- * entries forms a chunk that rolldown also names `theme`): the JS output deduplicates such
8
- * filename collisions in favor of the entry, but the d.ts output can resolve them the other way
9
- * around, handing `theme.d.ts` to the chunk - which re-exports everything under minified aliases -
10
- * so every named import from the `theme` entry fails to type-check with TS2460
11
- * (https://github.com/sanity-io/ui/issues/2262).
12
- */
13
- function resolveChunkFileNames(defaultOutputOptions, format) {
14
- return (chunk) => {
15
- let template = (typeof defaultOutputOptions.chunkFileNames == "function" ? defaultOutputOptions.chunkFileNames(chunk) : defaultOutputOptions.chunkFileNames) ?? "[name].js";
16
- return `${chunk.name.endsWith(".d") ? "_chunks-dts" : `_chunks-${format}`}/${template}`;
17
- };
18
- }
1
+ import { detect } from "package-manager-detector/detect";
2
+ import { defineConfig as defineConfig$1, mergeConfig } from "tsdown";
19
3
  /**
20
4
  * @public
21
5
  */
22
6
  async function defineConfig(options = {}) {
23
- let { entry, dts, define } = options, tsconfig = options.tsconfig ?? "tsconfig.json", platform = options.platform ?? "neutral", reactCompiler = options.reactCompiler ?? !1, styledComponents = options.styledComponents ?? !1, report = { gzip: !1 }, format = options.format ?? "esm", inputOptions = {
7
+ let { entry, tsconfig, dts, define, target } = options, platform = options.platform ?? "neutral", reactCompiler = options.reactCompiler ?? !1, styledComponents = options.styledComponents ?? !1, report = { gzip: !1 }, format = options.format ?? "esm", inputOptions = {
24
8
  preserveEntrySignatures: "strict",
25
9
  experimental: { attachDebugInfo: "none" },
26
10
  ...styledComponents !== !1 && { transform: { plugins: { styledComponents: {
@@ -30,69 +14,34 @@ async function defineConfig(options = {}) {
30
14
  cssProp: !1,
31
15
  ...typeof styledComponents == "object" ? styledComponents : {}
32
16
  } } } }
33
- }, resolveBaseOutputOptions = (defaultOptions, outputFormat) => ({
34
- hoistTransitiveImports: !1,
35
- chunkFileNames: resolveChunkFileNames(defaultOptions, outputFormat)
36
- }), outputOptions = resolveBaseOutputOptions, treeshake, customExports, plugins = [];
17
+ }, plugins = [];
37
18
  if (reactCompiler !== !1) {
38
19
  let [{ default: pluginBabel }, { reactCompilerPreset }] = await Promise.all([import("@rolldown/plugin-babel"), import("@vitejs/plugin-react")]);
39
20
  plugins.push(await pluginBabel({ presets: [reactCompilerPreset(typeof reactCompiler == "object" ? reactCompiler : {})] }));
40
21
  }
41
22
  if (options.vanillaExtract) {
42
- let [{ vanillaExtractPlugin }, { default: browserslistConfig }, { optimizeCss }, { bundleCssShim }, { composeIntro, createConditionalCssExport, insertCssExport, readPackageName, resolveVanillaExtract, resolveVanillaExtractCssName }] = await Promise.all([
43
- import("@vanilla-extract/rollup-plugin"),
44
- import("@sanity/browserslist-config"),
45
- import("./_chunks-es/optimizeCss.mjs"),
46
- import("./_chunks-es/bundleCssShim.mjs"),
47
- import("./_chunks-es/vanillaExtract.mjs")
48
- ]), vanillaExtract = resolveVanillaExtract(options.vanillaExtract), cssName = resolveVanillaExtractCssName(vanillaExtract.options);
23
+ let { vanillaExtractPlugin } = await import("@sanity/vanilla-extract-tsdown-plugin");
49
24
  plugins.push(vanillaExtractPlugin({
50
- identifiers: vanillaExtract.options.identifiers ?? "short",
51
- cwd: vanillaExtract.options.cwd,
52
- esbuildOptions: vanillaExtract.options.esbuildOptions,
53
- unstable_injectFilescopes: vanillaExtract.options.unstable_injectFilescopes,
54
- extract: {
55
- name: cssName,
56
- sourcemap: vanillaExtract.options.extract?.sourcemap ?? !0
57
- }
58
- }), optimizeCss({
59
- extractFileName: cssName,
60
- browserslist: vanillaExtract.options.browserslist || browserslistConfig,
61
- minify: vanillaExtract.options.minify ?? !0
62
- })), treeshake = { moduleSideEffects: [{
63
- test: /\.vanilla\.css$/,
64
- external: !0,
65
- sideEffects: !1
66
- }] };
67
- let cssImportId = vanillaExtract.compatMode ? `${readPackageName(process.cwd())}/${cssName}` : void 0;
68
- if (outputOptions = (defaultOptions, outputFormat, context) => ({
69
- ...resolveBaseOutputOptions(defaultOptions, outputFormat),
70
- assetFileNames: "[name][extname]",
71
- ...cssImportId && !context.cjsDts && (outputFormat === "es" || outputFormat === "cjs") ? { intro: composeIntro(outputFormat === "cjs" ? `require(${JSON.stringify(cssImportId)})` : `import ${JSON.stringify(cssImportId)}`) } : {}
72
- }), vanillaExtract.compatMode) {
73
- plugins.push(bundleCssShim({ fileName: `${cssName}.js` }));
74
- let conditionalCssExport = createConditionalCssExport(cssName, "dist");
75
- customExports = (exportsMap) => insertCssExport(exportsMap, `./${cssName}`, conditionalCssExport);
76
- }
25
+ inject: { nodeCompat: !0 },
26
+ ...options.vanillaExtract === !0 ? {} : options.vanillaExtract
27
+ }));
77
28
  }
29
+ let { exports } = mergeConfig({ exports: {
30
+ enabled: "local-only",
31
+ ...(await detect({ cwd: process.cwd() }))?.name === "pnpm" && { devExports: !0 }
32
+ } }, { exports: options.exports });
78
33
  return defineConfig$1({
79
34
  define,
80
35
  dts,
81
36
  entry,
82
- exports: {
83
- enabled: "local-only",
84
- devExports: !0,
85
- ...customExports && { customExports }
86
- },
37
+ exports,
87
38
  format,
88
- hash: !1,
89
39
  inputOptions,
90
- outputOptions,
91
40
  platform,
92
41
  plugins,
93
42
  publint: !0,
94
43
  report,
95
- treeshake,
44
+ target,
96
45
  tsconfig,
97
46
  minify: {
98
47
  compress: !0,
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["defineTsdownConfig"],"sources":["../src/index.ts"],"sourcesContent":["import type {PluginOptions as ReactCompilerPluginOptions} from 'babel-plugin-react-compiler'\nimport {\n defineConfig as defineTsdownConfig,\n type NormalizedFormat,\n type Rolldown,\n type UserConfig,\n} from 'tsdown'\nimport type {PackageVanillaExtractOptions} from './vanillaExtract.ts'\n\nexport type {PackageVanillaExtractOptions}\n\n/**\n * Options for the `styled-components` transform, the same options as `babel-plugin-styled-components`.\n * @public\n */\nexport interface StyledComponentsOptions {\n /** @defaultValue true */\n displayName?: boolean\n /**\n * @defaultValue []\n * @example [\"\\@xstyled/styled-components\", \"\\@xstyled/styled-components/*\"]\n */\n topLevelImportPaths?: string[]\n /** @defaultValue true */\n ssr?: boolean\n /** @defaultValue false */\n fileName?: boolean\n /** @defaultValue [\"index\"] */\n meaninglessFileNames?: string[]\n /** @defaultValue true */\n minify?: boolean\n /** @defaultValue false */\n transpileTemplateLiterals?: boolean\n namespace?: string\n /** @defaultValue true */\n pure?: boolean\n}\n\n/**\n * Options for the React Compiler, the same options as `babel-plugin-react-compiler`.\n * The typings resolve in userland once `babel-plugin-react-compiler` (an optional peer\n * dependency, required to use `reactCompiler`) is installed, and always match the installed\n * version of the compiler.\n * @public\n */\nexport type ReactCompilerOptions = Partial<ReactCompilerPluginOptions>\n\n/**\n * @public\n */\nexport interface PackageOptions extends Pick<\n UserConfig,\n 'tsconfig' | 'entry' | 'format' | 'dts' | 'define'\n> {\n /**\n * @defaultValue 'neutral'\n */\n platform?: UserConfig['platform']\n /**\n * Runs `babel-plugin-react-compiler` on the source files before they are bundled, so published\n * components are memoized automatically. Pass `true` to use the defaults, or an options object\n * to configure the compiler (e.g. `{target: '18'}`).\n * This is the same feature as the `babel: {reactCompiler: true}` and `reactCompilerOptions`\n * options in `@sanity/pkg-utils`. Unlike `styledComponents` there's no oxc native port of the\n * React Compiler yet, so `babel-plugin-react-compiler` needs to be installed.\n * @defaultValue false\n */\n reactCompiler?: boolean | ReactCompilerOptions\n /**\n * Applies the `styled-components` transform (`displayName`, `componentId`, CSS minification, etc)\n * with the same defaults as the `babel: {styledComponents: true}` option in `@sanity/pkg-utils`.\n * Unlike `@sanity/pkg-utils` it doesn't use `babel-plugin-styled-components`, but oxc's native port of it,\n * so there's no need to install babel dependencies.\n * @defaultValue false\n */\n styledComponents?: boolean | StyledComponentsOptions\n /**\n * Enables `@vanilla-extract/rollup-plugin` to extract CSS into a separate file, with support for\n * minifying the extracted CSS. Pass `true` to use the defaults, or an object to customize.\n *\n * By default (`extract.compatMode: true`) the config also injects the self-referential\n * `import \"<pkg>/bundle.css\"`, emits a `bundle.css.js` shim, and writes the conditional\n * `\"./bundle.css\"` export to `package.json` - see {@link PackageVanillaExtractOptions}.\n * This is the same feature as `rollup.vanillaExtract` in `@sanity/pkg-utils`.\n * @alpha\n */\n vanillaExtract?: boolean | PackageVanillaExtractOptions\n}\n\n/**\n * Emits shared (non-entry) chunks into subfolders per output flavor, following the same naming\n * convention as `@sanity/pkg-utils` (`_chunks-es`, `_chunks-cjs` and `_chunks-dts`), instead of\n * rolldown's default of placing chunks at the root of the output directory next to the entries.\n * A chunk can otherwise be named like an entry (e.g. code shared between `index` and `theme`\n * entries forms a chunk that rolldown also names `theme`): the JS output deduplicates such\n * filename collisions in favor of the entry, but the d.ts output can resolve them the other way\n * around, handing `theme.d.ts` to the chunk - which re-exports everything under minified aliases -\n * so every named import from the `theme` entry fails to type-check with TS2460\n * (https://github.com/sanity-io/ui/issues/2262).\n */\nfunction resolveChunkFileNames(\n defaultOutputOptions: Rolldown.OutputOptions,\n format: NormalizedFormat,\n): Rolldown.OutputOptions['chunkFileNames'] {\n return (chunk) => {\n // tsdown's default is a `[name]` template string carrying the resolved output extension for\n // the current format and package type (e.g. `[name].mjs`), so reuse it for the file names\n const template =\n (typeof defaultOutputOptions.chunkFileNames === 'function'\n ? defaultOutputOptions.chunkFileNames(chunk)\n : defaultOutputOptions.chunkFileNames) ?? '[name].js'\n // `rolldown-plugin-dts` names d.ts chunks with a `.d` suffix and later rewrites the rendered\n // JS filename to the matching d.ts extension (e.g. `_chunks-dts/[name].mjs` renders\n // `_chunks-dts/theme.mjs`, which becomes `_chunks-dts/theme.d.mts`)\n const folder = chunk.name.endsWith('.d') ? '_chunks-dts' : `_chunks-${format}`\n return `${folder}/${template}`\n }\n}\n\n/**\n * @public\n */\nexport async function defineConfig(options: PackageOptions = {}): Promise<UserConfig> {\n // `dts` and `define` are passed through to tsdown as-is. When left undefined, tsdown keeps its\n // default behavior (`dts` is auto-detected from `package.json`, `define` replaces nothing).\n const {entry, dts, define} = options\n const tsconfig = options.tsconfig ?? 'tsconfig.json'\n const platform = options.platform ?? 'neutral'\n const reactCompiler = options.reactCompiler ?? false\n const styledComponents = options.styledComponents ?? false\n const report = {gzip: false} as const satisfies UserConfig['report']\n const publint = true\n const hash = false\n const format = options.format ?? 'esm'\n const inputOptions = {\n preserveEntrySignatures: 'strict',\n experimental: {attachDebugInfo: 'none'},\n ...(styledComponents !== false && {\n transform: {\n plugins: {\n styledComponents: {\n // The same defaults as `babel: {styledComponents: true}` in `@sanity/pkg-utils`:\n // `fileName` is unnecessary, as the way we use styled-components in Sanity is usually by wrapping\n // `@sanity/ui` primitives, not declaring new ones like \"const Button = styled.button``\"\n fileName: false,\n // Native template literals take less space than this transpilation, and unlike\n // `babel-plugin-styled-components`, oxc doesn't add a `@__PURE__` annotation to the\n // transpiled call expression either, so enabling it wouldn't improve tree-shaking\n transpileTemplateLiterals: false,\n // Helps dead code elimination and tree-shaking, although oxc only annotates plain call\n // expressions so far, not tagged template expressions (https://github.com/rollup/rollup/issues/4035)\n pure: true,\n // Disabled, as tsdown tends to be used for npm publishing, while other tooling,\n // like `sanity dev`, `next dev`, etc are used for testing\n cssProp: false,\n ...(typeof styledComponents === 'object' ? styledComponents : {}),\n },\n },\n },\n }),\n } as const satisfies UserConfig['inputOptions']\n\n const resolveBaseOutputOptions = (\n defaultOptions: Rolldown.OutputOptions,\n outputFormat: NormalizedFormat,\n ) =>\n ({\n hoistTransitiveImports: false,\n chunkFileNames: resolveChunkFileNames(defaultOptions, outputFormat),\n }) satisfies Rolldown.OutputOptions\n\n let outputOptions: UserConfig['outputOptions'] = resolveBaseOutputOptions\n let treeshake: UserConfig['treeshake']\n let customExports: ((exportsMap: Record<string, unknown>) => Record<string, unknown>) | undefined\n\n const plugins: Rolldown.Plugin[] = []\n if (reactCompiler !== false) {\n // Follows the official tsdown recipe for the React Compiler:\n // https://tsdown.dev/recipes/react-support#enabling-react-compiler\n // The plugins are lazy loaded so they're only paid for when the React Compiler is enabled.\n // `babel-plugin-react-compiler` itself is resolved by Babel from the consumer package during\n // the build, which is why it can be an optional peer dependency. Once rolldown ships its rust\n // port of the React Compiler this can be swapped out for an oxc transform, like `styledComponents`.\n const [{default: pluginBabel}, {reactCompilerPreset}] = await Promise.all([\n import('@rolldown/plugin-babel'),\n import('@vitejs/plugin-react'),\n ])\n plugins.push(\n await pluginBabel({\n presets: [reactCompilerPreset(typeof reactCompiler === 'object' ? reactCompiler : {})],\n }),\n )\n }\n if (options.vanillaExtract) {\n // Everything vanilla-extract related is lazy loaded, like `reactCompiler`, so it's only paid\n // for when the option is enabled: `@vanilla-extract/rollup-plugin` compiles the `.css.ts`\n // files, and `optimizeCss` pulls in the CSS toolchain (`lightningcss`, `browserslist`) that\n // minifies the extracted CSS.\n const [\n {vanillaExtractPlugin},\n {default: browserslistConfig},\n {optimizeCss},\n {bundleCssShim},\n {\n composeIntro,\n createConditionalCssExport,\n insertCssExport,\n readPackageName,\n resolveVanillaExtract,\n resolveVanillaExtractCssName,\n },\n ] = await Promise.all([\n import('@vanilla-extract/rollup-plugin'),\n import('@sanity/browserslist-config'),\n import('./optimizeCss.ts'),\n import('./bundleCssShim.ts'),\n import('./vanillaExtract.ts'),\n ])\n\n // Resolve vanilla-extract options + the conditional CSS export \"compat mode\"\n const vanillaExtract = resolveVanillaExtract(options.vanillaExtract)\n const cssName = resolveVanillaExtractCssName(vanillaExtract.options)\n\n plugins.push(\n // Rolldown supports most Rollup plugins, but the plugin types are not identical, so the\n // official guidance is to cast: https://tsdown.dev/advanced/plugins#rollup-plugins\n // oxlint-disable-next-line no-unsafe-type-assertion\n vanillaExtractPlugin({\n identifiers: vanillaExtract.options.identifiers ?? 'short',\n cwd: vanillaExtract.options.cwd,\n esbuildOptions: vanillaExtract.options.esbuildOptions,\n unstable_injectFilescopes: vanillaExtract.options.unstable_injectFilescopes,\n extract: {\n name: cssName,\n sourcemap: vanillaExtract.options.extract?.sourcemap ?? true,\n },\n }) as unknown as Rolldown.Plugin,\n optimizeCss({\n extractFileName: cssName,\n browserslist: vanillaExtract.options.browserslist || browserslistConfig,\n minify: vanillaExtract.options.minify ?? true,\n }),\n )\n\n // The vanilla-extract plugin resolves each compiled `.css.ts` module's CSS to an external,\n // side-effect-only `<file>.vanilla.css` import and extracts the CSS into a single file. The\n // imports are redundant once the CSS is extracted, so let tree-shaking drop them up front:\n // the plugin's own `generateBundle` cleanup only strips imports at the start of a line, which\n // the minifier's statement merging can defeat (e.g. `a(), require(\"….vanilla.css\")` in CJS).\n // Modules not matching the rule keep the default tree-shaking behavior.\n treeshake = {moduleSideEffects: [{test: /\\.vanilla\\.css$/, external: true, sideEffects: false}]}\n\n // In compat mode, the self-referential `import \"<pkg>/<css>\"` needs the package name.\n const cssImportId = vanillaExtract.compatMode\n ? `${readPackageName(process.cwd())}/${cssName}`\n : undefined\n\n outputOptions = (defaultOptions, outputFormat, context) => ({\n ...resolveBaseOutputOptions(defaultOptions, outputFormat),\n // Emit the extracted CSS (and its sourcemap) with a stable name at the root of the tsdown\n // default `outDir` ('dist', not configurable yet) instead of rolldown's default\n // `assets/[name]-[hash][extname]`, so it can back the conditional `./<css>` export.\n assetFileNames: '[name][extname]',\n // In compat mode, inject the self-referential CSS import into the `index` entry chunk so\n // userland does not need to set `outputOptions.intro` themselves. Use `require()` for\n // CommonJS output (a top-level `import` would be invalid in a `.cjs` bundle).\n ...(cssImportId && !context.cjsDts && (outputFormat === 'es' || outputFormat === 'cjs')\n ? {\n intro: composeIntro(\n outputFormat === 'cjs'\n ? `require(${JSON.stringify(cssImportId)})`\n : `import ${JSON.stringify(cssImportId)}`,\n ),\n }\n : {}),\n })\n\n if (vanillaExtract.compatMode) {\n // In compat mode, emit the no-op JS shim that the `node`/`default` conditions of the\n // `./<css>` export resolve to.\n plugins.push(bundleCssShim({fileName: `${cssName}.js`}))\n\n // Write the conditional `./<css>` export to `package.json` (and, through tsdown, mirror it\n // into `publishConfig.exports`) so userland does not have to maintain it.\n const conditionalCssExport = createConditionalCssExport(cssName, 'dist')\n customExports = (exportsMap) =>\n insertCssExport(exportsMap, `./${cssName}`, conditionalCssExport)\n }\n }\n\n const exports = {\n enabled: 'local-only',\n // @TODO use @sanity/parse-package-json to determine if devExports should be `true` or `source`\n devExports: true,\n ...(customExports && {customExports}),\n } as const satisfies UserConfig['exports']\n\n return defineTsdownConfig({\n define,\n dts,\n entry,\n exports,\n format,\n hash,\n inputOptions,\n outputOptions,\n platform,\n plugins,\n publint,\n report,\n treeshake,\n tsconfig,\n minify: {compress: true, codegen: false, mangle: false},\n // `treeshake` stays `undefined` (tsdown's/rolldown's default, `moduleSideEffects: true`)\n // unless vanilla-extract needs its targeted rule above. Previously this set the equivalent of\n // `moduleSideEffects: 'no-external'` (with a `.css` exemption), which stripped intentional\n // side-effect-only imports of external packages (e.g. `import 'react-time-ago/locale/en'`)\n // from the output. The default preserves those imports while still honoring `package.json`\n // `sideEffects` fields for bundled modules.\n })\n}\n"],"mappings":";;;;;;;;;;;;AAoGA,SAAS,sBACP,sBACA,QAC0C;CAC1C,QAAQ,UAAU;EAGhB,IAAM,YACH,OAAO,qBAAqB,kBAAmB,aAC5C,qBAAqB,eAAe,KAAK,IACzC,qBAAqB,mBAAmB;EAK9C,OAAO,GADQ,MAAM,KAAK,SAAS,IAAI,IAAI,gBAAgB,WAAW,SACrD,GAAG;CACtB;AACF;;;;AAKA,eAAsB,aAAa,UAA0B,CAAC,GAAwB;CAGpF,IAAM,EAAC,OAAO,KAAK,WAAU,SACvB,WAAW,QAAQ,YAAY,iBAC/B,WAAW,QAAQ,YAAY,WAC/B,gBAAgB,QAAQ,iBAAiB,IACzC,mBAAmB,QAAQ,oBAAoB,IAC/C,SAAS,EAAC,MAAM,GAAK,GAGrB,SAAS,QAAQ,UAAU,OAC3B,eAAe;EACnB,yBAAyB;EACzB,cAAc,EAAC,iBAAiB,OAAM;EACtC,GAAI,qBAAqB,MAAS,EAChC,WAAW,EACT,SAAS,EACP,kBAAkB;GAIhB,UAAU;GAIV,2BAA2B;GAG3B,MAAM;GAGN,SAAS;GACT,GAAI,OAAO,oBAAqB,WAAW,mBAAmB,CAAC;EACjE,EACF,EACF,EACF;CACF,GAEM,4BACJ,gBACA,kBAEC;EACC,wBAAwB;EACxB,gBAAgB,sBAAsB,gBAAgB,YAAY;CACpE,IAEE,gBAA6C,0BAC7C,WACA,eAEE,UAA6B,CAAC;CACpC,IAAI,kBAAkB,IAAO;EAO3B,IAAM,CAAC,EAAC,SAAS,eAAc,EAAC,yBAAwB,MAAM,QAAQ,IAAI,CACxE,OAAO,2BACP,OAAO,uBACT,CAAC;EACD,QAAQ,KACN,MAAM,YAAY,EAChB,SAAS,CAAC,oBAAoB,OAAO,iBAAkB,WAAW,gBAAgB,CAAC,CAAC,CAAC,EACvF,CAAC,CACH;CACF;CACA,IAAI,QAAQ,gBAAgB;EAK1B,IAAM,CACJ,EAAC,wBACD,EAAC,SAAS,sBACV,EAAC,eACD,EAAC,iBACD,EACE,cACA,4BACA,iBACA,iBACA,uBACA,kCAEA,MAAM,QAAQ,IAAI;GACpB,OAAO;GACP,OAAO;GACP,OAAO;GACP,OAAO;GACP,OAAO;EACT,CAAC,GAGK,iBAAiB,sBAAsB,QAAQ,cAAc,GAC7D,UAAU,6BAA6B,eAAe,OAAO;EA6BnE,AA3BA,QAAQ,KAIN,qBAAqB;GACnB,aAAa,eAAe,QAAQ,eAAe;GACnD,KAAK,eAAe,QAAQ;GAC5B,gBAAgB,eAAe,QAAQ;GACvC,2BAA2B,eAAe,QAAQ;GAClD,SAAS;IACP,MAAM;IACN,WAAW,eAAe,QAAQ,SAAS,aAAa;GAC1D;EACF,CAAC,GACD,YAAY;GACV,iBAAiB;GACjB,cAAc,eAAe,QAAQ,gBAAgB;GACrD,QAAQ,eAAe,QAAQ,UAAU;EAC3C,CAAC,CACH,GAQA,YAAY,EAAC,mBAAmB,CAAC;GAAC,MAAM;GAAmB,UAAU;GAAM,aAAa;EAAK,CAAC,EAAC;EAG/F,IAAM,cAAc,eAAe,aAC/B,GAAG,gBAAgB,QAAQ,IAAI,CAAC,EAAE,GAAG,YACrC,KAAA;EAsBJ,IApBA,iBAAiB,gBAAgB,cAAc,aAAa;GAC1D,GAAG,yBAAyB,gBAAgB,YAAY;GAIxD,gBAAgB;GAIhB,GAAI,eAAe,CAAC,QAAQ,WAAW,iBAAiB,QAAQ,iBAAiB,SAC7E,EACE,OAAO,aACL,iBAAiB,QACb,WAAW,KAAK,UAAU,WAAW,EAAE,KACvC,UAAU,KAAK,UAAU,WAAW,GAC1C,EACF,IACA,CAAC;EACP,IAEI,eAAe,YAAY;GAG7B,QAAQ,KAAK,cAAc,EAAC,UAAU,GAAG,QAAQ,KAAI,CAAC,CAAC;GAIvD,IAAM,uBAAuB,2BAA2B,SAAS,MAAM;GACvE,iBAAiB,eACf,gBAAgB,YAAY,KAAK,WAAW,oBAAoB;EACpE;CACF;CASA,OAAOA,eAAmB;EACxB;EACA;EACA;EACA,SAAA;GAVA,SAAS;GAET,YAAY;GACZ,GAAI,iBAAiB,EAAC,cAAa;EAO7B;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;GAAC,UAAU;GAAM,SAAS;GAAO,QAAQ;EAAK;CAOxD,CAAC;AACH"}
1
+ {"version":3,"file":"index.mjs","names":["defineTsdownConfig"],"sources":["../src/index.ts"],"sourcesContent":["import type {Options as VanillaExtractPluginOptions} from '@sanity/vanilla-extract-tsdown-plugin'\nimport type {PluginOptions as ReactCompilerPluginOptions} from 'babel-plugin-react-compiler'\nimport {detect} from 'package-manager-detector/detect'\nimport {\n defineConfig as defineTsdownConfig,\n mergeConfig,\n type Rolldown,\n type UserConfig,\n} from 'tsdown'\n\n/**\n * Options for the `vanillaExtract` option — the same options as\n * `@sanity/vanilla-extract-tsdown-plugin` (`identifiers`, `fileName`, `minify`, `target`, and\n * `inject`, all modeled after the `css` options of `@tsdown/css`), with one different default:\n * `inject` defaults to `{nodeCompat: true}` (instead of the plugin's `false`), wiring up the\n * conditional CSS export pattern that Sanity libraries ship with. Set `inject: true` for a plain\n * relative CSS import, or `inject: false` to only extract the CSS.\n * @public\n */\nexport type PackageVanillaExtractOptions = VanillaExtractPluginOptions\n\n/**\n * Options for the `styled-components` transform, the same options as `babel-plugin-styled-components`.\n * @public\n */\nexport interface StyledComponentsOptions {\n /** @defaultValue true */\n displayName?: boolean\n /**\n * @defaultValue []\n * @example [\"\\@xstyled/styled-components\", \"\\@xstyled/styled-components/*\"]\n */\n topLevelImportPaths?: string[]\n /** @defaultValue true */\n ssr?: boolean\n /** @defaultValue false */\n fileName?: boolean\n /** @defaultValue [\"index\"] */\n meaninglessFileNames?: string[]\n /** @defaultValue true */\n minify?: boolean\n /** @defaultValue false */\n transpileTemplateLiterals?: boolean\n namespace?: string\n /** @defaultValue true */\n pure?: boolean\n}\n\n/**\n * Options for the React Compiler, the same options as `babel-plugin-react-compiler`.\n * The typings resolve in userland once `babel-plugin-react-compiler` (an optional peer\n * dependency, required to use `reactCompiler`) is installed, and always match the installed\n * version of the compiler.\n * @public\n */\nexport type ReactCompilerOptions = Partial<ReactCompilerPluginOptions>\n\n/**\n * @public\n */\nexport interface PackageOptions extends Pick<\n UserConfig,\n 'tsconfig' | 'entry' | 'format' | 'dts' | 'define' | 'target'\n> {\n /**\n * @defaultValue 'neutral'\n */\n platform?: UserConfig['platform']\n /**\n * tsdown's `exports` option, with defaults suited for publishing Sanity libraries:\n * `enabled: 'local-only'` generates the `exports` map during local builds and skips it in CI\n * (where the committed `package.json` is already up to date). When pnpm is detected,\n * `devExports: true` also keeps the local `exports` map pointing at source files while\n * `publishConfig.exports` receives the built files.\n *\n * Userland values apply with tsdown's `mergeConfig` semantics: an object deep-merges over\n * these defaults (so individual fields can be overridden), while any other value - `false`\n * to disable exports generation, or a bare CI condition (`'ci-only'`/`'local-only'`) -\n * replaces them entirely.\n * @defaultValue `{enabled: 'local-only', devExports: true}` for pnpm projects;\n * `{enabled: 'local-only'}` otherwise.\n */\n exports?: UserConfig['exports']\n /**\n * Runs `babel-plugin-react-compiler` on the source files before they are bundled, so published\n * components are memoized automatically. Pass `true` to use the defaults, or an options object\n * to configure the compiler (e.g. `{target: '18'}`).\n * This is the same feature as the `babel: {reactCompiler: true}` and `reactCompilerOptions`\n * options in `@sanity/pkg-utils`. Unlike `styledComponents` there's no oxc native port of the\n * React Compiler yet, so `babel-plugin-react-compiler` needs to be installed.\n * @defaultValue false\n */\n reactCompiler?: boolean | ReactCompilerOptions\n /**\n * Applies the `styled-components` transform (`displayName`, `componentId`, CSS minification, etc)\n * with the same defaults as the `babel: {styledComponents: true}` option in `@sanity/pkg-utils`.\n * Unlike `@sanity/pkg-utils` it doesn't use `babel-plugin-styled-components`, but oxc's native port of it,\n * so there's no need to install babel dependencies.\n * @defaultValue false\n */\n styledComponents?: boolean | StyledComponentsOptions\n /**\n * Enables `@sanity/vanilla-extract-tsdown-plugin` to extract CSS into a separate,\n * `lightningcss`-optimized file. Pass `true` to use the defaults, or an object to customize.\n *\n * By default (`inject: {nodeCompat: true}`) the plugin also injects the self-referential\n * `import \"<pkg>/bundle.css\"`, emits a `bundle.css.js` shim, and writes the conditional\n * `\"./bundle.css\"` export to `package.json` - see {@link PackageVanillaExtractOptions}.\n * This is the same feature as `rollup.vanillaExtract` in `@sanity/pkg-utils`.\n * @alpha\n */\n vanillaExtract?: boolean | PackageVanillaExtractOptions\n}\n\n/**\n * @public\n */\nexport async function defineConfig(options: PackageOptions = {}): Promise<UserConfig> {\n // `tsconfig`, `entry`, `dts`, `define` and `target` are passed through to tsdown as-is. When\n // left undefined, tsdown keeps its default behavior (`tsconfig` is auto-detected from the\n // project, `dts` from `package.json`, `define` replaces nothing, and `target` applies no\n // syntax downleveling).\n const {entry, tsconfig, dts, define, target} = options\n const platform = options.platform ?? 'neutral'\n const reactCompiler = options.reactCompiler ?? false\n const styledComponents = options.styledComponents ?? false\n const report = {gzip: false} as const satisfies UserConfig['report']\n const publint = true\n const format = options.format ?? 'esm'\n const inputOptions = {\n // https://github.com/rolldown/rolldown/blob/main/packages/rolldown/src/options/docs/preserve-entry-signatures.md#strict\n preserveEntrySignatures: 'strict',\n experimental: {attachDebugInfo: 'none'},\n ...(styledComponents !== false && {\n transform: {\n plugins: {\n styledComponents: {\n // The same defaults as `babel: {styledComponents: true}` in `@sanity/pkg-utils`:\n // `fileName` is unnecessary, as the way we use styled-components in Sanity is usually by wrapping\n // `@sanity/ui` primitives, not declaring new ones like \"const Button = styled.button``\"\n fileName: false,\n // Native template literals take less space than this transpilation, and unlike\n // `babel-plugin-styled-components`, oxc doesn't add a `@__PURE__` annotation to the\n // transpiled call expression either, so enabling it wouldn't improve tree-shaking\n transpileTemplateLiterals: false,\n // Helps dead code elimination and tree-shaking, although oxc only annotates plain call\n // expressions so far, not tagged template expressions (https://github.com/rollup/rollup/issues/4035)\n pure: true,\n // Disabled, as tsdown tends to be used for npm publishing, while other tooling,\n // like `sanity dev`, `next dev`, etc are used for testing\n cssProp: false,\n ...(typeof styledComponents === 'object' ? styledComponents : {}),\n },\n },\n },\n }),\n } as const satisfies UserConfig['inputOptions']\n\n // `outputOptions` is left to tsdown's defaults - notably chunk filenames keep tsdown's hashed\n // default (unless userland sets `hash`), which prevents chunk/entry filename collisions\n // (https://github.com/sanity-io/ui/issues/2262).\n const plugins: Rolldown.Plugin[] = []\n if (reactCompiler !== false) {\n // Follows the official tsdown recipe for the React Compiler:\n // https://tsdown.dev/recipes/react-support#enabling-react-compiler\n // The plugins are lazy loaded so they're only paid for when the React Compiler is enabled.\n // `babel-plugin-react-compiler` itself is resolved by Babel from the consumer package during\n // the build, which is why it can be an optional peer dependency. Once rolldown ships its rust\n // port of the React Compiler this can be swapped out for an oxc transform, like `styledComponents`.\n const [{default: pluginBabel}, {reactCompilerPreset}] = await Promise.all([\n import('@rolldown/plugin-babel'),\n import('@vitejs/plugin-react'),\n ])\n plugins.push(\n await pluginBabel({\n presets: [reactCompilerPreset(typeof reactCompiler === 'object' ? reactCompiler : {})],\n }),\n )\n }\n if (options.vanillaExtract) {\n // Lazy loaded, like `reactCompiler`, so the CSS toolchain is only paid for when the option is\n // enabled. The plugin compiles the `.css.ts` files and extracts the CSS into a single\n // `lightningcss`-optimized file. Its `inject` option is general purpose (and, like\n // `css.inject` in `@tsdown/css`, disabled by default), so this config supplies the default\n // most Sanity libraries want: `{nodeCompat: true}` wires up the whole conditional CSS export\n // pattern - the self-referential CSS import, the no-op JS shim, and the conditional\n // `./<fileName>` export written through this config's `exports` option (which the plugin's\n // `tsdownConfig` hook composes into).\n const {vanillaExtractPlugin} = await import('@sanity/vanilla-extract-tsdown-plugin')\n plugins.push(\n vanillaExtractPlugin({\n inject: {nodeCompat: true},\n ...(options.vanillaExtract === true ? {} : options.vanillaExtract),\n }),\n )\n }\n\n const packageManager = await detect({cwd: process.cwd()})\n // tsdown's `exports` feature is enabled with Sanity-flavored defaults, and userland values\n // apply with tsdown's own `mergeConfig` semantics: an object deep-merges over the defaults,\n // anything else (`false`, a CI condition) replaces them.\n const {exports} = mergeConfig(\n {\n exports: {\n enabled: 'local-only',\n // Only opt in by default when pnpm is detected: support for replacing package fields\n // from `publishConfig` is not reliable across package managers.\n ...(packageManager?.name === 'pnpm' && {devExports: true}),\n },\n },\n {exports: options.exports},\n )\n\n return defineTsdownConfig({\n define,\n dts,\n entry,\n exports,\n format,\n inputOptions,\n platform,\n plugins,\n publint,\n report,\n target,\n tsconfig,\n minify: {compress: true, codegen: false, mangle: false},\n })\n}\n"],"mappings":";;;;;AAqHA,eAAsB,aAAa,UAA0B,CAAC,GAAwB;CAKpF,IAAM,EAAC,OAAO,UAAU,KAAK,QAAQ,WAAU,SACzC,WAAW,QAAQ,YAAY,WAC/B,gBAAgB,QAAQ,iBAAiB,IACzC,mBAAmB,QAAQ,oBAAoB,IAC/C,SAAS,EAAC,MAAM,GAAK,GAErB,SAAS,QAAQ,UAAU,OAC3B,eAAe;EAEnB,yBAAyB;EACzB,cAAc,EAAC,iBAAiB,OAAM;EACtC,GAAI,qBAAqB,MAAS,EAChC,WAAW,EACT,SAAS,EACP,kBAAkB;GAIhB,UAAU;GAIV,2BAA2B;GAG3B,MAAM;GAGN,SAAS;GACT,GAAI,OAAO,oBAAqB,WAAW,mBAAmB,CAAC;EACjE,EACF,EACF,EACF;CACF,GAKM,UAA6B,CAAC;CACpC,IAAI,kBAAkB,IAAO;EAO3B,IAAM,CAAC,EAAC,SAAS,eAAc,EAAC,yBAAwB,MAAM,QAAQ,IAAI,CACxE,OAAO,2BACP,OAAO,uBACT,CAAC;EACD,QAAQ,KACN,MAAM,YAAY,EAChB,SAAS,CAAC,oBAAoB,OAAO,iBAAkB,WAAW,gBAAgB,CAAC,CAAC,CAAC,EACvF,CAAC,CACH;CACF;CACA,IAAI,QAAQ,gBAAgB;EAS1B,IAAM,EAAC,yBAAwB,MAAM,OAAO;EAC5C,QAAQ,KACN,qBAAqB;GACnB,QAAQ,EAAC,YAAY,GAAI;GACzB,GAAI,QAAQ,mBAAmB,KAAO,CAAC,IAAI,QAAQ;EACrD,CAAC,CACH;CACF;CAMA,IAAM,EAAC,YAAW,YAChB,EACE,SAAS;EACP,SAAS;EAGT,IAAI,MAVmB,OAAO,EAAC,KAAK,QAAQ,IAAI,EAAC,CAAC,EAAA,EAU9B,SAAS,UAAU,EAAC,YAAY,GAAI;CAC1D,EACF,GACA,EAAC,SAAS,QAAQ,QAAO,CAC3B;CAEA,OAAOA,eAAmB;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;GAAC,UAAU;GAAM,SAAS;GAAO,QAAQ;EAAK;CACxD,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/tsdown-config",
3
- "version": "0.13.1",
3
+ "version": "0.14.1",
4
4
  "description": "Shared configuration for tsdown",
5
5
  "keywords": [
6
6
  "sanity-io",
@@ -37,12 +37,10 @@
37
37
  "dependencies": {
38
38
  "@babel/core": "^7.29.7",
39
39
  "@rolldown/plugin-babel": "^0.2.3",
40
- "@sanity/browserslist-config": "^1.0.5",
41
- "@vanilla-extract/rollup-plugin": "^1.5.4",
42
40
  "@vitejs/plugin-react": "^6.0.3",
43
- "browserslist": "^4.28.5",
44
- "lightningcss": "^1.32.0",
45
- "publint": "^0.3.21"
41
+ "package-manager-detector": "^1.7.0",
42
+ "publint": "^0.3.21",
43
+ "@sanity/vanilla-extract-tsdown-plugin": "^0.1.0"
46
44
  },
47
45
  "devDependencies": {
48
46
  "@types/babel__core": "^7.20.5",
@@ -51,12 +49,12 @@
51
49
  "tsdown": "^0.22.5",
52
50
  "typescript": "7.0.2",
53
51
  "vitest": "^4.1.10",
54
- "@sanity/pkg-utils": "^11.0.1",
52
+ "@sanity/pkg-utils": "^11.0.2",
55
53
  "@sanity/tsconfig": "^2.2.0"
56
54
  },
57
55
  "peerDependencies": {
58
56
  "babel-plugin-react-compiler": "*",
59
- "tsdown": "0.22.5",
57
+ "tsdown": "^0.22.5",
60
58
  "typescript": "6.x || 7.x"
61
59
  },
62
60
  "peerDependenciesMeta": {
@@ -1,34 +0,0 @@
1
- /**
2
- * Emits a no-op JavaScript shim (`export default ""`) alongside the extracted CSS. The conditional
3
- * `./<css>` export points its `node`/`default` conditions at this file so that the self-referential
4
- * `import "<pkg>/<css>"` resolves to a harmless module in runtimes that cannot import `.css` files,
5
- * instead of throwing `Error: Unknown file extension ".css"`.
6
- *
7
- * A matching `.d.ts` declaration is emitted next to the shim as well. Both the `browser`/`style`
8
- * (`<css>`) and the `node`/`default` (`<css>.js`) conditions of the `./<css>` export resolve their
9
- * types to the same `<css>.d.ts` file, so type-aware tooling (e.g. dts export checkers that load a
10
- * `.d.ts` for every export target) does not crash on a missing declaration file.
11
- *
12
- * @param options.fileName - The shim file name, e.g. `bundle.css.js`.
13
- * @internal
14
- */
15
- function bundleCssShim(options) {
16
- let cssName = options.fileName.replace(/\.js$/, "");
17
- return {
18
- name: "sanity-tsdown-config:bundle-css-shim",
19
- generateBundle() {
20
- this.emitFile({
21
- type: "asset",
22
- fileName: options.fileName,
23
- source: `// No-op shim for \`${cssName}\` in runtimes that cannot import \`.css\` files directly.\nexport default ""\n`
24
- }), this.emitFile({
25
- type: "asset",
26
- fileName: `${cssName}.d.ts`,
27
- source: `// Type declarations for \`${cssName}\` and its no-op JS shim.\ndeclare const _default: string\nexport default _default\n`
28
- });
29
- }
30
- };
31
- }
32
- export { bundleCssShim };
33
-
34
- //# sourceMappingURL=bundleCssShim.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bundleCssShim.mjs","names":[],"sources":["../../src/bundleCssShim.ts"],"sourcesContent":["import type {Rolldown} from 'tsdown'\n\n/**\n * Emits a no-op JavaScript shim (`export default \"\"`) alongside the extracted CSS. The conditional\n * `./<css>` export points its `node`/`default` conditions at this file so that the self-referential\n * `import \"<pkg>/<css>\"` resolves to a harmless module in runtimes that cannot import `.css` files,\n * instead of throwing `Error: Unknown file extension \".css\"`.\n *\n * A matching `.d.ts` declaration is emitted next to the shim as well. Both the `browser`/`style`\n * (`<css>`) and the `node`/`default` (`<css>.js`) conditions of the `./<css>` export resolve their\n * types to the same `<css>.d.ts` file, so type-aware tooling (e.g. dts export checkers that load a\n * `.d.ts` for every export target) does not crash on a missing declaration file.\n *\n * @param options.fileName - The shim file name, e.g. `bundle.css.js`.\n * @internal\n */\nexport function bundleCssShim(options: {fileName: string}): Rolldown.Plugin {\n const cssName = options.fileName.replace(/\\.js$/, '')\n\n return {\n name: 'sanity-tsdown-config:bundle-css-shim',\n generateBundle() {\n this.emitFile({\n type: 'asset',\n fileName: options.fileName,\n source: `// No-op shim for \\`${cssName}\\` in runtimes that cannot import \\`.css\\` files directly.\\nexport default \"\"\\n`,\n })\n this.emitFile({\n type: 'asset',\n fileName: `${cssName}.d.ts`,\n source: `// Type declarations for \\`${cssName}\\` and its no-op JS shim.\\ndeclare const _default: string\\nexport default _default\\n`,\n })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,SAA8C;CAC1E,IAAM,UAAU,QAAQ,SAAS,QAAQ,SAAS,EAAE;CAEpD,OAAO;EACL,MAAM;EACN,iBAAiB;GAMf,AALA,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,QAAQ;IAClB,QAAQ,uBAAuB,QAAQ;GACzC,CAAC,GACD,KAAK,SAAS;IACZ,MAAM;IACN,UAAU,GAAG,QAAQ;IACrB,QAAQ,8BAA8B,QAAQ;GAChD,CAAC;EACH;CACF;AACF"}
@@ -1,38 +0,0 @@
1
- import { basename } from "node:path";
2
- import browserslist from "browserslist";
3
- import { browserslistToTargets, transform } from "lightningcss";
4
- /**
5
- * Post-processes the CSS file extracted by `@vanilla-extract/rollup-plugin` with `lightningcss`,
6
- * applying browserslist targets and (unless disabled) minification. Ported from the equivalent
7
- * `@sanity/pkg-utils` Rollup plugin.
8
- * @internal
9
- */
10
- function optimizeCss(options) {
11
- return {
12
- name: "sanity-tsdown-config:optimize-css",
13
- async generateBundle(_outputOptions, bundle, _isWrite) {
14
- for (let [fileName, assetOrChunk] of Object.entries(bundle)) if (assetOrChunk.type === "asset") {
15
- let asset = assetOrChunk;
16
- if (asset.fileName === options.extractFileName || asset.originalFileNames.includes(options.extractFileName)) {
17
- let sourceMap = bundle[`${fileName}.map`];
18
- await transformCss(asset, sourceMap?.type === "asset" ? sourceMap : void 0, options.browserslist, options.minify ?? !0);
19
- }
20
- }
21
- }
22
- };
23
- }
24
- async function transformCss(asset, sourceMapAsset, browserslistConfig, minify) {
25
- let css = asset.source.toString(), file = asset.fileName, targets = browserslistToTargets(browserslist(browserslistConfig)), lightningCssResult = transform({
26
- filename: file,
27
- code: Buffer.from(css),
28
- minify,
29
- cssModules: !1,
30
- targets,
31
- sourceMap: !!sourceMapAsset,
32
- inputSourceMap: sourceMapAsset ? sourceMapAsset.source.toString() : void 0
33
- });
34
- lightningCssResult.warnings.length && console.warn(lightningCssResult.warnings), asset.source = new TextDecoder().decode(lightningCssResult.code), sourceMapAsset && lightningCssResult.map && (sourceMapAsset.source = new TextDecoder().decode(lightningCssResult.map), asset.source += `\n/*# sourceMappingURL=${basename(sourceMapAsset.fileName)}*/\n`);
35
- }
36
- export { optimizeCss };
37
-
38
- //# sourceMappingURL=optimizeCss.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"optimizeCss.mjs","names":[],"sources":["../../src/optimizeCss.ts"],"sourcesContent":["import {basename} from 'node:path'\nimport browserslist from 'browserslist'\nimport {browserslistToTargets, transform} from 'lightningcss'\nimport type {Rolldown} from 'tsdown'\n\n/**\n * Post-processes the CSS file extracted by `@vanilla-extract/rollup-plugin` with `lightningcss`,\n * applying browserslist targets and (unless disabled) minification. Ported from the equivalent\n * `@sanity/pkg-utils` Rollup plugin.\n * @internal\n */\nexport function optimizeCss(options: {\n extractFileName: string\n browserslist: string | string[]\n minify?: boolean\n}): Rolldown.Plugin {\n return {\n name: 'sanity-tsdown-config:optimize-css',\n\n async generateBundle(_outputOptions, bundle, _isWrite) {\n for (const [fileName, assetOrChunk] of Object.entries(bundle)) {\n // find the extracted CSS asset\n if (assetOrChunk.type === 'asset') {\n const asset = assetOrChunk\n if (\n asset.fileName === options.extractFileName ||\n asset.originalFileNames.includes(options.extractFileName)\n ) {\n const sourceMap = bundle[`${fileName}.map`]\n await transformCss(\n asset,\n sourceMap?.type === 'asset' ? sourceMap : undefined,\n options.browserslist,\n options.minify ?? true,\n )\n }\n }\n }\n },\n }\n}\n\nasync function transformCss(\n asset: Rolldown.OutputAsset,\n sourceMapAsset: Rolldown.OutputAsset | undefined,\n browserslistConfig: string | string[],\n minify: boolean,\n) {\n const css = asset.source.toString()\n const file = asset.fileName\n\n const targets = browserslistToTargets(browserslist(browserslistConfig))\n\n // process (and, unless disabled, minify) css using lightningcss\n const lightningCssResult = transform({\n filename: file,\n code: Buffer.from(css),\n minify,\n cssModules: false,\n targets,\n sourceMap: !!sourceMapAsset,\n inputSourceMap: sourceMapAsset ? sourceMapAsset.source.toString() : undefined,\n })\n\n if (lightningCssResult.warnings.length) {\n console.warn(lightningCssResult.warnings)\n }\n\n asset.source = new TextDecoder().decode(lightningCssResult.code)\n if (sourceMapAsset && lightningCssResult.map) {\n sourceMapAsset.source = new TextDecoder().decode(lightningCssResult.map)\n asset.source += `\\n/*# sourceMappingURL=${basename(sourceMapAsset.fileName)}*/\\n`\n }\n}\n"],"mappings":";;;;;;;;;AAWA,SAAgB,YAAY,SAIR;CAClB,OAAO;EACL,MAAM;EAEN,MAAM,eAAe,gBAAgB,QAAQ,UAAU;GACrD,KAAK,IAAM,CAAC,UAAU,iBAAiB,OAAO,QAAQ,MAAM,GAE1D,IAAI,aAAa,SAAS,SAAS;IACjC,IAAM,QAAQ;IACd,IACE,MAAM,aAAa,QAAQ,mBAC3B,MAAM,kBAAkB,SAAS,QAAQ,eAAe,GACxD;KACA,IAAM,YAAY,OAAO,GAAG,SAAS;KACrC,MAAM,aACJ,OACA,WAAW,SAAS,UAAU,YAAY,KAAA,GAC1C,QAAQ,cACR,QAAQ,UAAU,EACpB;IACF;GACF;EAEJ;CACF;AACF;AAEA,eAAe,aACb,OACA,gBACA,oBACA,QACA;CACA,IAAM,MAAM,MAAM,OAAO,SAAS,GAC5B,OAAO,MAAM,UAEb,UAAU,sBAAsB,aAAa,kBAAkB,CAAC,GAGhE,qBAAqB,UAAU;EACnC,UAAU;EACV,MAAM,OAAO,KAAK,GAAG;EACrB;EACA,YAAY;EACZ;EACA,WAAW,CAAC,CAAC;EACb,gBAAgB,iBAAiB,eAAe,OAAO,SAAS,IAAI,KAAA;CACtE,CAAC;CAOD,AALI,mBAAmB,SAAS,UAC9B,QAAQ,KAAK,mBAAmB,QAAQ,GAG1C,MAAM,SAAS,IAAI,YAAY,CAAC,CAAC,OAAO,mBAAmB,IAAI,GAC3D,kBAAkB,mBAAmB,QACvC,eAAe,SAAS,IAAI,YAAY,CAAC,CAAC,OAAO,mBAAmB,GAAG,GACvE,MAAM,UAAU,0BAA0B,SAAS,eAAe,QAAQ,EAAE;AAEhF"}
@@ -1,77 +0,0 @@
1
- import path from "node:path";
2
- import { readFileSync } from "node:fs";
3
- /**
4
- * Normalize the `vanillaExtract` option into a consistent shape and resolve whether compatibility
5
- * mode is active.
6
- * @internal
7
- */
8
- function resolveVanillaExtract(value) {
9
- let enabled = !!value, options = value === !0 || !value ? {} : value;
10
- return {
11
- enabled,
12
- options,
13
- compatMode: enabled ? options.extract?.compatMode ?? !0 : !1
14
- };
15
- }
16
- /**
17
- * Resolve the name of the emitted CSS file. Unlike `@sanity/pkg-utils`, tsdown produces a single
18
- * bundle that is shared across runtimes, so there are no runtime-suffixed defaults.
19
- * @internal
20
- */
21
- function resolveVanillaExtractCssName(options) {
22
- return options.extract?.name ?? "bundle.css";
23
- }
24
- /**
25
- * Build the conditional CSS export object that vanilla-extract compat mode expects, e.g.
26
- * ```json
27
- * {
28
- * "browser": "./dist/bundle.css",
29
- * "style": "./dist/bundle.css",
30
- * "node": "./dist/bundle.css.js",
31
- * "default": "./dist/bundle.css.js"
32
- * }
33
- * ```
34
- * @internal
35
- */
36
- function createConditionalCssExport(cssName, outDir) {
37
- let cssFile = `./${outDir}/${cssName}`, shimFile = `./${outDir}/${cssName}.js`;
38
- return {
39
- browser: cssFile,
40
- style: cssFile,
41
- node: shimFile,
42
- default: shimFile
43
- };
44
- }
45
- /**
46
- * Insert (or replace) the `"./<cssName>"` export in an `exports`-shaped map, preserving the
47
- * existing order and placing it before `./package.json` when present. Used with tsdown's
48
- * `exports.customExports` so both `exports` and `publishConfig.exports` receive the entry.
49
- * @internal
50
- */
51
- function insertCssExport(exports, exportKey, conditionalExport) {
52
- let nextExports = {}, inserted = !1;
53
- for (let [key, value] of Object.entries(exports)) key !== exportKey && (key === "./package.json" && !inserted && (nextExports[exportKey] = conditionalExport, inserted = !0), nextExports[key] = value);
54
- return inserted || (nextExports[exportKey] = conditionalExport), nextExports;
55
- }
56
- const RE_DTS = /\.d\.[cm]?ts$/;
57
- /**
58
- * Build an `intro` function that prepends `autoImport` to the `index` entry chunk only. The
59
- * `.d.ts` chunks generated by tsdown share the build, so they are explicitly excluded.
60
- * @internal
61
- */
62
- function composeIntro(autoImport) {
63
- return (chunk) => chunk.isEntry && chunk.name === "index" && !RE_DTS.test(chunk.fileName) ? `${autoImport}\n` : "";
64
- }
65
- /**
66
- * Resolve the package name from `package.json`, required by compat mode to inject the
67
- * self-referential CSS import.
68
- * @internal
69
- */
70
- function readPackageName(cwd) {
71
- let pkgPath = path.resolve(cwd, "package.json"), pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
72
- if (typeof pkg.name != "string" || !pkg.name) throw Error(`Unable to resolve the package name from ${pkgPath}, which is required by \`vanillaExtract\` compat mode to inject the self-referential CSS import. Set \`vanillaExtract: {extract: {compatMode: false}}\` to wire up the CSS export manually.`);
73
- return pkg.name;
74
- }
75
- export { composeIntro, createConditionalCssExport, insertCssExport, readPackageName, resolveVanillaExtract, resolveVanillaExtractCssName };
76
-
77
- //# sourceMappingURL=vanillaExtract.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vanillaExtract.mjs","names":[],"sources":["../../src/vanillaExtract.ts"],"sourcesContent":["import {readFileSync} from 'node:fs'\nimport path from 'node:path'\nimport type {Options as VanillaExtractPluginOptions} from '@vanilla-extract/rollup-plugin'\nimport type {Rolldown} from 'tsdown'\n\n/** The default name of the extracted CSS file. */\nconst DEFAULT_VANILLA_EXTRACT_CSS_NAME = 'bundle.css'\n\n/**\n * Options for the `@vanilla-extract/rollup-plugin` integration, including the same extensions as\n * `@sanity/pkg-utils` (`minify`, `browserslist`, and `extract.compatMode`).\n * @public\n */\nexport interface PackageVanillaExtractOptions extends Omit<VanillaExtractPluginOptions, 'extract'> {\n /**\n * Minify the extracted CSS with `lightningcss`.\n * @defaultValue true\n */\n minify?: boolean\n /**\n * Browserslist query passed to `lightningcss` when optimizing the extracted CSS.\n * @defaultValue `@sanity/browserslist-config`\n */\n browserslist?: string | string[]\n /**\n * Different formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc).\n * @defaultValue \"short\"\n */\n identifiers?: VanillaExtractPluginOptions['identifiers']\n /**\n * Extract the CSS into a separate file. The CSS is always extracted, so this configures _how_.\n */\n extract?: {\n /**\n * Name of the emitted `.css` file (and, with `compatMode`, the `exports` subpath + shim base).\n * @defaultValue \"bundle.css\"\n */\n name?: string\n /**\n * Generate a `.css.map` sourcemap file.\n * @defaultValue true\n */\n sourcemap?: boolean\n /**\n * Compatibility mode automatically wires up the conditional CSS export pattern so userland does\n * not have to. When enabled, the config:\n *\n * - injects `import \"<pkg-name>/<name>\"` into the `index` entry chunk,\n * - emits a no-op `<name>.js` shim for runtimes that cannot import `.css` files, and\n * - writes the conditional `\"./<name>\"` export to `package.json`\n * (`browser`/`style` → the real CSS, `node`/`default` → the shim).\n *\n * The result is that `import \"<pkg>/<name>\"` resolves to the real CSS in bundlers/browsers and\n * to the no-op shim in Node and similar runtimes. Disable it to wire these up yourself.\n * @defaultValue true\n */\n compatMode?: boolean\n }\n}\n\n/** @internal */\nexport interface ResolvedVanillaExtract {\n enabled: boolean\n /** Normalized options (the object form, or `{}` when `vanillaExtract: true`). */\n options: PackageVanillaExtractOptions\n /**\n * Whether to automatically wire up the conditional CSS export pattern (intro import, JS shim, and\n * the `package.json` export). Only `true` when vanilla-extract is enabled.\n */\n compatMode: boolean\n}\n\n/**\n * Normalize the `vanillaExtract` option into a consistent shape and resolve whether compatibility\n * mode is active.\n * @internal\n */\nexport function resolveVanillaExtract(\n value: boolean | PackageVanillaExtractOptions | undefined,\n): ResolvedVanillaExtract {\n const enabled = Boolean(value)\n const options: PackageVanillaExtractOptions = value === true || !value ? {} : value\n const compatMode = enabled ? (options.extract?.compatMode ?? true) : false\n\n return {enabled, options, compatMode}\n}\n\n/**\n * Resolve the name of the emitted CSS file. Unlike `@sanity/pkg-utils`, tsdown produces a single\n * bundle that is shared across runtimes, so there are no runtime-suffixed defaults.\n * @internal\n */\nexport function resolveVanillaExtractCssName(options: PackageVanillaExtractOptions): string {\n return options.extract?.name ?? DEFAULT_VANILLA_EXTRACT_CSS_NAME\n}\n\n/**\n * Build the conditional CSS export object that vanilla-extract compat mode expects, e.g.\n * ```json\n * {\n * \"browser\": \"./dist/bundle.css\",\n * \"style\": \"./dist/bundle.css\",\n * \"node\": \"./dist/bundle.css.js\",\n * \"default\": \"./dist/bundle.css.js\"\n * }\n * ```\n * @internal\n */\nexport function createConditionalCssExport(\n cssName: string,\n outDir: string,\n): Record<string, string> {\n const cssFile = `./${outDir}/${cssName}`\n const shimFile = `./${outDir}/${cssName}.js`\n return {browser: cssFile, style: cssFile, node: shimFile, default: shimFile}\n}\n\n/**\n * Insert (or replace) the `\"./<cssName>\"` export in an `exports`-shaped map, preserving the\n * existing order and placing it before `./package.json` when present. Used with tsdown's\n * `exports.customExports` so both `exports` and `publishConfig.exports` receive the entry.\n * @internal\n */\nexport function insertCssExport(\n exports: Record<string, unknown>,\n exportKey: string,\n conditionalExport: Record<string, string>,\n): Record<string, unknown> {\n const nextExports: Record<string, unknown> = {}\n let inserted = false\n for (const [key, value] of Object.entries(exports)) {\n if (key === exportKey) continue\n if (key === './package.json' && !inserted) {\n nextExports[exportKey] = conditionalExport\n inserted = true\n }\n nextExports[key] = value\n }\n if (!inserted) {\n nextExports[exportKey] = conditionalExport\n }\n return nextExports\n}\n\nconst RE_DTS = /\\.d\\.[cm]?ts$/\n\n/**\n * Build an `intro` function that prepends `autoImport` to the `index` entry chunk only. The\n * `.d.ts` chunks generated by tsdown share the build, so they are explicitly excluded.\n * @internal\n */\nexport function composeIntro(autoImport: string): (chunk: Rolldown.RenderedChunk) => string {\n return (chunk) =>\n chunk.isEntry && chunk.name === 'index' && !RE_DTS.test(chunk.fileName) ? `${autoImport}\\n` : ''\n}\n\n/**\n * Resolve the package name from `package.json`, required by compat mode to inject the\n * self-referential CSS import.\n * @internal\n */\nexport function readPackageName(cwd: string): string {\n const pkgPath = path.resolve(cwd, 'package.json')\n // oxlint-disable-next-line no-unsafe-type-assertion\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as {name?: unknown}\n if (typeof pkg.name !== 'string' || !pkg.name) {\n throw new Error(\n `Unable to resolve the package name from ${pkgPath}, which is required by \\`vanillaExtract\\` compat mode to inject the self-referential CSS import. Set \\`vanillaExtract: {extract: {compatMode: false}}\\` to wire up the CSS export manually.`,\n )\n }\n return pkg.name\n}\n"],"mappings":";;;;;;;AA6EA,SAAgB,sBACd,OACwB;CACxB,IAAM,UAAU,EAAQ,OAClB,UAAwC,UAAU,MAAQ,CAAC,QAAQ,CAAC,IAAI;CAG9E,OAAO;EAAC;EAAS;EAAS,YAFP,UAAW,QAAQ,SAAS,cAAc,KAAQ;CAEjC;AACtC;;;;;;AAOA,SAAgB,6BAA6B,SAA+C;CAC1F,OAAO,QAAQ,SAAS,QAAQ;AAClC;;;;;;;;;;;;;AAcA,SAAgB,2BACd,SACA,QACwB;CACxB,IAAM,UAAU,KAAK,OAAO,GAAG,WACzB,WAAW,KAAK,OAAO,GAAG,QAAQ;CACxC,OAAO;EAAC,SAAS;EAAS,OAAO;EAAS,MAAM;EAAU,SAAS;CAAQ;AAC7E;;;;;;;AAQA,SAAgB,gBACd,SACA,WACA,mBACyB;CACzB,IAAM,cAAuC,CAAC,GAC1C,WAAW;CACf,KAAK,IAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC3C,QAAQ,cACR,QAAQ,oBAAoB,CAAC,aAC/B,YAAY,aAAa,mBACzB,WAAW,KAEb,YAAY,OAAO;CAKrB,OAHK,aACH,YAAY,aAAa,oBAEpB;AACT;AAEA,MAAM,SAAS;;;;;;AAOf,SAAgB,aAAa,YAA+D;CAC1F,QAAQ,UACN,MAAM,WAAW,MAAM,SAAS,WAAW,CAAC,OAAO,KAAK,MAAM,QAAQ,IAAI,GAAG,WAAW,MAAM;AAClG;;;;;;AAOA,SAAgB,gBAAgB,KAAqB;CACnD,IAAM,UAAU,KAAK,QAAQ,KAAK,cAAc,GAE1C,MAAM,KAAK,MAAM,aAAa,SAAS,MAAM,CAAC;CACpD,IAAI,OAAO,IAAI,QAAS,YAAY,CAAC,IAAI,MACvC,MAAU,MACR,2CAA2C,QAAQ,4LACrD;CAEF,OAAO,IAAI;AACb"}