@sanity/tsdown-config 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -0
- package/dist/bundleCssShim.mjs +34 -0
- package/dist/bundleCssShim.mjs.map +1 -0
- package/dist/index.d.mts +65 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +47 -6
- package/dist/index.mjs.map +1 -1
- package/dist/optimizeCss.mjs +38 -0
- package/dist/optimizeCss.mjs.map +1 -0
- package/dist/vanillaExtract.mjs +77 -0
- package/dist/vanillaExtract.mjs.map +1 -0
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -67,3 +67,76 @@ export default defineConfig({
|
|
|
67
67
|
styledComponents: {namespace: 'my-package'},
|
|
68
68
|
})
|
|
69
69
|
```
|
|
70
|
+
|
|
71
|
+
## vanilla-extract
|
|
72
|
+
|
|
73
|
+
The same `vanillaExtract` feature as `@sanity/pkg-utils` is available. It extracts the CSS from
|
|
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:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
pnpm add --save-dev @vanilla-extract/css
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import {defineConfig} from '@sanity/tsdown-config'
|
|
83
|
+
|
|
84
|
+
export default defineConfig({
|
|
85
|
+
tsconfig: 'tsconfig.dist.json',
|
|
86
|
+
vanillaExtract: true,
|
|
87
|
+
})
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
By default a compatibility mode is active that automatically wires up the conditional CSS export
|
|
91
|
+
pattern:
|
|
92
|
+
|
|
93
|
+
- injects the self-referential `import "<pkg>/bundle.css"` into the `index` entry chunk,
|
|
94
|
+
- emits a no-op `bundle.css.js` shim (plus `bundle.css.d.ts`) for runtimes that cannot import
|
|
95
|
+
`.css` files, and
|
|
96
|
+
- writes the conditional `"./bundle.css"` export to `package.json` (`browser`/`style` → the real
|
|
97
|
+
CSS, `node`/`default` → the shim).
|
|
98
|
+
|
|
99
|
+
The result is that `import "<pkg>/bundle.css"` resolves to the real CSS in bundlers/browsers and to
|
|
100
|
+
the no-op shim in Node and similar runtimes. Make sure the extracted CSS survives tree-shaking in
|
|
101
|
+
consumers by adding it to `sideEffects` in `package.json`:
|
|
102
|
+
|
|
103
|
+
```json
|
|
104
|
+
{
|
|
105
|
+
"sideEffects": ["*.css"]
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
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
|
+
|
|
113
|
+
## dts
|
|
114
|
+
|
|
115
|
+
tsdown's [`dts` option](https://tsdown.dev/options/dts) is passed through as-is. By default tsdown
|
|
116
|
+
auto-detects it from `package.json` (it's enabled when a `types` field or a `types` condition in
|
|
117
|
+
`exports` is present). Pass an object to customize how the `.d.ts` files are generated, for example
|
|
118
|
+
to use [`tsgo`](https://github.com/microsoft/typescript-go) (the same feature as the `tsgo` option
|
|
119
|
+
in `@sanity/pkg-utils`, requires `@typescript/native-preview` to be installed):
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import {defineConfig} from '@sanity/tsdown-config'
|
|
123
|
+
|
|
124
|
+
export default defineConfig({
|
|
125
|
+
tsconfig: 'tsconfig.dist.json',
|
|
126
|
+
dts: {tsgo: true},
|
|
127
|
+
})
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## define
|
|
131
|
+
|
|
132
|
+
tsdown's `define` option is also passed through as-is. It replaces global identifiers with constant
|
|
133
|
+
expressions at build time (the same feature as the `define` option in `@sanity/pkg-utils`):
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import {defineConfig} from '@sanity/tsdown-config'
|
|
137
|
+
|
|
138
|
+
export default defineConfig({
|
|
139
|
+
tsconfig: 'tsconfig.dist.json',
|
|
140
|
+
define: {'process.env.NODE_ENV': JSON.stringify('production')},
|
|
141
|
+
})
|
|
142
|
+
```
|
|
@@ -0,0 +1,34 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,57 @@
|
|
|
1
1
|
import { UserConfig } from "tsdown";
|
|
2
2
|
import { PluginOptions } from "babel-plugin-react-compiler";
|
|
3
|
+
import { Options } from "@vanilla-extract/rollup-plugin";
|
|
4
|
+
/**
|
|
5
|
+
* Options for the `@vanilla-extract/rollup-plugin` integration, including the same extensions as
|
|
6
|
+
* `@sanity/pkg-utils` (`minify`, `browserslist`, and `extract.compatMode`).
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
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
|
+
}
|
|
3
55
|
/**
|
|
4
56
|
* Options for the `styled-components` transform, the same options as `babel-plugin-styled-components`.
|
|
5
57
|
* @public
|
|
@@ -37,7 +89,7 @@ type ReactCompilerOptions = Partial<PluginOptions>;
|
|
|
37
89
|
/**
|
|
38
90
|
* @public
|
|
39
91
|
*/
|
|
40
|
-
interface PackageOptions extends Pick<UserConfig, "tsconfig" | "entry" | "format"> {
|
|
92
|
+
interface PackageOptions extends Pick<UserConfig, "tsconfig" | "entry" | "format" | "dts" | "define"> {
|
|
41
93
|
/**
|
|
42
94
|
* @defaultValue 'neutral'
|
|
43
95
|
*/
|
|
@@ -60,10 +112,21 @@ interface PackageOptions extends Pick<UserConfig, "tsconfig" | "entry" | "format
|
|
|
60
112
|
* @defaultValue false
|
|
61
113
|
*/
|
|
62
114
|
styledComponents?: boolean | StyledComponentsOptions;
|
|
115
|
+
/**
|
|
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.
|
|
118
|
+
*
|
|
119
|
+
* By default (`extract.compatMode: true`) the config also injects the self-referential
|
|
120
|
+
* `import "<pkg>/bundle.css"`, emits a `bundle.css.js` shim, and writes the conditional
|
|
121
|
+
* `"./bundle.css"` export to `package.json` - see {@link PackageVanillaExtractOptions}.
|
|
122
|
+
* This is the same feature as `rollup.vanillaExtract` in `@sanity/pkg-utils`.
|
|
123
|
+
* @alpha
|
|
124
|
+
*/
|
|
125
|
+
vanillaExtract?: boolean | PackageVanillaExtractOptions;
|
|
63
126
|
}
|
|
64
127
|
/**
|
|
65
128
|
* @public
|
|
66
129
|
*/
|
|
67
130
|
declare function defineConfig(options?: PackageOptions): Promise<UserConfig>;
|
|
68
|
-
export { PackageOptions, ReactCompilerOptions, StyledComponentsOptions, defineConfig };
|
|
131
|
+
export { PackageOptions, type PackageVanillaExtractOptions, ReactCompilerOptions, StyledComponentsOptions, defineConfig };
|
|
69
132
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/vanillaExtract.ts","../src/index.ts"],"mappings":";;;;;AAaA;;;UAAiB,4BAAA,SAAqC,IAAA,CAAK,OAAA;;;;;EAKzD,MAAA;;;;;EAKA,YAAA;;;;;EAKA,WAAA,GAAc,OAAA;EA4BZ;;AC9CJ;EDsBE,OAAA;;;;;IAKE,IAAA;IChBF;;;;IDqBE,SAAA;ICZF;;AAAA;AAUF;;;;AAA2C;AAK3C;;;;;IDWI,UAAA;EAAA;AAAA;AA3CJ;;;;AAAA,UCHiB,uBAAA;;EAEf,WAAA;EDCoD;;;;ECIpD,mBAAA;;EAEA,GAAA;;EAEA,QAAA;;EAEA,oBAAA;EDiCE;EC/BF,MAAA;;EAEA,yBAAA;EACA,SAAA;;EAEA,IAAA;AAAA;;;;;;;;KAUU,oBAAA,GAAuB,OAAA,CAAQ,aAAA;;AAVzC;AAUF;UAKiB,cAAA,SAAuB,IAAA,CACtC,UAAA;;;AANyC;EAYzC,QAAA,GAAW,UAAA;EAPI;;;;;;;;;EAiBf,aAAA,aAA0B,oBAAA;;;;;;;;EAQ1B,gBAAA,aAA6B,uBAAA;;;;AAWF;AAM7B;;;;;;EANE,cAAA,aAA2B,4BAAA;AAAA;;;;iBAMP,YAAA,CAAa,OAAA,GAAS,cAAA,GAAsB,OAAA,CAAQ,UAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { defineConfig as defineConfig$1 } from "tsdown";
|
|
|
3
3
|
* @public
|
|
4
4
|
*/
|
|
5
5
|
async function defineConfig(options = {}) {
|
|
6
|
-
let { entry } = 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 = {
|
|
6
|
+
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
7
|
preserveEntrySignatures: "strict",
|
|
8
8
|
experimental: { attachDebugInfo: "none" },
|
|
9
9
|
...styledComponents !== !1 && { transform: { plugins: { styledComponents: {
|
|
@@ -13,17 +13,57 @@ async function defineConfig(options = {}) {
|
|
|
13
13
|
cssProp: !1,
|
|
14
14
|
...typeof styledComponents == "object" ? styledComponents : {}
|
|
15
15
|
} } } }
|
|
16
|
-
},
|
|
17
|
-
enabled: "local-only",
|
|
18
|
-
devExports: !0
|
|
19
|
-
}, plugins = [];
|
|
16
|
+
}, baseOutputOptions = { hoistTransitiveImports: !1 }, outputOptions = baseOutputOptions, treeshake, customExports, plugins = [];
|
|
20
17
|
if (reactCompiler !== !1) {
|
|
21
18
|
let [{ default: pluginBabel }, { reactCompilerPreset }] = await Promise.all([import("@rolldown/plugin-babel"), import("@vitejs/plugin-react")]);
|
|
22
19
|
plugins.push(await pluginBabel({ presets: [reactCompilerPreset(typeof reactCompiler == "object" ? reactCompiler : {})] }));
|
|
23
20
|
}
|
|
21
|
+
if (options.vanillaExtract) {
|
|
22
|
+
let [{ vanillaExtractPlugin }, { default: browserslistConfig }, { optimizeCss }, { bundleCssShim }, { composeIntro, createConditionalCssExport, insertCssExport, readPackageName, resolveVanillaExtract, resolveVanillaExtractCssName }] = await Promise.all([
|
|
23
|
+
import("@vanilla-extract/rollup-plugin"),
|
|
24
|
+
import("@sanity/browserslist-config"),
|
|
25
|
+
import("./optimizeCss.mjs"),
|
|
26
|
+
import("./bundleCssShim.mjs"),
|
|
27
|
+
import("./vanillaExtract.mjs")
|
|
28
|
+
]), vanillaExtract = resolveVanillaExtract(options.vanillaExtract), cssName = resolveVanillaExtractCssName(vanillaExtract.options);
|
|
29
|
+
plugins.push(vanillaExtractPlugin({
|
|
30
|
+
identifiers: vanillaExtract.options.identifiers ?? "short",
|
|
31
|
+
cwd: vanillaExtract.options.cwd,
|
|
32
|
+
esbuildOptions: vanillaExtract.options.esbuildOptions,
|
|
33
|
+
unstable_injectFilescopes: vanillaExtract.options.unstable_injectFilescopes,
|
|
34
|
+
extract: {
|
|
35
|
+
name: cssName,
|
|
36
|
+
sourcemap: vanillaExtract.options.extract?.sourcemap ?? !0
|
|
37
|
+
}
|
|
38
|
+
}), optimizeCss({
|
|
39
|
+
extractFileName: cssName,
|
|
40
|
+
browserslist: vanillaExtract.options.browserslist || browserslistConfig,
|
|
41
|
+
minify: vanillaExtract.options.minify ?? !0
|
|
42
|
+
})), treeshake = { moduleSideEffects: [{
|
|
43
|
+
test: /\.vanilla\.css$/,
|
|
44
|
+
external: !0,
|
|
45
|
+
sideEffects: !1
|
|
46
|
+
}] };
|
|
47
|
+
let cssImportId = vanillaExtract.compatMode ? `${readPackageName(process.cwd())}/${cssName}` : void 0;
|
|
48
|
+
if (outputOptions = (_options, outputFormat, context) => ({
|
|
49
|
+
...baseOutputOptions,
|
|
50
|
+
assetFileNames: "[name][extname]",
|
|
51
|
+
...cssImportId && !context.cjsDts && (outputFormat === "es" || outputFormat === "cjs") ? { intro: composeIntro(outputFormat === "cjs" ? `require(${JSON.stringify(cssImportId)})` : `import ${JSON.stringify(cssImportId)}`) } : {}
|
|
52
|
+
}), vanillaExtract.compatMode) {
|
|
53
|
+
plugins.push(bundleCssShim({ fileName: `${cssName}.js` }));
|
|
54
|
+
let conditionalCssExport = createConditionalCssExport(cssName, "dist");
|
|
55
|
+
customExports = (exportsMap) => insertCssExport(exportsMap, `./${cssName}`, conditionalCssExport);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
24
58
|
return defineConfig$1({
|
|
59
|
+
define,
|
|
60
|
+
dts,
|
|
25
61
|
entry,
|
|
26
|
-
exports
|
|
62
|
+
exports: {
|
|
63
|
+
enabled: "local-only",
|
|
64
|
+
devExports: !0,
|
|
65
|
+
...customExports && { customExports }
|
|
66
|
+
},
|
|
27
67
|
format,
|
|
28
68
|
hash: !1,
|
|
29
69
|
inputOptions,
|
|
@@ -32,6 +72,7 @@ async function defineConfig(options = {}) {
|
|
|
32
72
|
plugins,
|
|
33
73
|
publint: !0,
|
|
34
74
|
report,
|
|
75
|
+
treeshake,
|
|
35
76
|
tsconfig,
|
|
36
77
|
minify: {
|
|
37
78
|
compress: !0,
|
package/dist/index.mjs.map
CHANGED
|
@@ -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 {defineConfig as defineTsdownConfig, type Rolldown, type UserConfig} from 'tsdown'\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<UserConfig, 'tsconfig' | 'entry' | 'format'> {\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\n/**\n * @public\n */\nexport async function defineConfig(options: PackageOptions = {}): Promise<UserConfig> {\n const {entry} = 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 const outputOptions = {\n hoistTransitiveImports: false,\n } as const satisfies UserConfig['outputOptions']\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 } as const satisfies UserConfig['exports']\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 // The plugin types don't match when `@rolldown/plugin-babel` resolves its `rolldown` peer\n // dependency to a different version than the one bundled with `tsdown`, so cast it:\n // https://tsdown.dev/advanced/plugins#rollup-plugins\n // oxlint-disable-next-line no-unsafe-type-assertion\n (await pluginBabel({\n presets: [reactCompilerPreset(typeof reactCompiler === 'object' ? reactCompiler : {})],\n })) as unknown as Rolldown.Plugin,\n )\n }\n\n return defineTsdownConfig({\n entry,\n exports,\n format,\n hash,\n inputOptions,\n outputOptions,\n platform,\n plugins,\n publint,\n report,\n tsconfig,\n minify: {compress: true, codegen: false, mangle: false},\n // Rely on tsdown's/rolldown's default tree-shaking (`moduleSideEffects: true`) rather than\n // customizing it. Previously this set the equivalent of `moduleSideEffects: 'no-external'`\n // (with a `.css` exemption), which stripped intentional side-effect-only imports of external\n // packages (e.g. `import 'react-time-ago/locale/en'`) from the output. The default preserves\n // those imports while still honoring `package.json` `sideEffects` fields for bundled modules.\n })\n}\n"],"mappings":";;;;AAsEA,eAAsB,aAAa,UAA0B,CAAC,GAAwB;CACpF,IAAM,EAAC,UAAS,SACV,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,GACM,gBAAgB,EACpB,wBAAwB,GAC1B,GACM,UAAU;EACd,SAAS;EAET,YAAY;CACd,GAEM,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,KAKL,MAAM,YAAY,EACjB,SAAS,CAAC,oBAAoB,OAAO,iBAAkB,WAAW,gBAAgB,CAAC,CAAC,CAAC,EACvF,CAAC,CACH;CACF;CAEA,OAAOA,eAAmB;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;GAAC,UAAU;GAAM,SAAS;GAAO,QAAQ;EAAK;CAMxD,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["defineTsdownConfig"],"sources":["../src/index.ts"],"sourcesContent":["import type {PluginOptions as ReactCompilerPluginOptions} from 'babel-plugin-react-compiler'\nimport {defineConfig as defineTsdownConfig, type Rolldown, type UserConfig} 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 * @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 baseOutputOptions = {\n hoistTransitiveImports: false,\n } as const satisfies UserConfig['outputOptions']\n\n let outputOptions: UserConfig['outputOptions'] = baseOutputOptions\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 // The plugin types don't match when `@rolldown/plugin-babel` resolves its `rolldown` peer\n // dependency to a different version than the one bundled with `tsdown`, so cast it:\n // https://tsdown.dev/advanced/plugins#rollup-plugins\n // oxlint-disable-next-line no-unsafe-type-assertion\n (await pluginBabel({\n presets: [reactCompilerPreset(typeof reactCompiler === 'object' ? reactCompiler : {})],\n })) as unknown as Rolldown.Plugin,\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 = (_options, outputFormat, context) => ({\n ...baseOutputOptions,\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":";;;;AAuFA,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,oBAAoB,EACxB,wBAAwB,GAC1B,GAEI,gBAA6C,mBAC7C,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,KAKL,MAAM,YAAY,EACjB,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,UAAU,cAAc,aAAa;GACpD,GAAG;GAIH,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"}
|
|
@@ -0,0 +1,38 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,77 @@
|
|
|
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
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/tsdown-config",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Shared configuration for tsdown",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity-io",
|
|
@@ -37,7 +37,11 @@
|
|
|
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.3",
|
|
40
42
|
"@vitejs/plugin-react": "^6.0.3",
|
|
43
|
+
"browserslist": "^4.28.4",
|
|
44
|
+
"lightningcss": "^1.32.0",
|
|
41
45
|
"publint": "^0.3.21"
|
|
42
46
|
},
|
|
43
47
|
"devDependencies": {
|
|
@@ -49,7 +53,7 @@
|
|
|
49
53
|
"typescript": "6.0.3",
|
|
50
54
|
"vitest": "^4.1.9",
|
|
51
55
|
"@sanity/pkg-utils": "^10.9.0",
|
|
52
|
-
"@sanity/tsconfig": "^2.
|
|
56
|
+
"@sanity/tsconfig": "^2.2.0"
|
|
53
57
|
},
|
|
54
58
|
"peerDependencies": {
|
|
55
59
|
"babel-plugin-react-compiler": "*",
|