@sanity/pkg-utils 12.0.1 → 12.1.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.
Files changed (34) hide show
  1. package/MIGRATE.md +23 -22
  2. package/README.md +59 -4
  3. package/dist/{buildAction-D-M3KYyN.js → buildAction-BzyCXuxp.js} +10 -6
  4. package/dist/buildAction-BzyCXuxp.js.map +1 -0
  5. package/dist/{checkAction-B8M5CP3j.js → checkAction--wB2oNGm.js} +42 -37
  6. package/dist/checkAction--wB2oNGm.js.map +1 -0
  7. package/dist/cli.js +5 -5
  8. package/dist/index.d.ts +40 -26
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +12 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/{resolveBuildContext-CbwvYKj1.js → resolveBuildContext-clvZ-QQy.js} +30 -7
  13. package/dist/resolveBuildContext-clvZ-QQy.js.map +1 -0
  14. package/dist/{resolveTsdownConfig-CGE_7cMM.js → resolveTsdownConfig-fBDvhjvu.js} +143 -12
  15. package/dist/resolveTsdownConfig-fBDvhjvu.js.map +1 -0
  16. package/dist/watchAction-CEADXNwO.js +117 -0
  17. package/dist/watchAction-CEADXNwO.js.map +1 -0
  18. package/dist/writeBundleCssExports-8AIeBdCf.js +64 -0
  19. package/dist/writeBundleCssExports-8AIeBdCf.js.map +1 -0
  20. package/package.json +9 -8
  21. package/dist/buildAction-D-M3KYyN.js.map +0 -1
  22. package/dist/checkAction-B8M5CP3j.js.map +0 -1
  23. package/dist/createApiExtractorConfig-CJoZqw8e.js +0 -30
  24. package/dist/createApiExtractorConfig-CJoZqw8e.js.map +0 -1
  25. package/dist/createTSDocConfig-ylfirNWP.js +0 -25
  26. package/dist/createTSDocConfig-ylfirNWP.js.map +0 -1
  27. package/dist/getExtractMessagesConfig-CXljwFbQ.js +0 -75
  28. package/dist/getExtractMessagesConfig-CXljwFbQ.js.map +0 -1
  29. package/dist/printExtractMessages-DyaYtByp.js +0 -33
  30. package/dist/printExtractMessages-DyaYtByp.js.map +0 -1
  31. package/dist/resolveBuildContext-CbwvYKj1.js.map +0 -1
  32. package/dist/resolveTsdownConfig-CGE_7cMM.js.map +0 -1
  33. package/dist/watchAction-BQG5_hhl.js +0 -179
  34. package/dist/watchAction-BQG5_hhl.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"getExtractMessagesConfig-CXljwFbQ.js","names":[],"sources":["../src/node/tasks/dts/getExtractMessagesConfig.ts"],"sourcesContent":["import {ExtractorLogLevel, type IExtractorMessagesConfig} from '@microsoft/api-extractor'\nimport type {PkgRuleLevel, PkgTsdocOptions} from '../../core/config/types.ts'\n\nconst LOG_LEVELS: Record<PkgRuleLevel, ExtractorLogLevel> = {\n error: ExtractorLogLevel.Error,\n info: ExtractorLogLevel.Info,\n off: ExtractorLogLevel.None,\n warn: ExtractorLogLevel.Warning,\n}\n\n/** @alpha */\nexport function getExtractMessagesConfig(options: {\n rules: PkgTsdocOptions['rules']\n disabled?: boolean\n}): IExtractorMessagesConfig {\n const {rules, disabled = false} = options\n\n function ruleToLogLevel(\n key: keyof NonNullable<PkgTsdocOptions['rules']>,\n defaultLevel?: ExtractorLogLevel,\n ) {\n const r = rules?.[key]\n\n return r ? LOG_LEVELS[r] : defaultLevel || ExtractorLogLevel.Warning\n }\n\n return {\n compilerMessageReporting: {\n default: {\n logLevel: disabled ? ExtractorLogLevel.None : ExtractorLogLevel.Warning,\n },\n },\n\n extractorMessageReporting: disabled\n ? {\n default: {\n logLevel: ExtractorLogLevel.None,\n addToApiReportFile: false,\n },\n }\n : {\n 'default': {\n logLevel: ExtractorLogLevel.Warning,\n addToApiReportFile: false,\n },\n\n 'ae-forgotten-export': {\n /**\n * This is hardcoded to `none` as it's no longer needed since TypeScript 5.5 https://github.com/microsoft/TypeScript/issues/42873\n * It's hardcoded to `none` since supported by API Extractor when using `module: 'Preserve'` doesn't support it well since `@microsoft/api-extractor` v7.49.0, which upgraded from TS 5.4 to 5.7 internally\n */\n logLevel: ExtractorLogLevel.None,\n addToApiReportFile: false,\n },\n\n 'ae-incompatible-release-tags': {\n logLevel: ruleToLogLevel('ae-incompatible-release-tags', ExtractorLogLevel.Error),\n addToApiReportFile: false,\n },\n\n 'ae-internal-missing-underscore': {\n logLevel: ruleToLogLevel('ae-internal-missing-underscore'),\n addToApiReportFile: false,\n },\n\n 'ae-missing-release-tag': {\n logLevel: ruleToLogLevel('ae-missing-release-tag', ExtractorLogLevel.Error),\n addToApiReportFile: false,\n },\n\n 'ae-wrong-input-file-type': {\n logLevel: ExtractorLogLevel.None,\n addToApiReportFile: false,\n },\n },\n\n tsdocMessageReporting: disabled\n ? {\n default: {\n logLevel: ExtractorLogLevel.None,\n addToApiReportFile: false,\n },\n }\n : {\n 'default': {\n logLevel: ExtractorLogLevel.Warning,\n addToApiReportFile: false,\n },\n\n 'tsdoc-link-tag-unescaped-text': {\n logLevel: ruleToLogLevel('tsdoc-link-tag-unescaped-text', ExtractorLogLevel.Warning),\n addToApiReportFile: false,\n },\n\n 'tsdoc-undefined-tag': {\n logLevel: ruleToLogLevel('tsdoc-undefined-tag', ExtractorLogLevel.Error),\n addToApiReportFile: false,\n },\n\n 'tsdoc-unsupported-tag': {\n logLevel: ruleToLogLevel('tsdoc-unsupported-tag', ExtractorLogLevel.None),\n addToApiReportFile: false,\n },\n },\n }\n}\n"],"mappings":";AAGA,MAAM,aAAsD;CAC1D,OAAO,kBAAkB;CACzB,MAAM,kBAAkB;CACxB,KAAK,kBAAkB;CACvB,MAAM,kBAAkB;AAC1B;;AAGA,SAAgB,yBAAyB,SAGZ;CAC3B,IAAM,EAAC,OAAO,WAAW,OAAS;CAElC,SAAS,eACP,KACA,cACA;EACA,IAAM,IAAI,QAAQ;EAElB,OAAO,IAAI,WAAW,KAAK,gBAAgB,kBAAkB;CAC/D;CAEA,OAAO;EACL,0BAA0B,EACxB,SAAS,EACP,UAAU,WAAW,kBAAkB,OAAO,kBAAkB,QAClE,EACF;EAEA,2BAA2B,WACvB,EACE,SAAS;GACP,UAAU,kBAAkB;GAC5B,oBAAoB;EACtB,EACF,IACA;GACE,SAAW;IACT,UAAU,kBAAkB;IAC5B,oBAAoB;GACtB;GAEA,uBAAuB;;;;;IAKrB,UAAU,kBAAkB;IAC5B,oBAAoB;GACtB;GAEA,gCAAgC;IAC9B,UAAU,eAAe,gCAAgC,kBAAkB,KAAK;IAChF,oBAAoB;GACtB;GAEA,kCAAkC;IAChC,UAAU,eAAe,gCAAgC;IACzD,oBAAoB;GACtB;GAEA,0BAA0B;IACxB,UAAU,eAAe,0BAA0B,kBAAkB,KAAK;IAC1E,oBAAoB;GACtB;GAEA,4BAA4B;IAC1B,UAAU,kBAAkB;IAC5B,oBAAoB;GACtB;EACF;EAEJ,uBAAuB,WACnB,EACE,SAAS;GACP,UAAU,kBAAkB;GAC5B,oBAAoB;EACtB,EACF,IACA;GACE,SAAW;IACT,UAAU,kBAAkB;IAC5B,oBAAoB;GACtB;GAEA,iCAAiC;IAC/B,UAAU,eAAe,iCAAiC,kBAAkB,OAAO;IACnF,oBAAoB;GACtB;GAEA,uBAAuB;IACrB,UAAU,eAAe,uBAAuB,kBAAkB,KAAK;IACvE,oBAAoB;GACtB;GAEA,yBAAyB;IACvB,UAAU,eAAe,yBAAyB,kBAAkB,IAAI;IACxE,oBAAoB;GACtB;EACF;CACN;AACF"}
@@ -1,33 +0,0 @@
1
- import path from "node:path";
2
- import chalk from "chalk";
3
- import { ExtractorLogLevel } from "@microsoft/api-extractor";
4
- function printExtractMessages(ctx, messages) {
5
- let { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === ExtractorLogLevel.Warning);
6
- warnings.length && logger.log();
7
- for (let msg of warnings) {
8
- let sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
9
- msg.messageId !== "TS6307" && logger.log([
10
- chalk.cyan(sourceFilePath || "?"),
11
- `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,
12
- ` - ${chalk.yellow("warning")} ${chalk.gray(msg.messageId)}\n`,
13
- msg.text,
14
- "\n"
15
- ].join(""));
16
- }
17
- let errors = messages.filter((msg) => msg.logLevel === ExtractorLogLevel.Error);
18
- !warnings.length && errors.length && logger.log("");
19
- for (let msg of errors) {
20
- let sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
21
- logger.log([
22
- chalk.cyan(sourceFilePath || "?"),
23
- `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,
24
- ` - ${chalk.red("error")} ${chalk.gray(msg.messageId)}\n`,
25
- msg.text,
26
- "\n"
27
- ].join(""));
28
- }
29
- errors.length && process.exit(1);
30
- }
31
- export { printExtractMessages };
32
-
33
- //# sourceMappingURL=printExtractMessages-DyaYtByp.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"printExtractMessages-DyaYtByp.js","names":[],"sources":["../src/node/printExtractMessages.ts"],"sourcesContent":["import path from 'node:path'\nimport {ExtractorLogLevel, type ExtractorMessage} from '@microsoft/api-extractor'\nimport chalk from 'chalk'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\n\nexport function printExtractMessages(ctx: BuildContext, messages: ExtractorMessage[]): void {\n const {cwd, logger} = ctx\n\n const warnings = messages.filter((msg) => msg.logLevel === ExtractorLogLevel.Warning)\n\n if (warnings.length) {\n logger.log()\n }\n\n for (const msg of warnings) {\n const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath)\n\n if (msg.messageId === 'TS6307') {\n // Ignore this warning:\n // > TS6307: <filename> is not in project file list.\n // > Projects must list all files or use an 'include' pattern.\n continue\n }\n\n logger.log(\n [\n chalk.cyan(sourceFilePath || '?'),\n `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,\n ` - ${chalk.yellow('warning')} ${chalk.gray(msg.messageId)}\\n`,\n msg.text,\n '\\n',\n ].join(''),\n )\n }\n\n const errors: ExtractorMessage[] = messages.filter(\n (msg) => msg.logLevel === ExtractorLogLevel.Error,\n )\n\n if (!warnings.length && errors.length) {\n logger.log('')\n }\n\n for (const msg of errors) {\n const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath)\n\n logger.log(\n [\n chalk.cyan(sourceFilePath || '?'),\n `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,\n ` - ${chalk.red('error')} ${chalk.gray(msg.messageId)}\\n`,\n msg.text,\n '\\n',\n ].join(''),\n )\n }\n\n if (errors.length) {\n process.exit(1)\n }\n}\n"],"mappings":";;;AAKA,SAAgB,qBAAqB,KAAmB,UAAoC;CAC1F,IAAM,EAAC,KAAK,WAAU,KAEhB,WAAW,SAAS,QAAQ,QAAQ,IAAI,aAAa,kBAAkB,OAAO;CAEpF,AAAI,SAAS,UACX,OAAO,IAAI;CAGb,KAAK,IAAM,OAAO,UAAU;EAC1B,IAAM,iBAAiB,IAAI,kBAAkB,KAAK,SAAS,KAAK,IAAI,cAAc;EAE9E,IAAI,cAAc,YAOtB,OAAO,IACL;GACE,MAAM,KAAK,kBAAkB,GAAG;GAChC,IAAI,MAAM,OAAO,IAAI,cAAc,EAAE,GAAG,MAAM,OAAO,IAAI,gBAAgB;GACzE,MAAM,MAAM,OAAO,SAAS,EAAE,GAAG,MAAM,KAAK,IAAI,SAAS,EAAE;GAC3D,IAAI;GACJ;EACF,CAAC,CAAC,KAAK,EAAE,CACX;CACF;CAEA,IAAM,SAA6B,SAAS,QACzC,QAAQ,IAAI,aAAa,kBAAkB,KAC9C;CAEA,AAAI,CAAC,SAAS,UAAU,OAAO,UAC7B,OAAO,IAAI,EAAE;CAGf,KAAK,IAAM,OAAO,QAAQ;EACxB,IAAM,iBAAiB,IAAI,kBAAkB,KAAK,SAAS,KAAK,IAAI,cAAc;EAElF,OAAO,IACL;GACE,MAAM,KAAK,kBAAkB,GAAG;GAChC,IAAI,MAAM,OAAO,IAAI,cAAc,EAAE,GAAG,MAAM,OAAO,IAAI,gBAAgB;GACzE,MAAM,MAAM,IAAI,OAAO,EAAE,GAAG,MAAM,KAAK,IAAI,SAAS,EAAE;GACtD,IAAI;GACJ;EACF,CAAC,CAAC,KAAK,EAAE,CACX;CACF;CAEA,AAAI,OAAO,UACT,QAAQ,KAAK,CAAC;AAElB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolveBuildContext-CbwvYKj1.js","names":["typoMap","extMap","isTruthy","resolvePath"],"sources":["../src/node/core/config/findConfigFile.ts","../src/node/core/config/legacyConfig.ts","../src/node/core/config/loadConfig.ts","../src/node/core/pkg/dependencyPlacement.ts","../src/node/core/pkg/helpers.ts","../src/node/core/pkg/validatePkg.ts","../src/node/core/pkg/loadPkg.ts","../src/node/core/pkg/loadPkgWithReporting.ts","../src/node/core/config/resolveConfigProperty.ts","../src/node/core/defaults.ts","../src/node/core/findCommonPath.ts","../src/node/core/pkg/pkgExt.ts","../src/node/core/pkg/validateExports.ts","../src/node/core/pkg/parseAndValidateExports.ts","../src/node/core/ts/loadTSConfig.ts","../src/node/resolveBrowserTarget.ts","../src/node/resolveNodeTarget.ts","../src/node/strict.ts","../src/node/resolveBuildContext.ts"],"sourcesContent":["import path from 'node:path'\nimport findConfig from 'find-config'\nimport {fileExists} from '../../fileExists.ts'\n\nconst CONFIG_FILE_NAMES = [\n 'package.config.ts',\n 'package.config.js',\n 'package.config.cjs',\n 'package.config.mts',\n 'package.config.mjs',\n]\n\n/** @internal */\nexport function findConfigFile(cwd: string): string | undefined {\n const pkgJsonPath = findConfig('package.json', {cwd})\n\n if (!pkgJsonPath) return undefined\n\n const pkgPath = path.dirname(pkgJsonPath)\n\n for (const fileName of CONFIG_FILE_NAMES) {\n const configPath = path.resolve(pkgPath, fileName)\n\n const exists = fileExists(configPath)\n\n if (exists) {\n return configPath\n }\n }\n\n return undefined\n}\n","/**\n * Migration checks for `package.config.ts` options that were removed or deprecated in v12,\n * when `@sanity/pkg-utils` moved from its rollup/rolldown stack onto `tsdown` +\n * `@sanity/tsdown-config`.\n *\n * Removed options are \"tombstoned\": they stay declared on `PkgConfigOptions` (typed `never`,\n * tagged `@deprecated`) so editors surface the migration path, and the checks below throw a\n * runtime error with copy-pasteable migration instructions when they are set anyway — JS\n * configs bypass the types, and the error text is written to be actionable for humans and\n * agents alike.\n *\n * The checks are gated by the `legacyChecks` option, defaulting to on outside production\n * builds (`process.env.NODE_ENV !== 'production'`) so they add no overhead where migration\n * mistakes can no longer surface.\n */\n\nconst MIGRATION_GUIDE_URL =\n 'https://github.com/sanity-io/pkg-utils/blob/main/packages/@sanity/pkg-utils/MIGRATE.md'\n\ninterface LegacyCheck {\n option: string\n migration: string[]\n}\n\nconst tombstones: LegacyCheck[] = [\n {\n option: 'tsgo',\n migration: [\n 'The `dts` option is now passed through to tsdown as-is. Move the flag into it:',\n '',\n ' // package.config.ts',\n ' export default defineConfig({',\n ' dts: {tsgo: true},',\n ' })',\n ],\n },\n {\n option: 'extract',\n migration: [\n 'TSDoc/release-tag checking is configured with the top-level `tsdoc` option:',\n '',\n ' // extract: {enabled: false} -> tsdoc: false',\n ' // extract: {rules: {...}} -> tsdoc: {rules: {...}}',\n ' // extract: {customTags: [...]} -> tsdoc: {customTags: [...]}',\n '',\n 'Type inlining (`extract.bundledPackages`) follows the bundling decisions now:',\n 'devDependencies that are imported are inlined automatically (types included), and',\n '`deps: {alwaysBundle: [...]}` forces inlining a dependency/peerDependency.',\n '',\n '`extract.checkTypes` has no successor: type generation no longer type-checks',\n '(run `tsc --noEmit` for type checking).',\n ],\n },\n {\n option: 'babel',\n migration: [\n 'The Babel options moved to the top level:',\n '',\n ' // babel: {reactCompiler: true} -> reactCompiler: true',\n ' // babel: {styledComponents: true} -> styledComponents: true',\n '',\n '`styledComponents` now uses oxc\\u2019s native port of `babel-plugin-styled-components`,',\n 'so `babel-plugin-styled-components` can be uninstalled.',\n '',\n 'Custom Babel plugins (`babel.plugins`) run through the `plugins` option instead,',\n 'with a self-installed `@rolldown/plugin-babel`:',\n '',\n ' import pluginBabel from \"@rolldown/plugin-babel\"',\n ' export default defineConfig({',\n ' plugins: [await pluginBabel({plugins: [\"babel-plugin-example\"]})],',\n ' })',\n ],\n },\n {\n option: 'rollup',\n migration: [\n 'The rollup stack was replaced with tsdown:',\n '',\n ' // rollup: {vanillaExtract: true} -> vanillaExtract: true',\n ' // rollup: {plugins: [...]} -> plugins: [...] (rolldown plugins; most',\n ' // Rollup plugins are compatible)',\n '',\n '`rollup.output`, `rollup.treeshake`, `rollup.experimentalLogSideEffects` and',\n '`rollup.hashChunkFileNames` have no successor (chunk filenames are content-hashed now).',\n '',\n '`rollup.optimizeLodash` has no successor either \\u2014 and neither does the implicit',\n 'lodash-import optimization that was applied whenever `lodash` was a dependency.',\n 'Preferably drop lodash altogether (see https://e18e.dev for module replacements like',\n '`es-toolkit`), or import from `lodash-es`, which tree-shakes in consumers without',\n 'build-time rewriting.',\n ],\n },\n {\n option: 'reactCompilerOptions',\n migration: [\n 'Pass the compiler options to `reactCompiler` instead:',\n '',\n ' // babel: {reactCompiler: true}, reactCompilerOptions: {target: \"18\"}',\n ' // becomes:',\n ' reactCompiler: {target: \"18\"}',\n ],\n },\n {\n option: 'jsx',\n migration: [\n 'Configure JSX through `tsconfig.json` \\u2014 the bundler reads it from there:',\n '',\n ' // tsconfig.json',\n ' {\"compilerOptions\": {\"jsx\": \"react-jsx\"}}',\n ],\n },\n {\n option: 'jsxFactory',\n migration: ['Configure JSX through `tsconfig.json` (`compilerOptions.jsxFactory`).'],\n },\n {\n option: 'jsxFragment',\n migration: ['Configure JSX through `tsconfig.json` (`compilerOptions.jsxFragmentFactory`).'],\n },\n {\n option: 'jsxImportSource',\n migration: ['Configure JSX through `tsconfig.json` (`compilerOptions.jsxImportSource`).'],\n },\n]\n\n/**\n * Throws for tombstoned options and warns for grandfathered ones. `config` is the raw loaded\n * config object (before it is narrowed to `PkgConfigOptions`), so removed options are still\n * observable.\n * @internal\n */\nexport function runLegacyConfigChecks(config: Record<string, unknown>): void {\n const legacyChecks =\n typeof config['legacyChecks'] === 'boolean'\n ? config['legacyChecks']\n : process.env['NODE_ENV'] !== 'production'\n\n if (!legacyChecks) return\n\n for (const {option, migration} of tombstones) {\n if (config[option] === undefined) continue\n\n throw new Error(\n [\n `package.config.ts: the \\`${option}\\` option was removed in @sanity/pkg-utils v12.`,\n '',\n ...migration,\n '',\n `Full migration guide: ${MIGRATION_GUIDE_URL}`,\n 'Set `legacyChecks: false` in package.config.ts to skip this validation (it is also',\n 'skipped when NODE_ENV=production).',\n ].join('\\n'),\n )\n }\n\n // `dts` survived, but as a tsdown passthrough object — the old mode strings are tombstoned\n // with value-specific migration instructions.\n const dts = config['dts']\n if (typeof dts === 'string') {\n throw new Error(\n [\n `package.config.ts: \\`dts: '${dts}'\\` was removed in @sanity/pkg-utils v12 — the \\`dts\\``,\n 'option is now passed through to tsdown as-is (an options object, or `false`).',\n '',\n ...(dts === 'rolldown'\n ? [\n \"`dts: 'rolldown'` is the default behavior now: delete the option. Options that\",\n 'accompanied it move into the object, e.g. `tsgo: true` becomes `dts: {tsgo: true}`.',\n ]\n : [\n \"`dts: 'api-extractor'` type generation was removed. Types are generated with\",\n 'tsdown (rolldown-plugin-dts); api-extractor remains as the TSDoc/release-tag',\n 'checking that runs during `pkg check` — configure it with the `tsdoc` option.',\n ]),\n '',\n `Full migration guide: ${MIGRATION_GUIDE_URL}`,\n 'Set `legacyChecks: false` in package.config.ts to skip this validation (it is also',\n 'skipped when NODE_ENV=production).',\n ].join('\\n'),\n )\n }\n\n // Grandfathered: `external` still works (mapped onto tsdown's `deps`), with a nudge toward\n // its successor.\n if (config['external'] !== undefined) {\n // eslint-disable-next-line no-console -- config-load-time deprecation warning\n console.warn(\n [\n 'package.config.ts: `external` is deprecated. Use `deps: {neverBundle: [...]}` to mark',\n 'dependencies as external, and `deps: {alwaysBundle: [...]}` to bundle a dependency',\n '(the callback pattern that filtered entries out of the defaults).',\n ].join('\\n'),\n )\n }\n}\n","import path from 'node:path'\nimport {pathToFileURL} from 'node:url'\nimport {tsImport} from 'tsx/esm/api'\nimport {findConfigFile} from './findConfigFile.ts'\nimport {runLegacyConfigChecks} from './legacyConfig.ts'\nimport type {PkgConfigOptions} from './types.ts'\n\n/** @alpha */\nexport async function loadConfig(options: {\n cwd: string\n pkgPath: string\n}): Promise<PkgConfigOptions | undefined> {\n const {cwd, pkgPath} = options\n\n const root = path.dirname(pkgPath)\n\n const configFile = findConfigFile(root)\n\n if (!configFile) {\n return undefined\n }\n\n // Do not accept config files outside of the root\n if (!configFile.startsWith(cwd)) {\n return undefined\n }\n\n const mod = await tsImport(pathToFileURL(configFile).toString(), import.meta.url)\n\n const config = mod?.default || mod || undefined\n\n if (config && typeof config === 'object') {\n runLegacyConfigChecks(config)\n }\n\n return config\n}\n","import type {PackageJSON} from '@sanity/parse-package-json'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\n\n/**\n * The `package.json` fields a dependency placement rule can reference.\n */\ntype DependencyField = 'dependencies' | 'devDependencies' | 'peerDependencies'\n\n/**\n * Describes where a given package may, and may not, be declared in `package.json`.\n */\ninterface DependencyPlacementRule {\n /** The name of the package this rule applies to. */\n name: string\n /** The `strictOptions` toggle that controls whether this rule runs. */\n option: keyof StrictOptions\n /** Fields the package must _not_ be declared in. */\n disallowedIn: DependencyField[]\n /** Fields the package is allowed to be declared in (used for messaging). */\n allowedIn: DependencyField[]\n /**\n * When set and the package is declared in `peerDependencies`, the version range must be\n * exactly this value (e.g. `*` for `@types/*` packages).\n */\n requiredPeerVersion?: string\n}\n\n/**\n * The set of dependency placement rules enforced in `--strict` mode.\n */\nconst dependencyPlacementRules: DependencyPlacementRule[] = [\n {\n name: 'react-is',\n option: 'noReactIsPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: '@sanity/ui',\n option: 'noSanityUiPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: '@sanity/icons',\n option: 'noSanityIconsPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: 'sanity',\n option: 'noSanityDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: 'styled-components',\n option: 'noStyledComponentsDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: 'react',\n option: 'noReactDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: 'react-dom',\n option: 'noReactDomDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: '@types/react',\n option: 'noReactTypesDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n requiredPeerVersion: '*',\n },\n {\n name: '@types/react-dom',\n option: 'noReactDomTypesDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n requiredPeerVersion: '*',\n },\n {\n name: '@types/node',\n option: 'noNodeTypesDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n requiredPeerVersion: '*',\n },\n {\n name: 'rxjs',\n option: 'noRxjsPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: '@sanity/client',\n option: 'noSanityClientPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n]\n\nfunction formatFields(fields: DependencyField[]): string {\n const labels = fields.map((field) => `\\`${field}\\``)\n\n if (labels.length <= 1) {\n return labels.join('')\n }\n\n return `${labels.slice(0, -1).join(', ')} or ${labels[labels.length - 1]}`\n}\n\n/**\n * Validates that well-known packages are declared in the correct `package.json` dependency\n * fields. Returns `true` if any rule with severity `error` was violated.\n * @internal\n */\nexport function checkDependencyPlacement(options: {\n pkg: PackageJSON\n logger: Logger\n strictOptions: StrictOptions\n}): boolean {\n const {pkg, logger, strictOptions} = options\n let shouldError = false\n\n const report = (level: 'error' | 'warn', message: string) => {\n if (level === 'error') {\n shouldError = true\n logger.error(message)\n } else {\n logger.warn(message)\n }\n }\n\n for (const rule of dependencyPlacementRules) {\n const level = strictOptions[rule.option]\n\n if (level === 'off') {\n continue\n }\n\n for (const field of rule.disallowedIn) {\n if (Object.hasOwn(pkg[field] ?? {}, rule.name)) {\n report(\n level,\n `package.json: \\`${rule.name}\\` should not be in \\`${field}\\`. It should be in ${formatFields(\n rule.allowedIn,\n )} instead.`,\n )\n }\n }\n\n if (rule.requiredPeerVersion !== undefined) {\n const peerDependencies = pkg.peerDependencies ?? {}\n\n if (\n Object.hasOwn(peerDependencies, rule.name) &&\n peerDependencies[rule.name] !== rule.requiredPeerVersion\n ) {\n report(\n level,\n `package.json: \\`${rule.name}\\` in \\`peerDependencies\\` should be set to \"${rule.requiredPeerVersion}\" (got \"${peerDependencies[rule.name]}\").`,\n )\n }\n }\n }\n\n return shouldError\n}\n","/** @internal */\nexport function assertLast<T>(a: T, arr: T[]): boolean {\n const aIdx = arr.indexOf(a)\n\n // if not found, then we don't care\n if (aIdx === -1) {\n return true\n }\n\n return aIdx === arr.length - 1\n}\n\n/** @internal */\nexport function assertOrder<T>(a: T, b: T, arr: T[]): boolean {\n const aIdx = arr.indexOf(a)\n const bIdx = arr.indexOf(b)\n\n // if either is not found, then we don't care\n if (aIdx === -1 || bIdx === -1) {\n return true\n }\n\n return aIdx < bIdx\n}\n","import {parsePackage, _typoMap as typoMap, type PackageJSON} from '@sanity/parse-package-json'\n\nexport function validatePkg(input: unknown): PackageJSON {\n const pkg = parsePackage(input)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- Need to check raw input for typos\n const invalidKey = Object.keys(input as PackageJSON).find((key) => {\n const needle = key.toUpperCase()\n\n return typoMap.has(needle) ? typoMap.get(needle) !== key : false\n })\n\n if (invalidKey) {\n throw new TypeError(\n `\n- package.json: \"${invalidKey}\" is not a valid key. Did you mean \"${typoMap.get(invalidKey.toUpperCase())}\"?`,\n )\n }\n\n return pkg\n}\n","import fs from 'node:fs/promises'\nimport type {PackageJSON} from '@sanity/parse-package-json'\nimport {validatePkg} from './validatePkg.ts'\n\n/** @internal */\nexport async function loadPkg(options: {pkgPath: string}): Promise<PackageJSON> {\n const {pkgPath} = options\n\n const raw = JSON.parse(await fs.readFile(pkgPath, 'utf-8'))\n\n validatePkg(raw)\n\n return raw\n}\n","import {ZodError, type PackageJSON} from '@sanity/parse-package-json'\nimport chalk from 'chalk'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\nimport {checkDependencyPlacement} from './dependencyPlacement.ts'\nimport {assertLast, assertOrder} from './helpers.ts'\nimport {loadPkg} from './loadPkg.ts'\n\n/**\n * Helper function to recursively compare export values, excluding source, development, and monorepo conditions\n */\nfunction areExportValuesEqual(value1: unknown, value2: unknown): boolean {\n // If both are strings, simple comparison\n if (typeof value1 === 'string' && typeof value2 === 'string') {\n return value1 === value2\n }\n\n // If types don't match, they're not equal\n if (typeof value1 !== typeof value2) {\n return false\n }\n\n // Both are objects, compare recursively\n if (\n typeof value1 === 'object' &&\n value1 !== null &&\n typeof value2 === 'object' &&\n value2 !== null &&\n !Array.isArray(value1) &&\n !Array.isArray(value2)\n ) {\n const obj1 = value1 as Record<string, any>\n const obj2 = value2 as Record<string, any>\n\n const keys1 = Object.keys(obj1).filter(\n (k) => k !== 'source' && k !== 'development' && k !== 'monorepo',\n )\n const keys2 = Object.keys(obj2).filter(\n (k) => k !== 'source' && k !== 'development' && k !== 'monorepo',\n )\n\n // Check if they have the same keys\n if (keys1.length !== keys2.length) {\n return false\n }\n\n for (const key of keys1) {\n if (!keys2.includes(key)) {\n return false\n }\n\n const val1 = obj1[key]\n const val2 = obj2[key]\n\n // Skip if either value is undefined\n if (val1 === undefined || val2 === undefined) {\n return false\n }\n\n // Recursively compare nested values\n if (!areExportValuesEqual(val1, val2)) {\n return false\n }\n }\n\n return true\n }\n\n return false\n}\n\n/** @alpha */\nexport async function loadPkgWithReporting(options: {\n pkgPath: string\n logger: Logger\n strict: boolean\n strictOptions: StrictOptions\n}): Promise<PackageJSON> {\n const {pkgPath, logger, strict, strictOptions} = options\n\n try {\n const pkg = await loadPkg({pkgPath})\n let shouldError = false\n\n if (strict) {\n // Check for missing or commonjs type field\n if (strictOptions.preferModuleType !== 'off') {\n if (!pkg.type) {\n const msg =\n 'package.json: `type` field is missing. Future versions of pkg-utils will require `\"type\": \"module\"`. Consider adding `\"type\": \"module\"` to prepare for this change.'\n if (strictOptions.preferModuleType === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n } else if (pkg.type === 'commonjs') {\n const msg =\n 'package.json: `type` is set to \"commonjs\". Future versions of pkg-utils will require `\"type\": \"module\"`. Consider migrating to ES modules to prepare for this change.'\n if (strictOptions.preferModuleType === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n }\n\n // Check for banned root-level fields\n if (strictOptions.noPackageJsonBrowser !== 'off' && pkg.browser) {\n const msg =\n 'package.json: the `browser` field is no longer needed. Use the `browser` condition in `exports` instead for better support across modern bundlers.'\n if (strictOptions.noPackageJsonBrowser === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n if (strictOptions.noPackageJsonTypesVersions !== 'off' && pkg.typesVersions) {\n const msg =\n 'package.json: the `typesVersions` field is no longer needed. TypeScript has long supported conditional exports and the `types` condition. Remove the `typesVersions` field and use the `types` condition in `exports` instead.'\n if (strictOptions.noPackageJsonTypesVersions === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n // Check that well-known packages are declared in the correct dependency fields\n if (checkDependencyPlacement({pkg, logger, strictOptions})) {\n shouldError = true\n }\n }\n\n // validate exports\n if (pkg.exports) {\n const _exports = Object.entries(pkg.exports)\n\n for (const [expPath, exp] of _exports) {\n // Skip plain string exports, svelte exports, and conditional CSS exports (a flat\n // condition -> path map at a `.css` subpath); none of these use standard export conditions.\n if (typeof exp === 'string' || expPath.endsWith('.css') || 'svelte' in exp) {\n continue\n }\n\n const keys = Object.keys(exp)\n\n if (exp.types) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`types\\` condition shouldn't be used as dts files are generated in such a way that both CJS and ESM is supported`,\n )\n }\n\n if (exp.module) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`module\\` condition shouldn't be used as it's not well supported in all bundlers.`,\n )\n }\n\n if (exp.development && exp.source && exp.development !== exp.source) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`development\\` condition must have the same value as \\`source\\` when both are present. Expected \"${exp.source}\" but got \"${exp.development}\"`,\n )\n }\n\n if (exp.monorepo && exp.source && exp.monorepo !== exp.source) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`monorepo\\` condition must have the same value as \\`source\\` when both are present. Expected \"${exp.source}\" but got \"${exp.monorepo}\"`,\n )\n }\n\n if (exp.node) {\n if (exp.import && exp.node.import && !assertOrder('node', 'import', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node\\` property should come before the \\`import\\` property`,\n )\n }\n\n if (exp.node.module) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.module\\` condition shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the \"dual package hazard\"`,\n )\n }\n\n if (\n !exp.node.source &&\n exp.node.import &&\n (exp.node.require || exp.require) &&\n (exp.node.import.endsWith('.cjs.js') || exp.node.import.endsWith('.cjs.mjs'))\n ) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.import\\` re-export pattern shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the \"dual package hazard\"`,\n )\n }\n\n if (exp.require && exp.node.require && exp.require === exp.node.require) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.require\\` property isn't necessary as it's identical to \\`require\\``,\n )\n } else if (exp.require && exp.node.require && !assertOrder('node', 'require', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node\\` property should come before the \\`require\\` property`,\n )\n }\n } else {\n if (!assertOrder('import', 'require', keys)) {\n logger.warn(\n `exports[\"${expPath}\"]: the \\`import\\` property should come before the \\`require\\` property`,\n )\n }\n }\n\n if (!assertLast('default', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`default\\` property should be the last property`,\n )\n }\n }\n }\n\n // validate publishConfig.exports\n if (strict && pkg.exports && Object.keys(pkg.exports).length > 0) {\n // Check if exports contains source, development, or monorepo conditions\n const hasSourceOrDevelopment = Object.entries(pkg.exports).some(([, exp]) => {\n if (typeof exp === 'string') return false\n if (typeof exp === 'object' && 'svelte' in exp) return false\n return Boolean(exp.source || exp.development || exp.monorepo)\n })\n\n if (hasSourceOrDevelopment) {\n if (!pkg.publishConfig?.exports) {\n const msg =\n 'package.json: `publishConfig.exports` is missing. Adding it helps avoid publishing to npm with the `source`, `development`, or `monorepo` condition that points to code that cannot be used by the resolver. ' +\n 'See https://tsdown.dev/options/package-exports#dev-exports for more information.'\n if (strictOptions.noPublishConfigExports === 'error') {\n shouldError = true\n logger.error(msg)\n } else if (strictOptions.noPublishConfigExports !== 'off') {\n logger.warn(msg)\n }\n } else {\n // Validate publishConfig.exports structure\n const publishExports = pkg.publishConfig.exports\n\n // Check that all keys in exports exist in publishConfig.exports\n for (const exportPath of Object.keys(pkg.exports)) {\n if (!(exportPath in publishExports)) {\n shouldError = true\n logger.error(\n `publishConfig.exports: missing export path \"${exportPath}\" that exists in exports`,\n )\n }\n }\n\n // Check that all keys in publishConfig.exports exist in exports\n for (const exportPath of Object.keys(publishExports)) {\n if (!(exportPath in pkg.exports)) {\n shouldError = true\n logger.error(\n `publishConfig.exports: unexpected export path \"${exportPath}\" that does not exist in exports`,\n )\n }\n }\n\n // Validate each export path\n for (const [exportPath, exp] of Object.entries(pkg.exports)) {\n if (typeof exp === 'string' || 'svelte' in exp) {\n // For string or svelte exports, publishConfig should match\n const publishExp = publishExports[exportPath]\n if (\n typeof publishExp !== 'string' &&\n (typeof publishExp !== 'object' || !('svelte' in publishExp))\n ) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should be a string matching exports[\"${exportPath}\"]`,\n )\n }\n continue\n }\n\n const publishExp = publishExports[exportPath]\n if (!publishExp) {\n continue\n }\n if (typeof publishExp === 'string') {\n // publishConfig has a string, validate it's correct\n // It should be a condensed form when only default remains after removing source/development/monorepo\n const conditions = Object.keys(exp).filter(\n (k) => k !== 'source' && k !== 'development' && k !== 'monorepo',\n )\n if (conditions.length !== 1 || conditions[0] !== 'default') {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: is a string but exports[\"${exportPath}\"] has multiple conditions besides source/development/monorepo: ${conditions.join(', ')}`,\n )\n } else {\n // Validate that the string value matches the default condition value\n const expectedValue = exp.default\n if (publishExp !== expectedValue) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should be \"${expectedValue}\" but got \"${publishExp}\"`,\n )\n }\n }\n continue\n }\n\n if ('svelte' in publishExp) {\n continue\n }\n\n // Validate conditions\n const exportConditions = Object.keys(exp).filter(\n (k) => k !== 'source' && k !== 'development' && k !== 'monorepo',\n )\n const publishConditions = Object.keys(publishExp)\n\n // Check for source, development, or monorepo in publishConfig\n if ('source' in publishExp) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should not contain the \\`source\\` condition`,\n )\n }\n\n if ('development' in publishExp) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should not contain the \\`development\\` condition`,\n )\n }\n\n if ('monorepo' in publishExp) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should not contain the \\`monorepo\\` condition`,\n )\n }\n\n // Check that all conditions match (except source/development/monorepo)\n for (const condition of exportConditions) {\n if (!(condition in publishExp)) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: missing \\`${condition}\\` condition that exists in exports[\"${exportPath}\"]`,\n )\n }\n }\n\n for (const condition of publishConditions) {\n if (!exportConditions.includes(condition)) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: unexpected \\`${condition}\\` condition that does not exist in exports[\"${exportPath}\"]`,\n )\n }\n }\n\n // Validate that values match for all conditions\n for (const condition of exportConditions) {\n if (condition in publishExp) {\n const exportValue = (exp as Record<string, unknown>)[condition]\n const publishValue = (publishExp as Record<string, unknown>)[condition]\n\n // Compare values recursively for nested objects\n if (!areExportValuesEqual(exportValue, publishValue)) {\n const exportValueStr =\n typeof exportValue === 'string' ? exportValue : JSON.stringify(exportValue)\n const publishValueStr =\n typeof publishValue === 'string' ? publishValue : JSON.stringify(publishValue)\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"].${condition}: should be ${exportValueStr} but got ${publishValueStr}`,\n )\n }\n }\n }\n }\n }\n }\n }\n\n if (shouldError) {\n process.exit(1)\n }\n\n return pkg\n } catch (err) {\n if (err instanceof ZodError) {\n for (const issue of err.issues) {\n if (issue.code === 'invalid_type') {\n logger.error(\n [\n `\\`${formatPath(issue.path)}\\` `,\n `in \\`./package.json\\` must be of type ${chalk.magenta(issue.expected)} `,\n `(received ${chalk.magenta(issue.received)})`,\n ].join(''),\n )\n continue\n }\n\n logger.error(issue)\n }\n } else {\n logger.error(err)\n }\n\n return process.exit(1)\n }\n}\n\nfunction formatPath(segments: Array<string | number>) {\n return segments\n .map((s, idx) => {\n if (idx === 0) return s\n\n if (typeof s === 'number') {\n return `[${s}]`\n }\n\n if (s.startsWith('.')) {\n return `[\"${s}\"]`\n }\n\n return `.${s}`\n })\n .join('')\n}\n","import type {PkgConfigProperty, PkgConfigPropertyResolver} from './types.ts'\n\nfunction isPkgConfigPropertyResolver<T>(\n prop: PkgConfigProperty<T>,\n): prop is PkgConfigPropertyResolver<T> {\n return typeof prop === 'function'\n}\n\n/** @internal */\nexport function resolveConfigProperty<T>(\n prop: PkgConfigProperty<T> | undefined,\n initialValue: T,\n): T {\n if (!prop) return initialValue\n\n if (isPkgConfigPropertyResolver(prop)) {\n return prop(initialValue)\n }\n\n return prop\n}\n","import config from '@sanity/browserslist-config'\n\n/** @public */\nexport const DEFAULT_BROWSERSLIST_QUERY: string[] = config\n","import path from 'node:path'\n\nexport function pathContains(containerPath: string, itemPath: string): boolean {\n return !path.relative(containerPath, itemPath).startsWith('..')\n}\n\nexport function findCommonDirPath(filePaths: string[]): string | undefined {\n let ret: string | undefined = undefined\n\n for (const filePath of filePaths) {\n let dirPath = path.dirname(filePath)\n\n if (!ret) {\n ret = dirPath\n continue\n }\n\n while (dirPath !== ret) {\n if (pathContains(dirPath, ret)) {\n ret = dirPath\n break\n }\n\n dirPath = path.dirname(dirPath)\n\n if (dirPath === ret) {\n break\n }\n\n if (dirPath === '.') return undefined\n }\n }\n\n return ret\n}\n","/** Matches the JS output file endings pkg-utils emits (`.js`, `.mjs`, `.cjs`). @internal */\nexport const fileEnding: RegExp = /\\.[mc]?js$/\n/** @internal */\nexport const defaultEnding = '.js'\nconst mjsEnding = '.mjs'\nconst cjsEnding = '.cjs'\n\n/** @internal */\nexport interface PkgExtMap {\n commonjs: {commonjs: string; esm: string}\n module: {commonjs: string; esm: string}\n}\n\n/** @internal */\nexport const pkgExtMap: PkgExtMap = {\n // pkg.type: \"commonjs\"\n commonjs: {\n commonjs: defaultEnding,\n esm: mjsEnding,\n },\n\n // pkg.type: \"module\"\n module: {\n commonjs: cjsEnding,\n esm: defaultEnding,\n },\n}\n","import type {PackageJSON} from '@sanity/parse-package-json'\nimport type {PkgExport} from '../config/types.ts'\nimport {pkgExtMap as extMap} from './pkgExt.ts'\n\nexport function validateExports(\n _exports: (PkgExport & {_path: string})[],\n options: {pkg: PackageJSON},\n): string[] {\n const {pkg} = options\n const type = pkg.type || 'commonjs'\n const ext = extMap[type]\n\n const errors: string[] = []\n\n for (const exp of _exports) {\n if (exp._path === '.') {\n if (exp.require && pkg.main && exp.require !== pkg.main) {\n errors.push(\n 'package.json: mismatch between \"main\" and \"exports.require\". These must be equal.',\n )\n }\n\n if (exp.import && pkg.module && exp.import !== pkg.module) {\n errors.push(\n 'package.json: mismatch between \"module\" and \"exports.import\". These must be equal.',\n )\n }\n }\n if (exp.require && !exp.require.endsWith(ext.commonjs)) {\n errors.push(\n `package.json with \\`type: \"${type}\"\\` - \\`exports[\"${exp._path}\"].require\\` must end with \"${ext.commonjs}\"`,\n )\n }\n\n if (exp.import && !exp.import.endsWith(ext.esm)) {\n errors.push(\n `package.json with \\`type: \"${type}\"\\` - \\`exports[\"${exp._path}\"].import\\` must end with \"${ext.esm}\"`,\n )\n }\n }\n\n return errors\n}\n","import {existsSync} from 'node:fs'\nimport {resolve as resolvePath} from 'node:path'\nimport {parseExports, type PackageJSON} from '@sanity/parse-package-json'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\nimport type {PkgExport} from '../config/types.ts'\nimport {isRecord} from '../isRecord.ts'\nimport {defaultEnding, fileEnding, pkgExtMap} from './pkgExt.ts'\nimport {validateExports} from './validateExports.ts'\n\n// Type guard to filter out falsy values\nfunction isTruthy<T>(value: T | false | null | undefined | 0 | ''): value is T {\n return Boolean(value)\n}\n\n/** @alpha */\nexport function parseAndValidateExports(options: {\n cwd: string\n pkg: PackageJSON\n strict: boolean\n strictOptions: StrictOptions\n logger: Logger\n}): (PkgExport & {_path: string})[] {\n const {cwd, pkg, strict, strictOptions, logger} = options\n const type = pkg.type || 'commonjs'\n const errors: string[] = []\n\n const report = (kind: 'warn' | 'error', message: string) => {\n if (kind === 'warn') {\n logger.warn(message)\n } else {\n errors.push(message)\n }\n }\n\n if (!Array.isArray(pkg.files) && strict && strictOptions.alwaysPackageJsonFiles !== 'off') {\n report(\n strictOptions.alwaysPackageJsonFiles,\n 'package.json: `files` should be used over `.npmignore`',\n )\n }\n\n if (pkg.source) {\n if (\n strict &&\n pkg.exports?.['.'] &&\n typeof pkg.exports['.'] === 'object' &&\n 'source' in pkg.exports['.'] &&\n pkg.exports['.'].source === pkg.source\n ) {\n errors.push(\n 'package.json: the \"source\" property can be removed, as it is equal to exports[\".\"].source.',\n )\n } else if (!pkg.exports && pkg.main) {\n const extMap = pkgExtMap[type]\n const importExport = pkg.main.replace(fileEnding, extMap.esm)\n const requireExport = pkg.main.replace(fileEnding, extMap.commonjs)\n const defaultExport = pkg.main.replace(fileEnding, defaultEnding)\n\n const maybeBrowserCondition = []\n\n if (pkg.browser) {\n const browserConditions = []\n\n if (pkg.module && pkg.browser?.[pkg.module]) {\n browserConditions.push(\n ` \"import\": ${JSON.stringify(pkg.browser[pkg.module]!.replace(fileEnding, extMap.esm))}`,\n )\n } else if (pkg.browser?.[pkg.main]) {\n browserConditions.push(\n ` \"import\": ${JSON.stringify(pkg.browser[pkg.main]!.replace(fileEnding, extMap.esm))}`,\n )\n }\n\n if (pkg.browser?.[pkg.main]) {\n browserConditions.push(\n ` \"require\": ${JSON.stringify(pkg.browser[pkg.main]!.replace(fileEnding, extMap.commonjs))}`,\n )\n }\n\n if (browserConditions.length) {\n maybeBrowserCondition.push(\n ` \"browser\": {`,\n ` \"source\": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,\n ...browserConditions,\n ` }`,\n )\n }\n }\n\n errors.push(\n ...[\n 'package.json: `exports` are missing, it should be:',\n `\"exports\": {`,\n ` \".\": {`,\n ` \"source\": ${JSON.stringify(pkg.source)},`,\n // If browser conditions are detected then add them to the suggestion\n ...(maybeBrowserCondition.length > 0 ? maybeBrowserCondition : []),\n type === 'commonjs' && ` \"import\": ${JSON.stringify(importExport)},`,\n type === 'module' && ` \"require\": ${JSON.stringify(requireExport)},`,\n ` \"default\": ${JSON.stringify(defaultExport)}`,\n ` },`,\n ` \"./package.json\": \"./package.json\"`,\n `}`,\n ].filter(isTruthy),\n )\n }\n }\n\n if (errors.length) {\n throw new Error('\\n- ' + errors.join('\\n- '))\n }\n\n if (!pkg.exports) {\n throw new Error(\n '\\n- ' +\n [\n 'package.json: `exports` are missing, please set a minimal configuration, for example:',\n `\"exports\": {`,\n ` \".\": {`,\n ` \"source\": \"./src/index.js\",`,\n ` \"default\": \"./dist/index.js\"`,\n ` },`,\n ` \"./package.json\": \"./package.json\"`,\n `}`,\n ].join('\\n- '),\n )\n }\n\n const _exports = parseExports({pkg})\n\n if (strict && strictOptions.noPackageJsonTypings !== 'off' && 'typings' in pkg) {\n report(strictOptions.noPackageJsonTypings, 'package.json: `typings` should be `types`')\n }\n\n if (\n strict &&\n strictOptions.alwaysPackageJsonTypes !== 'off' &&\n !pkg.types &&\n typeof pkg.exports?.['.'] === 'object' &&\n 'source' in pkg.exports['.'] &&\n pkg.exports['.'].source?.endsWith('.ts')\n ) {\n report(\n strictOptions.alwaysPackageJsonTypes,\n 'package.json: `types` must be declared for the npm listing to show as a TypeScript module.',\n )\n }\n\n if (strict && !pkg.exports['./package.json']) {\n errors.push('package.json: `exports[\"./package.json\"] must be declared.')\n }\n\n for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {\n if (\n exportPath.endsWith('.json') ||\n (typeof exportEntry === 'string' && exportEntry.endsWith('.json'))\n ) {\n if (exportPath === './package.json') {\n if (exportEntry !== './package.json') {\n errors.push('package.json: `exports[\"./package.json\"]` must be \"./package.json\".')\n }\n }\n } else if (exportPath.endsWith('.css')) {\n if (typeof exportEntry === 'string') {\n if (!existsSync(resolvePath(cwd, exportEntry))) {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: file does not exist.`,\n )\n }\n } else if (isRecord(exportEntry)) {\n // Conditional CSS export, e.g.\n // \"./bundle.css\": { \"types\": \"./dist/bundle-css.d.ts\", \"browser\": \"./dist/bundle.css\", \"node\": \"./dist/bundle-css.js\", \"default\": \"./dist/bundle-css.js\" }\n // This lets a package re-add a `import \"<pkg>/bundle.css\"` that resolves to the real CSS in\n // bundler/browser environments and to a no-op JS shim in CSS-unaware runtimes (e.g. Node).\n // Only the shape is validated here: the targets usually point at generated `dist` files that\n // do not exist yet at validation time, so file existence is intentionally not checked.\n for (const [condition, target] of Object.entries(exportEntry)) {\n if (typeof target !== 'string') {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}][${JSON.stringify(condition)}]\\`: must be a string path.`,\n )\n }\n }\n } else {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: must be a string path or an object of export conditions.`,\n )\n }\n } else if (isRecord(exportEntry) && 'svelte' in exportEntry) {\n // @TODO should we report a warning or a debug message here about a detected svelte export that is ignored?\n } else if (isPkgExport(exportEntry)) {\n const exp = {\n _exported: true,\n _path: exportPath,\n ...exportEntry,\n } satisfies PkgExport & {_path: string}\n\n // Infer the `default` condition based on the `type` and other conditions\n if (!exp.default) {\n const fallback = type === 'module' ? exp.import : exp.require\n\n if (fallback) {\n exp.default = fallback\n }\n }\n\n // Infer the `require` condition based on the `type` and other conditions\n if (!exp.require && type === 'commonjs' && exp.default) {\n exp.require = exp.default\n }\n\n // Infer the `import` condition based on the `type` and other conditions\n if (!exp.import && type === 'module' && exp.default) {\n exp.import = exp.default\n }\n\n if (exportPath === '.') {\n if (exportEntry.require && pkg.main && exportEntry.require !== pkg.main) {\n errors.push(\n 'package.json: mismatch between \"main\" and \"exports.require\". These must be equal.',\n )\n }\n\n if (exportEntry.import && pkg.module && exportEntry.import !== pkg.module) {\n errors.push(\n 'package.json: mismatch between \"module\" and \"exports.import\" These must be equal.',\n )\n }\n }\n } else if (!isRecord(exportEntry)) {\n errors.push('package.json: exports must be an object')\n }\n }\n\n errors.push(...validateExports(_exports, {pkg}))\n\n if (errors.length) {\n throw new Error('\\n- ' + errors.join('\\n- '))\n }\n\n return _exports\n}\n\nfunction isPkgExport(value: unknown): value is PkgExport {\n return isRecord(value) && 'source' in value && typeof value['source'] === 'string'\n}\n","// The JS compiler API is loaded from the official `@typescript/typescript6` compat package\n// instead of the `typescript` peer dependency, as TypeScript 7 (the Go-native compiler) no longer\n// ships it\nimport ts from '@typescript/typescript6'\n\n/** @internal */\nexport async function loadTSConfig(options: {\n cwd: string\n tsconfigPath: string\n}): Promise<ReturnType<typeof ts.parseJsonConfigFileContent> | undefined> {\n const {cwd, tsconfigPath} = options\n\n // oxlint-disable-next-line unbound-method\n const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath)\n\n if (!configPath) {\n return undefined\n }\n\n // oxlint-disable-next-line unbound-method\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile)\n\n return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd)\n}\n","export function resolveBrowserTarget(versions: string[]): string[] | undefined {\n const target: string[] = versions.filter(\n (version) =>\n version.startsWith('chrome') ||\n version.startsWith('edge') ||\n version.startsWith('firefox') ||\n version.startsWith('ios') ||\n version.startsWith('safari') ||\n version.startsWith('opera'),\n )\n\n if (target.length === 0) {\n return undefined\n }\n\n return target\n}\n","export function resolveNodeTarget(versions: string[]): string[] | undefined {\n const target: string[] = versions.filter((version) => version.startsWith('node'))\n\n if (target.length === 0) {\n return undefined\n }\n\n return target\n}\n","import {errorMap} from 'zod-validation-error/v3'\nimport {z} from 'zod/v3'\n\nconst toggle = z.union([z.literal('error'), z.literal('warn'), z.literal('off')])\n\ntype ToggleType = 'error' | 'warn' | 'off'\n\nconst strictOptions = z\n .object({\n noPackageJsonTypings: toggle.default('error'),\n noImplicitSideEffects: toggle.default('warn'),\n noImplicitBrowsersList: toggle.default('warn'),\n alwaysPackageJsonTypes: toggle.default('error'),\n alwaysPackageJsonFiles: toggle.default('error'),\n noCheckTypes: toggle.default('warn'),\n noPackageJsonBrowser: toggle.default('warn'),\n noPackageJsonTypesVersions: toggle.default('warn'),\n preferModuleType: toggle.default('warn'),\n noPublishConfigExports: toggle.default('warn'),\n noReactIsPeerDependency: toggle.default('error'),\n noSanityUiPeerDependency: toggle.default('error'),\n noSanityIconsPeerDependency: toggle.default('error'),\n noSanityDependency: toggle.default('error'),\n noStyledComponentsDependency: toggle.default('error'),\n noReactDependency: toggle.default('error'),\n noReactDomDependency: toggle.default('error'),\n noReactTypesDependency: toggle.default('error'),\n noReactDomTypesDependency: toggle.default('error'),\n noNodeTypesDependency: toggle.default('error'),\n noRxjsPeerDependency: toggle.default('error'),\n noSanityClientPeerDependency: toggle.default('error'),\n })\n .strict()\n\n/**\n * To make error message paths line up with the paths in package.config.ts the schema is hoisted into a root schema\n * This way errors will say `Expected boolean, received string at \"strict.noPackageJsonTypings\"` instead of `Expected boolean, received string at \"noPackageJsonTypings\"`.\n */\nconst validationSchema = z.object({\n strictOptions: strictOptions.default({}),\n})\n\n/**\n * @public\n */\nexport interface StrictOptions {\n /**\n * Disallows a top level `typings` field in `package.json` if it is equal to `exports['.'].source`.\n * @defaultValue 'error'\n */\n noPackageJsonTypings: ToggleType\n /**\n * Requires specifying `sideEffects` in `package.json`.\n * @defaultValue 'warn'\n */\n noImplicitSideEffects: ToggleType\n /**\n * Requires specifying `browserslist` in `package.json`, instead of relying on it implicitly being:\n * @example\n * ```\n * \"browserslist\": \"extends @sanity/browserslist-config\"\n * ```\n * @defaultValue 'warn'\n */\n noImplicitBrowsersList: ToggleType\n /**\n * If typescript is used then `types` in `package.json` should be specified for npm listings to show the TS icon.\n * @defaultValue 'error'\n */\n alwaysPackageJsonTypes: ToggleType\n /**\n * Using `.npmignore` is error prone, it's best practice to always declare `files` instead\n * @defaultValue 'error'\n */\n alwaysPackageJsonFiles: ToggleType\n /**\n * It's slow to perform type checking while generating dts files, so it's best practice to disable it with a `\"noCheck\": true` in the tsconfig.json file used by `package.config.ts`\n * @defaultValue 'warn'\n */\n noCheckTypes: ToggleType\n /**\n * Disallows the `browser` field in `package.json` as the `browser` condition in `exports` is better supported.\n * @defaultValue 'warn'\n */\n noPackageJsonBrowser: ToggleType\n /**\n * Disallows the `typesVersions` field in `package.json` as TypeScript has long supported conditional exports and the `types` condition.\n * @defaultValue 'warn'\n */\n noPackageJsonTypesVersions: ToggleType\n /**\n * Warns if `type` field is missing or set to `commonjs`. Future versions will require `\"type\": \"module\"`.\n * @defaultValue 'warn'\n */\n preferModuleType: ToggleType\n /**\n * Warns if `publishConfig.exports` is missing when `source`, `development`, or `monorepo` conditions are used in exports.\n * @defaultValue 'warn'\n */\n noPublishConfigExports: ToggleType\n /**\n * Disallows `react-is` in `peerDependencies`. It should be in `dependencies` (or `devDependencies`) instead.\n * @defaultValue 'error'\n */\n noReactIsPeerDependency: ToggleType\n /**\n * Disallows `@sanity/ui` in `peerDependencies`. It should be in `dependencies` (or `devDependencies`) instead.\n * @defaultValue 'error'\n */\n noSanityUiPeerDependency: ToggleType\n /**\n * Disallows `@sanity/icons` in `peerDependencies`. It should be in `dependencies` (or `devDependencies`) instead.\n * @defaultValue 'error'\n */\n noSanityIconsPeerDependency: ToggleType\n /**\n * Disallows `sanity` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noSanityDependency: ToggleType\n /**\n * Disallows `styled-components` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noStyledComponentsDependency: ToggleType\n /**\n * Disallows `react` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noReactDependency: ToggleType\n /**\n * Disallows `react-dom` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noReactDomDependency: ToggleType\n /**\n * Disallows `@types/react` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`, and when declared as a peer dependency the version range should be `*`.\n * @defaultValue 'error'\n */\n noReactTypesDependency: ToggleType\n /**\n * Disallows `@types/react-dom` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`, and when declared as a peer dependency the version range should be `*`.\n * @defaultValue 'error'\n */\n noReactDomTypesDependency: ToggleType\n /**\n * Disallows `@types/node` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`, and when declared as a peer dependency the version range should be `*`.\n * @defaultValue 'error'\n */\n noNodeTypesDependency: ToggleType\n /**\n * Disallows `rxjs` in `peerDependencies`. It should only be in `dependencies` and/or `devDependencies`.\n * @defaultValue 'error'\n */\n noRxjsPeerDependency: ToggleType\n /**\n * Disallows `@sanity/client` in `peerDependencies`. It should only be in `dependencies` and/or `devDependencies`.\n * @defaultValue 'error'\n */\n noSanityClientPeerDependency: ToggleType\n}\n\n/** @alpha */\nexport function parseStrictOptions(input: unknown): StrictOptions {\n return validationSchema.parse({strictOptions: input}, {errorMap}).strictOptions\n}\n","import path from 'node:path'\nimport type {PackageJSON} from '@sanity/parse-package-json'\nimport browserslistToEsbuild from 'browserslist-to-esbuild'\nimport {resolveConfigProperty} from './core/config/resolveConfigProperty.ts'\nimport {type PkgConfigOptions, type PkgExports, type PkgRuntime} from './core/config/types.ts'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\nimport {DEFAULT_BROWSERSLIST_QUERY} from './core/defaults.ts'\nimport {findCommonDirPath, pathContains} from './core/findCommonPath.ts'\nimport {parseAndValidateExports} from './core/pkg/parseAndValidateExports.ts'\nimport {loadTSConfig} from './core/ts/loadTSConfig.ts'\nimport type {Logger} from './logger.ts'\nimport {resolveBrowserTarget} from './resolveBrowserTarget.ts'\nimport {resolveNodeTarget} from './resolveNodeTarget.ts'\nimport {parseStrictOptions} from './strict.ts'\n\n// Type guard to filter out falsy values\nfunction isTruthy<T>(value: T | false | null | undefined | 0 | ''): value is T {\n return Boolean(value)\n}\n\nexport async function resolveBuildContext(options: {\n config?: PkgConfigOptions | undefined\n cwd: string\n emitDeclarationOnly?: boolean\n logger: Logger\n pkg: PackageJSON\n strict: boolean\n tsconfig: string\n}): Promise<BuildContext> {\n const {\n config,\n cwd,\n emitDeclarationOnly = false,\n logger,\n pkg,\n strict,\n tsconfig: tsconfigPath,\n } = options\n const tsconfig = await loadTSConfig({cwd, tsconfigPath})\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n\n let browserslist = pkg.browserslist\n if (!browserslist) {\n if (strict && strictOptions.noImplicitBrowsersList !== 'off') {\n if (strictOptions.noImplicitBrowsersList === 'error') {\n throw new Error(\n '\\n- ' +\n `package.json: \"browserslist\" is missing, set it to \\`\"browserslist\": \"extends @sanity/browserslist-config\"\\``,\n )\n } else {\n logger.warn(\n 'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `\"browserslist\": \"extends @sanity/browserslist-config\"` to silence this warning.',\n )\n }\n }\n browserslist = DEFAULT_BROWSERSLIST_QUERY\n }\n const targetVersions = browserslistToEsbuild(browserslist)\n\n if (\n strict &&\n strictOptions.noImplicitSideEffects !== 'off' &&\n typeof pkg.sideEffects === 'undefined'\n ) {\n const msg =\n 'package.json: `sideEffects` is missing, see https://webpack.js.org/guides/tree-shaking/#clarifying-tree-shaking-and-sideeffects for how to define `sideEffects`'\n\n if (strictOptions.noImplicitSideEffects === 'error') {\n throw new Error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n const nodeTarget = resolveNodeTarget(targetVersions)\n const webTarget = resolveBrowserTarget(targetVersions)\n\n if (!nodeTarget) {\n throw new Error('no matching `node` target')\n }\n\n if (!webTarget) {\n throw new Error('no matching `web` target')\n }\n\n const target: Record<PkgRuntime, string[]> = {\n '*': webTarget.concat(nodeTarget),\n 'browser': webTarget,\n 'node': nodeTarget,\n }\n\n const parsedExports = parseAndValidateExports({\n cwd,\n pkg,\n strict,\n strictOptions,\n logger,\n }).reduce<PkgExports>(\n (acc, {_path: exportPath, ...exportEntry}) => Object.assign(acc, {[exportPath]: exportEntry}),\n {},\n )\n\n const exports = resolveConfigProperty(config?.exports, parsedExports)\n\n const parsedExternal = [\n ...(pkg.dependencies ? Object.keys(pkg.dependencies) : []),\n ...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []),\n ]\n\n // The deprecated (grandfathered) `external` option: merge if an array, replace if a function\n const external =\n config && Array.isArray(config.external)\n ? [...parsedExternal, ...config.external]\n : resolveConfigProperty(config?.external, parsedExternal)\n\n // Map `external` onto tsdown's `deps`: additions over the default (dependencies + peers)\n // become `neverBundle`, defaults filtered out by the callback pattern become `alwaysBundle`\n // (tsdown auto-externalizes dependencies/peers, so only the diff needs expressing). The v11\n // `external` semantics were subpath-aware (`name` also matched `name/subpath`), so package\n // names map to `^name(/|$)` patterns. The package's own name always stays external, so\n // self-referencing imports (e.g. the injected `import \"<pkg>/bundle.css\"`) never resolve\n // into the bundle.\n const packagePattern = (name: string) => new RegExp(`^${escapeRegExp(name)}(/|$)`)\n const neverBundleAdditions: (string | RegExp)[] = external\n .filter((name) => !parsedExternal.includes(name))\n .map(packagePattern)\n neverBundleAdditions.push(packagePattern(pkg.name))\n const alwaysBundleNames = parsedExternal.filter((name) => !external.includes(name))\n const deps = mergeDeps(config?.deps, {\n neverBundle: neverBundleAdditions,\n alwaysBundle: alwaysBundleNames.map(packagePattern),\n })\n\n // Packages whose types are inlined into the emitted declarations, used by the api-extractor\n // TSDoc check: devDependencies that are not external (like v11), plus any string entries of\n // the `deps.alwaysBundle` passthrough (force-bundled dependencies inline their types too).\n const externalWithTypes = new Set([pkg.name, ...external, ...external.map(transformPackageName)])\n const bundledDependencies = (pkg.devDependencies ? Object.keys(pkg.devDependencies) : []).filter(\n // Do not bundle anything that is marked as external\n (_) => !externalWithTypes.has(_),\n )\n const bundledPackages = [\n ...bundledDependencies,\n ...alwaysBundleNames,\n ...(Array.isArray(config?.deps?.alwaysBundle)\n ? config.deps.alwaysBundle.filter((entry): entry is string => typeof entry === 'string')\n : typeof config?.deps?.alwaysBundle === 'string'\n ? [config.deps.alwaysBundle]\n : []),\n ]\n\n const outputPaths = Object.values(exports)\n .flatMap((exportEntry) => {\n return [\n exportEntry.import,\n exportEntry.require,\n exportEntry.browser?.import,\n exportEntry.browser?.require,\n exportEntry.node?.source && exportEntry.node.import,\n exportEntry.node?.source && exportEntry.node.require,\n ].filter(isTruthy)\n })\n .map((p) => path.resolve(cwd, p))\n\n const commonDistPath = findCommonDirPath(outputPaths)\n\n if (commonDistPath === cwd) {\n throw new Error(\n 'all output files must share a common parent directory which is not the root package directory',\n )\n }\n\n if (commonDistPath && !pathContains(cwd, commonDistPath)) {\n throw new Error('all output files must be located within the package')\n }\n\n const configDistPath = config?.dist ? path.resolve(cwd, config.dist) : undefined\n\n if (\n configDistPath &&\n commonDistPath &&\n configDistPath !== commonDistPath &&\n !pathContains(configDistPath, commonDistPath)\n ) {\n logger.log(`did you mean to configure \\`dist: './${path.relative(cwd, commonDistPath)}'\\`?`)\n\n throw new Error('all output files must be located with the configured `dist` path')\n }\n\n const distPath = configDistPath || commonDistPath\n\n if (!distPath) {\n throw new Error('could not detect `dist` path')\n }\n\n const ctx: BuildContext = {\n config,\n cwd,\n deps,\n distPath,\n emitDeclarationOnly,\n exports,\n external,\n bundledPackages,\n logger,\n pkg,\n runtime: config?.runtime ?? '*',\n strict,\n target,\n ts: {\n config: tsconfig,\n configPath: tsconfigPath,\n },\n }\n\n return ctx\n}\n\ntype DepsConfig = NonNullable<import('tsdown').UserConfig['deps']>\n\n/**\n * Merges the `deps` additions derived from the deprecated `external` option (and the\n * self-reference external) into the userland `deps` passthrough. Array forms concatenate, a\n * userland function is composed with the derived additions (the additions carry pipeline\n * invariants like the self-reference external, which must survive customization — the same\n * composition `@sanity/tsdown-config` applies to its `/^node:/` default), and a blanket\n * `true` (externalize all of `node_modules`) wins as the broadest request.\n * @internal Exported for tests.\n */\nexport function mergeDeps(\n configDeps: DepsConfig | undefined,\n additions: {neverBundle: (string | RegExp)[]; alwaysBundle: (string | RegExp)[]},\n): DepsConfig | undefined {\n const userNeverBundle = configDeps?.neverBundle\n let neverBundle: DepsConfig['neverBundle']\n if (userNeverBundle === undefined) {\n neverBundle = additions.neverBundle\n } else if (userNeverBundle === true) {\n neverBundle = userNeverBundle\n } else if (typeof userNeverBundle === 'function') {\n const patterns = additions.neverBundle\n neverBundle = (id, importer, isResolved) =>\n patterns.some((pattern) =>\n typeof pattern === 'string' ? pattern === id : pattern.test(id),\n ) || userNeverBundle(id, importer, isResolved)\n } else if (Array.isArray(userNeverBundle)) {\n neverBundle = [...additions.neverBundle, ...userNeverBundle]\n } else {\n neverBundle = [...additions.neverBundle, userNeverBundle]\n }\n\n const userAlwaysBundle = configDeps?.alwaysBundle\n let alwaysBundle: DepsConfig['alwaysBundle']\n if (userAlwaysBundle === undefined) {\n alwaysBundle = additions.alwaysBundle.length ? additions.alwaysBundle : undefined\n } else if (typeof userAlwaysBundle === 'function') {\n // A userland function wins over the derived additions\n alwaysBundle = userAlwaysBundle\n } else if (Array.isArray(userAlwaysBundle)) {\n alwaysBundle = [...additions.alwaysBundle, ...userAlwaysBundle]\n } else {\n alwaysBundle = [...additions.alwaysBundle, userAlwaysBundle]\n }\n\n const deps: DepsConfig = {\n ...configDeps,\n neverBundle,\n ...(alwaysBundle === undefined ? {} : {alwaysBundle}),\n }\n\n return deps\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction transformPackageName(packageName: string): string {\n if (packageName.startsWith('@types/')) {\n // If it already starts with @types, return it as is\n return packageName\n } else if (packageName.startsWith('@')) {\n // Handle scoped packages\n const [scope, name] = packageName.split('/')\n\n return `@types/${scope?.slice(1)}__${name}`\n } else {\n // Handle regular packages\n return `@types/${packageName}`\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,eAAe,KAAiC;CAC9D,IAAM,cAAc,WAAW,gBAAgB,EAAC,IAAG,CAAC;CAEpD,IAAI,CAAC,aAAa;CAElB,IAAM,UAAU,KAAK,QAAQ,WAAW;CAExC,KAAK,IAAM,YAAY,mBAAmB;EACxC,IAAM,aAAa,KAAK,QAAQ,SAAS,QAAQ;EAIjD,IAFe,WAAW,UAEjB,GACP,OAAO;CAEX;AAGF;;;;;;;;;;;;;;;;ACfA,MAAM,sBACJ,0FAOI,aAA4B;CAChC;EACE,QAAQ;EACR,WAAW;GACT;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,QAAQ;EACR,WAAW;GACT;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,QAAQ;EACR,WAAW;GACT;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,QAAQ;EACR,WAAW;GACT;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,QAAQ;EACR,WAAW;GACT;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,QAAQ;EACR,WAAW;GACT;GACA;GACA;GACA;EACF;CACF;CACA;EACE,QAAQ;EACR,WAAW,CAAC,uEAAuE;CACrF;CACA;EACE,QAAQ;EACR,WAAW,CAAC,+EAA+E;CAC7F;CACA;EACE,QAAQ;EACR,WAAW,CAAC,4EAA4E;CAC1F;AACF;;;;;;;AAQA,SAAgB,sBAAsB,QAAuC;CAM3E,IAAI,EAJF,OAAO,OAAO,gBAAoB,YAC9B,OAAO,eACP,QAAQ,IAAI,aAAgB,eAEf;CAEnB,KAAK,IAAM,EAAC,QAAQ,eAAc,YAC5B,WAAO,YAAY,KAAA,GAEvB,MAAU,MACR;EACE,4BAA4B,OAAO;EACnC;EACA,GAAG;EACH;EACA,yBAAyB;EACzB;EACA;CACF,CAAC,CAAC,KAAK,IAAI,CACb;CAKF,IAAM,MAAM,OAAO;CACnB,IAAI,OAAO,OAAQ,UACjB,MAAU,MACR;EACE,8BAA8B,IAAI;EAClC;EACA;EACA,GAAI,QAAQ,aACR,CACE,kFACA,qFACF,IACA;GACE;GACA;GACA;EACF;EACJ;E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IAE7C,CAAC,GAAG,UAAU,aAAa,eAAe;CAG1D,IAAM,mBAAmB,YAAY,cACjC;CAkBJ,OAjBA,AAQE,eARE,qBAAqB,KAAA,IACR,UAAU,aAAa,SAAS,UAAU,eAAe,KAAA,IAC/D,OAAO,oBAAqB,aAEtB,mBACN,MAAM,QAAQ,gBAAgB,IACxB,CAAC,GAAG,UAAU,cAAc,GAAG,gBAAgB,IAE/C,CAAC,GAAG,UAAU,cAAc,gBAAgB,GAStD;EALL,GAAG;EACH;EACA,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAC,aAAY;CAG3C;AACZ;AAEA,SAAS,aAAa,OAAuB;CAC3C,OAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEA,SAAS,qBAAqB,aAA6B;CACzD,IAAI,YAAY,WAAW,SAAS,GAElC,OAAO;CACF,IAAI,YAAY,WAAW,GAAG,GAAG;EAEtC,IAAM,CAAC,OAAO,QAAQ,YAAY,MAAM,GAAG;EAE3C,OAAO,UAAU,OAAO,MAAM,CAAC,EAAE,IAAI;CACvC;CAEE,OAAO,UAAU;AAErB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolveTsdownConfig-CGE_7cMM.js","names":[],"sources":["../src/node/tasks/tsdown/resolveTsdownBuilds.ts","../src/node/tasks/tsdown/composeExports.ts","../src/node/tasks/tsdown/resolveTsdownConfig.ts"],"sourcesContent":["import path from 'node:path'\nimport type {PkgFormat, PkgRuntime} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {fileEnding} from '../../core/pkg/pkgExt.ts'\n\n/**\n * One entry of a tsdown build.\n * @internal\n */\nexport interface TsdownBuildEntry {\n /**\n * The entry alias handed to tsdown: the output path relative to `dist` without the\n * extension (e.g. `index`, `index.browser`, `sub/feature`), so the emitted filenames match\n * the hand-written `exports` targets exactly.\n */\n alias: string\n source: string\n /** The hand-written export subpath this entry backs (`undefined` for `bundles`). */\n exportPath?: string\n /** The formats the hand-written exports declare for this entry. */\n formats: PkgFormat[]\n}\n\n/**\n * One tsdown `build()` call of the waterfall. Builds run serially — variants and bundles\n * first, the canonical build last, so its exports generation and publint see every emitted\n * file on disk.\n * @internal\n */\nexport interface TsdownBuild {\n /** Stable identifier, e.g. `neutral`, `browser`, `node`, `bundles`. */\n key: string\n runtime: PkgRuntime\n /** The canonical build owns `dist` conventions: exports generation runs here. */\n canonical: boolean\n entries: TsdownBuildEntry[]\n}\n\n/**\n * Collapses the hand-written `exports` map (+ `bundles`) into the per-platform tsdown build\n * waterfall: one canonical build for the package's default runtime, plus a variant build per\n * `browser`/`node` exports condition, plus builds for `bundles` (which must not participate\n * in exports generation).\n * @internal\n */\nexport function resolveTsdownBuilds(ctx: BuildContext): TsdownBuild[] {\n const {config, cwd, distPath, logger} = ctx\n\n const entryAlias = (output: string): string => {\n const alias = path\n .relative(distPath, path.resolve(cwd, output))\n .replaceAll('\\\\', '/')\n .replace(fileEnding, '')\n if (alias.startsWith('..')) {\n throw new Error(`output file is outside the \\`dist\\` folder: ${output}`)\n }\n return alias\n }\n\n interface EntryDraft {\n alias: string\n source: string\n exportPath?: string | undefined\n formats: Set<PkgFormat>\n }\n\n const draftsByBuild = new Map<string, Map<string, EntryDraft>>()\n const runtimeByBuild = new Map<string, PkgRuntime>()\n\n const addEntry = (\n buildKey: string,\n runtime: PkgRuntime,\n entry: {\n source: string\n exportPath?: string | undefined\n import?: string | undefined\n require?: string | undefined\n },\n ) => {\n runtimeByBuild.set(buildKey, runtime)\n const {source, exportPath} = entry\n const aliases = new Set<string>()\n const formats = new Set<PkgFormat>()\n if (entry.import) {\n aliases.add(entryAlias(entry.import))\n formats.add('esm')\n }\n if (entry.require) {\n aliases.add(entryAlias(entry.require))\n formats.add('commonjs')\n }\n if (aliases.size === 0) return\n if (aliases.size > 1) {\n throw new Error(\n `the \\`import\\` and \\`require\\` targets of ${\n exportPath ? `exports[\"${exportPath}\"]` : `the bundle for ${source}`\n } must share a basename (e.g. \\`./dist/index.js\\` + \\`./dist/index.cjs\\`), ` +\n `got: ${entry.import} and ${entry.require}`,\n )\n }\n const [alias] = aliases\n let drafts = draftsByBuild.get(buildKey)\n if (!drafts) {\n drafts = new Map()\n draftsByBuild.set(buildKey, drafts)\n }\n const existing = drafts.get(alias!)\n if (existing) {\n if (existing.source !== source) {\n throw new Error(\n `conflicting sources for the output alias \"${alias}\": ${existing.source} and ${source}`,\n )\n }\n for (const format of formats) existing.formats.add(format)\n return\n }\n drafts.set(alias!, {alias: alias!, source, exportPath, formats})\n }\n\n const exports = Object.entries(ctx.exports || {})\n\n let hasRuntimeConditions = false\n\n for (const [exportPath, exp] of exports) {\n addEntry('canonical', ctx.runtime, {\n source: exp.source,\n exportPath,\n import: exp.import,\n require: exp.require,\n })\n\n if (exp.browser?.import || exp.browser?.require) {\n hasRuntimeConditions = true\n addEntry('browser', 'browser', {\n source: exp.browser.source || exp.source,\n exportPath,\n import: exp.browser.import,\n require: exp.browser.require,\n })\n }\n\n if (exp.node?.import || exp.node?.require) {\n hasRuntimeConditions = true\n addEntry('node', 'node', {\n source: exp.node.source || exp.source,\n exportPath,\n import: exp.node.import,\n require: exp.node.require,\n })\n }\n }\n\n // `bundles` are extra entrypoints that are deliberately not in the exports map (CLI workers\n // and similar), so they build separately from the canonical build — exports generation\n // derives subpaths from every entry of its build, and bundles must never become export\n // subpaths of their own.\n for (const bundle of config?.bundles || []) {\n const runtime = bundle.runtime || ctx.runtime\n addEntry(runtime === ctx.runtime ? 'bundles' : `bundles:${runtime}`, runtime, {\n source: bundle.source,\n import: bundle.import,\n require: bundle.require,\n })\n }\n\n if (hasRuntimeConditions) {\n logger.warn(\n [\n 'The `exports[].browser.source` / `exports[].node.source` pattern is not recommended: every',\n 'runtime condition adds a full extra build (complexity and build time). Consider instead:',\n ' 1. separate npm packages per platform/runtime, selected through export conditions that',\n ' pick the right package per environment,',\n ' 2. when possible, a single neutral build using JS that works in both runtimes without',\n ' special-casing (e.g. `new URL` over `require(\"url\")`, WebCrypto over',\n ' `require(\"crypto\")`), or',\n ' 3. using `tsdown` + `@sanity/tsdown-config` directly, exporting an array from',\n ' `tsdown.config.ts` with one config per `platform` — the fully supported path for',\n ' this level of customization.',\n ].join('\\n'),\n )\n }\n\n const builds: TsdownBuild[] = []\n\n const toBuild = (key: string, runtime: PkgRuntime, canonical: boolean): TsdownBuild | null => {\n const drafts = draftsByBuild.get(key)\n if (!drafts || drafts.size === 0) return null\n return {\n key,\n runtime,\n canonical,\n entries: Array.from(drafts.values(), (draft) => ({\n alias: draft.alias,\n source: draft.source,\n ...(draft.exportPath === undefined ? {} : {exportPath: draft.exportPath}),\n formats: Array.from(draft.formats),\n })),\n }\n }\n\n // Variants and bundles run first; the canonical build runs last so its exports generation\n // and publint see the other builds' files on disk. Each build's runtime was recorded when\n // its entries were added, so nothing is re-derived from the build key (a bundle with\n // `runtime: '*'` in a `runtime: 'node'` package must build for `'*'`/neutral).\n for (const key of draftsByBuild.keys()) {\n if (key === 'canonical') continue\n const build = toBuild(key, runtimeByBuild.get(key) ?? ctx.runtime, false)\n if (build) builds.push(build)\n }\n\n const canonical = toBuild('canonical', ctx.runtime, true)\n if (canonical) builds.push(canonical)\n\n return builds\n}\n","import type {PkgExport} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {isRecord} from '../../core/isRecord.ts'\nimport type {TsdownBuild} from './resolveTsdownBuilds.ts'\n\ntype ExportsMap = Record<string, unknown>\ninterface ComposeContext {\n isPublish: boolean\n}\n\n/**\n * The pkg-utils opinion layer over tsdown's generated `exports` map, composed into\n * `exports.customExports` of the canonical build (the same composition hook\n * `@sanity/vanilla-extract-tsdown-plugin` uses for its conditional CSS export).\n *\n * tsdown generates subpaths from the entry aliases with `source`/`import`/`require` conditions\n * (`devExports: 'source'`) and a `source`-less `publishConfig.exports` — already the Sanity\n * convention. This composer reconciles the generated map with the hand-written one, which\n * remains the input:\n *\n * - generated keys are remapped to the hand-written subpaths (entry aliases are derived from\n * the output paths, which don't have to match the subpath names),\n * - the hand-written `types`, `browser`, `node`, `development` and `monorepo` conditions are\n * re-inserted (tsdown's generator cannot express them; the `browser`/`node` files are built\n * by the variant builds of the waterfall) — with `source`-like conditions stripped from the\n * publish variant,\n * - all hand-written conditions (`react-server`, `worker`, … included) retain their authored\n * order in each map independently, because earlier matching conditions take precedence,\n * - generated conditions for conditional entries are materialized in both `exports` and\n * `publishConfig.exports`, so they can be reordered directly in `package.json` and keep that\n * position on later builds (plain-string entries stay compact),\n * - a trailing `default` condition is kept on dual-format entries (tsdown emits bare\n * `import`/`require` pairs; the Sanity convention always ends with `default`),\n * - hand-written subpaths that aren't build entries (`.css`/`.json` exports, `svelte`\n * entries) are carried over untouched, and\n * - the hand-written subpath and condition key order of each map is preserved.\n * @internal\n */\nexport function createExportsComposer(\n ctx: BuildContext,\n build: TsdownBuild,\n): (exportsMap: ExportsMap, context: ComposeContext) => ExportsMap {\n const {pkg} = ctx\n const type = pkg.type === 'module' ? 'module' : 'commonjs'\n\n // alias -> hand-written subpath, e.g. `index` -> `.`, `sub/feature` -> `./feature`\n const aliasToExportPath = new Map<string, string>()\n for (const entry of build.entries) {\n if (entry.exportPath !== undefined) {\n aliasToExportPath.set(entry.alias, entry.exportPath)\n }\n }\n\n return (exportsMap, context) => {\n const {isPublish} = context\n\n // 1. Remap the generated keys (`.` for the `index` alias, `./<alias>` otherwise) back to\n // the hand-written subpaths.\n const remapped: ExportsMap = {}\n for (const [key, value] of Object.entries(exportsMap)) {\n const alias = key === '.' ? 'index' : key.startsWith('./') ? key.slice(2) : key\n const exportPath = aliasToExportPath.get(alias) ?? key\n remapped[exportPath] = value\n }\n\n // 2. Reconcile each generated entry with its hand-written counterpart.\n const result: ExportsMap = {}\n const handwritten = ctx.exports || {}\n const sourceRaw: ExportsMap = pkg.exports || {}\n const publishRaw: ExportsMap | undefined = pkg.publishConfig?.exports\n const authoredRaw = isPublish && publishRaw ? publishRaw : sourceRaw\n\n const reconcile = (exportPath: string, value: unknown): unknown => {\n const exp = handwritten[exportPath]\n if (!exp) return value\n const raw = authoredRaw[exportPath]\n const source = sourceRaw[exportPath]\n // A configured exports map is itself authoritative. Otherwise use the raw package entry\n // for the map being generated. Fall back to `exports` when a new publish map/entry is\n // being generated, so inferred conditions don't masquerade as ordering choices.\n const authored =\n ctx.config?.exports === undefined\n ? isRecord(raw)\n ? raw\n : isRecord(source)\n ? source\n : exp\n : exp\n return reconcileEntry(exp, value, {authored, isPublish, type})\n }\n\n // 3. Follow the hand-written key order of the map being generated. Source-only passthrough\n // subpaths missing from an existing publish map are appended, followed by generated extras.\n const authoredPaths = Object.keys(authoredRaw)\n for (const exportPath of Object.keys(sourceRaw)) {\n if (!Object.prototype.hasOwnProperty.call(authoredRaw, exportPath)) {\n authoredPaths.push(exportPath)\n }\n }\n for (const exportPath of authoredPaths) {\n if (exportPath in remapped) {\n result[exportPath] = reconcile(exportPath, remapped[exportPath])\n } else {\n // Hand-written subpaths that aren't build entries (`.css`/`.json` exports, `svelte`\n // entries) pass through untouched.\n result[exportPath] = Object.prototype.hasOwnProperty.call(authoredRaw, exportPath)\n ? authoredRaw[exportPath]\n : sourceRaw[exportPath]\n }\n }\n for (const [exportPath, value] of Object.entries(remapped)) {\n if (exportPath in result) continue\n result[exportPath] = reconcile(exportPath, value)\n }\n\n return result\n }\n}\n\n/**\n * Rebuilds a generated subpath entry in its authored condition order, re-inserting the\n * hand-written conditions tsdown's generator cannot express.\n */\nfunction reconcileEntry(\n exp: PkgExport,\n generated: unknown,\n options: {authored: object; isPublish: boolean; type: 'commonjs' | 'module'},\n): unknown {\n const {authored, isPublish, type} = options\n const authoredRecord = isRecord(authored) ? authored : {}\n\n // tsdown's publish variant of a single-format entry is a plain string\n const gen: Record<string, unknown> | undefined =\n typeof generated === 'string'\n ? {default: generated}\n : isRecord(generated)\n ? generated\n : undefined\n if (!gen) return generated\n\n const browserOrder = isRecord(authoredRecord['browser']) ? authoredRecord['browser'] : exp.browser\n const browser =\n exp.browser && (exp.browser.import || exp.browser.require)\n ? pickConditions(exp.browser, isPublish, browserOrder ?? exp.browser)\n : undefined\n const nodeOrder = isRecord(authoredRecord['node']) ? authoredRecord['node'] : exp.node\n const node =\n exp.node && (exp.node.import || exp.node.require)\n ? pickConditions(exp.node, isPublish, nodeOrder ?? exp.node)\n : undefined\n const custom = pickCustomConditions(exp)\n\n // Preserve tsdown's compact single-format publish shape unless hand-written conditions need\n // to be re-inserted. There is no condition ordering to preserve in a plain string entry.\n if (typeof generated === 'string' && !exp.types && !browser && !node && custom.length === 0) {\n return generated\n }\n\n const next: Record<string, unknown> = {}\n\n // `source`-like conditions resolve at development time and are stripped from the publish\n // variant (tsdown already does this for `source`; `development`/`monorepo` follow)\n if (!isPublish) {\n if (typeof gen['source'] === 'string') next['source'] = gen['source']\n else if (exp.source) next['source'] = exp.source\n if (exp.development) next['development'] = exp.development\n if (exp.monorepo) next['monorepo'] = exp.monorepo\n }\n\n if (exp.types) next['types'] = exp.types\n if (browser) next['browser'] = browser\n if (node) next['node'] = node\n\n // Hand-written custom conditions (`react-server`, `worker`, …) aren't built, but they are\n // the author's: carry their targets over, then restore every condition's authored position.\n for (const [condition, target] of custom) {\n const authoredTarget = authoredRecord[condition]\n next[condition] =\n isRecord(target) && isRecord(authoredTarget)\n ? preserveConditionOrder(target, authoredTarget)\n : target\n }\n\n if (typeof gen['import'] === 'string' && typeof gen['require'] === 'string') {\n next['import'] = gen['import']\n next['require'] = gen['require']\n // tsdown emits bare `import`/`require` pairs; the Sanity convention ends with `default`\n next['default'] = type === 'module' ? gen['import'] : gen['require']\n } else {\n // Single-format entries keep the generated shape (`{source, default}` in development)\n for (const [condition, target] of Object.entries(gen)) {\n if (condition in next || condition === 'source') continue\n next[condition] = target\n }\n }\n\n return preserveConditionOrder(next, authored)\n}\n\n/** The hand-written `browser`/`node` condition object, minus `source` for the publish map. */\nfunction pickConditions(\n conditions: {source?: string; import?: string; require?: string},\n isPublish: boolean,\n authored: object = conditions,\n): Record<string, string> {\n const next: Record<string, string> = {}\n if (!isPublish && conditions.source) next['source'] = conditions.source\n if (conditions.import) next['import'] = conditions.import\n if (conditions.require) next['require'] = conditions.require\n return preserveConditionOrder(next, authored)\n}\n\n/**\n * Reorders reconciled conditions to match their hand-written order. Conditions generated by\n * tsdown but absent from the hand-written entry are inserted before its `default` fallback.\n */\nfunction preserveConditionOrder<T>(\n conditions: Record<string, T>,\n authored: object,\n): Record<string, T> {\n const entries: [string, T][] = []\n const added = new Set<string>()\n const conditionEntries = Object.entries(conditions)\n const entriesByCondition = new Map(conditionEntries.map((entry) => [entry[0], entry]))\n const authoredOrder = Object.keys(authored).filter((condition) => !condition.startsWith('_'))\n const authoredConditions = new Set(authoredOrder)\n\n const addGeneratedConditions = () => {\n for (const entry of conditionEntries) {\n if (!authoredConditions.has(entry[0]) && !added.has(entry[0])) {\n entries.push(entry)\n added.add(entry[0])\n }\n }\n }\n\n for (const condition of authoredOrder) {\n // A generated condition has no authored position. Keep the explicit `default` as the final\n // fallback by placing generated conditions immediately before it.\n if (condition === 'default') addGeneratedConditions()\n const entry = entriesByCondition.get(condition)\n if (!entry) continue\n entries.push(entry)\n added.add(condition)\n }\n\n addGeneratedConditions()\n\n return Object.fromEntries(entries)\n}\n\n/** The conditions the pipeline owns (or re-inserts itself) on a build entry. */\nconst managedConditions = new Set([\n 'source',\n 'development',\n 'monorepo',\n 'types',\n 'browser',\n 'node',\n 'import',\n 'require',\n 'default',\n])\n\n/**\n * Hand-written conditions the pipeline knows nothing about (`react-server`, `worker`,\n * `edge-light`, …), in authored order. `parseExports` spreads the raw entry, so they survive\n * on the parsed `PkgExport` beyond its typed fields.\n */\nfunction pickCustomConditions(exp: PkgExport): [string, unknown][] {\n return Object.entries(exp).filter(\n ([condition, target]) =>\n !managedConditions.has(condition) && !condition.startsWith('_') && target !== undefined,\n )\n}\n","import path from 'node:path'\nimport {defineConfig} from '@sanity/tsdown-config'\nimport {mergeConfig, type InlineConfig, type UserConfig} from 'tsdown'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {pkgExtMap} from '../../core/pkg/pkgExt.ts'\nimport {createExportsComposer} from './composeExports.ts'\nimport type {TsdownBuild} from './resolveTsdownBuilds.ts'\n\nconst RE_TS_SOURCE = /\\.[cm]?tsx?$/\n\n/**\n * Composes the tsdown config for one build of the waterfall: `@sanity/tsdown-config`'s\n * `defineConfig()` provides the shared Sanity base, and the pkg-utils opinions (browserslist\n * targets, `PKG_*` defines, exports reconciliation, dts selection) layer over it with\n * tsdown's `mergeConfig`.\n *\n * pkg-utils owns its own experience: the returned config carries `config: false`, so tsdown\n * never loads `tsdown.config.*` files — `package.config.ts` is the sole config source — and\n * `logLevel: 'warn'` keeps tsdown's info chatter out of pkg-utils' own output.\n * @internal\n */\nexport async function resolveTsdownConfig(\n ctx: BuildContext,\n build: TsdownBuild,\n options: {\n /**\n * Whether this build may clean: only the first build of the waterfall cleans (so later\n * builds can't wipe earlier output), and `--no-clean` turns it off for the whole run.\n */\n clean: boolean\n watch?: boolean\n },\n): Promise<InlineConfig> {\n const {config, cwd, distPath, pkg} = ctx\n\n const reactCompiler = config?.reactCompiler\n if (typeof reactCompiler === 'object' && reactCompiler.reactServer === true) {\n throw new Error(\n [\n 'package.config.ts: `reactCompiler.reactServer` is not supported by `pkg build` — the',\n 'dual React Server Components build needs one tsdown run driving multiple configs.',\n 'Use `tsdown` + `@sanity/tsdown-config` directly instead: export the config from',\n '`tsdown.config.ts` and build with `tsdown`.',\n ].join('\\n'),\n )\n }\n\n const entry: Record<string, string> = {}\n for (const buildEntry of build.entries) {\n entry[buildEntry.alias] = buildEntry.source\n }\n\n // tsdown's `format` applies to the whole build (and its exports generation composes the\n // dual `import`/`require` map from both formats' chunks of one build), so the entries'\n // formats union: every entry is emitted in every format of the build. Mixed per-entry\n // coverage gets a heads-up — the extra files are emitted, and local exports generation\n // will declare them.\n const formats = new Set(build.entries.flatMap((buildEntry) => buildEntry.formats))\n if (formats.size > 1) {\n const partial = build.entries.filter((buildEntry) => buildEntry.formats.length < formats.size)\n if (partial.length) {\n const names = partial\n .map((buildEntry) =>\n buildEntry.exportPath ? `exports[\"${buildEntry.exportPath}\"]` : buildEntry.source,\n )\n .join(', ')\n ctx.logger.warn(\n `${names} declare${partial.length === 1 ? 's' : ''} fewer formats than the rest of the package. tsdown emits every format of a build for every entry, so the missing format is built anyway (and local exports generation will declare it). Declare both \\`import\\` and \\`require\\` targets for every subpath — or for none — to keep the exports map unambiguous.`,\n )\n }\n }\n const format = [\n ...(formats.has('esm') ? ['esm' as const] : []),\n ...(formats.has('commonjs') ? ['cjs' as const] : []),\n ]\n\n const platform =\n build.runtime === 'node' ? 'node' : build.runtime === 'browser' ? 'browser' : 'neutral'\n\n // Build-time constants: `PKG_VERSION` reads the environment override first, like v11.\n // pkg-utils' own build skips it so the replacement logic in this very file survives its own\n // bundling. (`PKG_FORMAT`, `PKG_RUNTIME` and `PKG_FILE_PATH` were removed in v12 — see\n // MIGRATE.md for the `package.json#imports` / `import.meta.url` replacements.)\n const define: Record<string, string> = {}\n if (pkg.name !== '@sanity/pkg-utils') {\n define['process.env.PKG_VERSION'] = JSON.stringify(process.env['PKG_VERSION'] || pkg.version)\n }\n for (const [key, value] of Object.entries(config?.define || {})) {\n define[key] = JSON.stringify(value)\n }\n\n // Types are generated with tsdown (rolldown-plugin-dts). `@typescript/native-preview` in\n // devDependencies auto-enables tsgo, like v11; an explicit `dts.tsgo` wins. Only the object\n // form spreads: when the `legacyChecks` migration errors are skipped\n // (`NODE_ENV=production` / `legacyChecks: false`), a leftover v11 string like\n // `dts: 'rolldown'` must degrade to the default behavior (which is what it meant) instead\n // of spreading into numeric character keys.\n const hasTsSources = build.entries.some((buildEntry) => RE_TS_SOURCE.test(buildEntry.source))\n const dtsPassthrough = typeof config?.dts === 'object' ? config.dts : undefined\n const dts =\n hasTsSources && config?.dts !== false\n ? {\n ...(typeof pkg.devDependencies === 'object' &&\n '@typescript/native-preview' in pkg.devDependencies\n ? {tsgo: true}\n : {}),\n // Always create dts from scratch, don't reuse contexts from previous builds\n newContext: true,\n ...dtsPassthrough,\n ...(ctx.emitDeclarationOnly ? {emitDtsOnly: true} : {}),\n }\n : false\n\n // Exports generation runs on the canonical build only, with `devExports: 'source'` — the\n // hand-written Sanity convention (`source` conditions in `exports`, a `source`-less\n // `publishConfig.exports`) — and the pkg-utils composer reconciling the generated map with\n // the hand-written one. `@sanity/tsdown-config`'s always-on exports default applies: the map\n // is rewritten on every build (CI included), so environments that set `CI=true` without\n // meaning \"skip package.json\" (Cursor Cloud, …) still keep exports in sync. A types-only\n // build never rewrites `package.json`, and neither do watch builds (a rewrite would\n // re-trigger the `package.json` watcher).\n const exports: UserConfig['exports'] =\n build.canonical && !ctx.emitDeclarationOnly && !options.watch\n ? {\n devExports: 'source',\n customExports: createExportsComposer(ctx, build),\n // Keep the hand-written legacy fields (`main`/`module`) in sync instead of deleting\n // them; packages without them don't gain them\n ...(pkg.main || pkg.module ? {legacy: true} : {}),\n }\n : false\n\n const base = await defineConfig({\n cwd,\n tsconfig: ctx.ts.configPath,\n platform,\n format,\n entry,\n // POSIX separators: on Windows `path.relative` yields backslashes, which would leak into\n // generated `package.json` export targets (e.g. the conditional vanilla-extract export)\n outDir: path.relative(cwd, distPath).replaceAll('\\\\', '/') || '.',\n target: ctx.target[build.runtime],\n define,\n sourcemap: config?.sourcemap,\n // tsdown owns cleaning: the first build of the waterfall carries the effective `clean`\n // (the config passthrough, or tsdown's default `true`), every later build gets `false`.\n // A types-only build never cleans, so it can't delete JS output.\n clean: options.clean && !ctx.emitDeclarationOnly ? config?.clean : false,\n dts,\n deps: ctx.deps,\n exports,\n reactCompiler: config?.reactCompiler,\n styledComponents: config?.styledComponents,\n vanillaExtract: config?.vanillaExtract,\n })\n\n // The hand-written exports define the emitted extensions (`.js`/`.mjs`/`.cjs` per\n // `package.json#type`, enforced by `validateExports`), so the extensions are pinned\n // explicitly instead of relying on tsdown's defaults (whose `fixedExtension` kicks in for\n // `platform: 'node'` and would emit `.mjs` for `type: module` packages).\n const extMap = pkgExtMap[pkg.type === 'module' ? 'module' : 'commonjs']\n const outExtensions: UserConfig['outExtensions'] = ({format: outputFormat}) => ({\n js: outputFormat === 'cjs' ? extMap.commonjs : extMap.esm,\n })\n\n const merged = mergeConfig(base, {\n outExtensions,\n // publint runs during `pkg check` (via its node API), not inside the build\n publint: false,\n // the per-file size report logs through tsdown's info channel; pkg-utils prints its own\n report: false,\n ...(config?.minify === true ? {minify: true} : {}),\n ...(config?.plugins === undefined ? {} : {plugins: config.plugins}),\n })\n\n return {\n ...merged,\n config: false,\n logLevel: 'warn',\n ...(options.watch ? {watch: true} : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;AA6CA,SAAgB,oBAAoB,KAAkC;CACpE,IAAM,EAAC,QAAQ,KAAK,UAAU,WAAU,KAElC,cAAc,WAA2B;EAC7C,IAAM,QAAQ,KACX,SAAS,UAAU,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAC7C,WAAW,MAAM,GAAG,CAAC,CACrB,QAAQ,YAAY,EAAE;EACzB,IAAI,MAAM,WAAW,IAAI,GACvB,MAAU,MAAM,+CAA+C,QAAQ;EAEzE,OAAO;CACT,GASM,gCAAgB,IAAI,IAAqC,GACzD,iCAAiB,IAAI,IAAwB,GAE7C,YACJ,UACA,SACA,UAMG;EACH,eAAe,IAAI,UAAU,OAAO;EACpC,IAAM,EAAC,QAAQ,eAAc,OACvB,0BAAU,IAAI,IAAY,GAC1B,0BAAU,IAAI,IAAe;EASnC,IARI,MAAM,WACR,QAAQ,IAAI,WAAW,MAAM,MAAM,CAAC,GACpC,QAAQ,IAAI,KAAK,IAEf,MAAM,YACR,QAAQ,IAAI,WAAW,MAAM,OAAO,CAAC,GACrC,QAAQ,IAAI,UAAU,IAEpB,QAAQ,SAAS,GAAG;EACxB,IAAI,QAAQ,OAAO,GACjB,MAAU,MACR,6CACE,aAAa,YAAY,WAAW,MAAM,kBAAkB,SAC7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isRecord, t as handleError } from "./handleError-83GwKIFM.js";
2
- import { a as loadPkgWithReporting, o as loadConfig, t as resolveBuildContext } from "./resolveBuildContext-CbwvYKj1.js";
3
- import { n as resolveTsdownBuilds, t as resolveTsdownConfig } from "./resolveTsdownConfig-CGE_7cMM.js";
4
- import path from "node:path";
5
- import { up } from "empathic/package";
6
- import { build } from "tsdown";
7
- import { readFile, writeFile } from "node:fs/promises";
8
- import { switchMap } from "rxjs";
9
- /**
10
- * The no-op JS shim file name for a CSS file under vanilla-extract compat mode.
11
- *
12
- * `bundle.css` → `bundle-css.js` — deliberately not `${cssFileName}.js` (`bundle.css.js`),
13
- * which vanilla-extract's `cssFileFilter` (`/\.css\.(js|cjs|mjs|jsx|ts|tsx)$/`) would treat as
14
- * a stylesheet module. Kept in sync with `cssShimFileName` in
15
- * `@sanity/vanilla-extract-rolldown-plugin`.
16
- *
17
- * @internal
18
- */
19
- function cssShimFileName(cssFileName) {
20
- return `${cssFileName.replace(/\.css$/, "-css")}.js`;
21
- }
22
- /**
23
- * The `.d.ts` companion for {@link cssShimFileName}. `bundle.css` → `bundle-css.d.ts`.
24
- *
25
- * @internal
26
- */
27
- function cssShimDtsFileName(cssFileName) {
28
- return `${cssFileName.replace(/\.css$/, "-css")}.d.ts`;
29
- }
30
- /**
31
- * Build the conditional CSS export object that vanilla-extract compat mode expects, e.g.
32
- * ```json
33
- * {
34
- * "types": "./dist/bundle-css.d.ts",
35
- * "browser": "./dist/bundle.css",
36
- * "style": "./dist/bundle.css",
37
- * "node": "./dist/bundle-css.js",
38
- * "default": "./dist/bundle-css.js"
39
- * }
40
- * ```
41
- * The shim is named `bundle-css.js` (not `bundle.css.js`) so it does not match
42
- * vanilla-extract's `cssFileFilter`. An explicit `types` condition (rather than relying on
43
- * TypeScript's extension-substitution fallback, which only works when the shim shares the CSS
44
- * file's basename, and which TypeScript is deprecating anyway - microsoft/TypeScript#50762)
45
- * points resolvers straight at the shim's declaration file.
46
- *
47
- * Kept in sync with `createConditionalCssExport` in `@sanity/vanilla-extract-tsdown-plugin`,
48
- * which writes the same entry through tsdown's `exports.customExports` during full builds.
49
- */
50
- function createConditionalCssExport(cssFile, shimFile, shimDtsFile) {
51
- return {
52
- types: shimDtsFile,
53
- browser: cssFile,
54
- style: cssFile,
55
- node: shimFile,
56
- default: shimFile
57
- };
58
- }
59
- function hasMatchingExport(value, expected) {
60
- if (typeof value != "object" || !value) return !1;
61
- let actual = Object.fromEntries(Object.entries(value)), keys = Object.keys(expected);
62
- return keys.length === Object.keys(actual).length && keys.every((key) => actual[key] === expected[key]);
63
- }
64
- /**
65
- * Insert (or replace) the `"./<cssName>"` export in an `exports`-shaped map, preserving the existing
66
- * order and placing it before `./package.json` when present.
67
- */
68
- function insertCssExport(exports, exportKey, conditionalExport) {
69
- let nextExports = {}, inserted = !1;
70
- for (let [key, value] of Object.entries(exports)) key !== exportKey && (key === "./package.json" && !inserted && (nextExports[exportKey] = conditionalExport, inserted = !0), nextExports[key] = value);
71
- return inserted || (nextExports[exportKey] = conditionalExport), nextExports;
72
- }
73
- function detectIndent(source) {
74
- let match = source.match(/\n([ \t]+)\S/);
75
- if (!match) return 2;
76
- let indent = match[1];
77
- return indent.includes(" ") ? " " : indent.length;
78
- }
79
- /**
80
- * Write the conditional `"./<cssName>"` export to `package.json` (used by vanilla-extract compat
81
- * mode), so userland does not have to maintain it by hand. The write is idempotent: if the export
82
- * already matches, the file is left untouched.
83
- *
84
- * Full builds write this entry through tsdown's `exports.customExports` (the
85
- * `@sanity/vanilla-extract-tsdown-plugin` composition), but watch mode disables tsdown's
86
- * `exports` feature (a `package.json` write per rebuild would loop the watcher) — `pkg watch`
87
- * calls this once per context instead, like v11 did.
88
- *
89
- * When `publishConfig.exports` is present, the same conditional CSS export is mirrored into it. The
90
- * conditional CSS export has no `source`/`development`/`monorepo` conditions to strip, so the entry
91
- * is identical in both places. Keeping them in sync prevents the `publishConfig.exports` validation
92
- * from failing with a "missing export path" error for the auto-added `./<cssName>` export.
93
- *
94
- * @internal
95
- */
96
- async function writeBundleCssExports(options) {
97
- let { cwd, distPath, cssName, logger } = options, pkgPath = path.resolve(cwd, "package.json"), source = await readFile(pkgPath, "utf8"), pkg = JSON.parse(source), distRel = (path.relative(cwd, distPath) || "dist").split(path.sep).join("/"), exportKey = `./${cssName}`, conditionalExport = createConditionalCssExport(`./${path.posix.join(distRel, cssName)}`, `./${path.posix.join(distRel, cssShimFileName(cssName))}`, `./${path.posix.join(distRel, cssShimDtsFileName(cssName))}`), publishConfig = pkg.publishConfig, publishConfigExports = isRecord(publishConfig?.exports) ? publishConfig.exports : void 0, exportsMatch = hasMatchingExport(pkg.exports?.[exportKey], conditionalExport), publishConfigExportsMatch = !publishConfigExports || hasMatchingExport(publishConfigExports[exportKey], conditionalExport);
98
- exportsMatch && publishConfigExportsMatch || (pkg.exports = insertCssExport(pkg.exports ?? {}, exportKey, conditionalExport), publishConfig && publishConfigExports && (publishConfig.exports = insertCssExport(publishConfigExports, exportKey, conditionalExport)), await writeFile(pkgPath, `${JSON.stringify(pkg, null, detectIndent(source))}\n`), logger.log(`Updated package.json: added \`exports["${exportKey}"]\`${publishConfigExports ? ` and \`publishConfig.exports["${exportKey}"]\`` : ""} for vanilla-extract compat mode`));
99
- }
100
- const asyncDispose = Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose");
101
- /** @public */
102
- async function watch(options) {
103
- let { cwd, strict = !1, tsconfig: tsconfigOption, signal } = options, logger = createLogger(), { watchConfigFiles } = await import("./watchConfigFiles-AGBDblwf.js"), configFiles$ = await watchConfigFiles({
104
- cwd,
105
- logger
106
- }), bundles = [], runId = 0, disposeBundles = async () => {
107
- let disposing = bundles;
108
- bundles = [];
109
- for (let bundle of disposing) await bundle[asyncDispose]();
110
- }, ctxSubscription = configFiles$.pipe(switchMap(async () => {
111
- let pkgPath = up({ cwd });
112
- if (!pkgPath) throw Error("missing package.json", { cause: { cwd } });
113
- let config = await loadConfig({
114
- cwd,
115
- pkgPath
116
- }), { parseStrictOptions } = await import("./resolveBuildContext-CbwvYKj1.js").then((n) => n.n), strictOptions = parseStrictOptions(config?.strictOptions ?? {}), pkg = await loadPkgWithReporting({
117
- pkgPath,
118
- logger,
119
- strict,
120
- strictOptions
121
- }), tsconfig = tsconfigOption || config?.tsconfig || "tsconfig.json";
122
- return resolveBuildContext({
123
- config,
124
- cwd,
125
- logger,
126
- pkg,
127
- strict,
128
- tsconfig
129
- });
130
- })).subscribe(async (ctx) => {
131
- let id = ++runId, runBundles = [];
132
- try {
133
- await disposeBundles();
134
- let vanillaExtract = ctx.config?.vanillaExtract;
135
- if (vanillaExtract) {
136
- let veOptions = vanillaExtract === !0 ? {} : vanillaExtract, inject = veOptions.inject ?? { nodeCompat: !0 };
137
- isRecord(inject) && inject.nodeCompat && await writeBundleCssExports({
138
- cwd,
139
- distPath: ctx.distPath,
140
- cssName: veOptions.fileName || "bundle.css",
141
- logger
142
- });
143
- }
144
- let builds = resolveTsdownBuilds(ctx), first = !0;
145
- for (let buildDef of builds) {
146
- if (id !== runId) break;
147
- let inlineConfig = await resolveTsdownConfig(ctx, buildDef, {
148
- clean: first,
149
- watch: !0
150
- });
151
- first = !1, runBundles.push(...await build(inlineConfig));
152
- }
153
- if (id !== runId) {
154
- for (let bundle of runBundles) await bundle[asyncDispose]();
155
- return;
156
- }
157
- bundles = runBundles, logger.success(`${ctx.pkg.name}: watching for file changes\u2026`), logger.log();
158
- } catch (err) {
159
- ctx.logger.error(err), ctx.logger.log(), process.exit(1);
160
- }
161
- });
162
- signal && signal.addEventListener("abort", () => {
163
- runId++, ctxSubscription.unsubscribe(), disposeBundles();
164
- }, { once: !0 });
165
- }
166
- async function watchAction(options) {
167
- try {
168
- await watch({
169
- cwd: process.cwd(),
170
- strict: options.strict,
171
- tsconfig: options.tsconfig
172
- });
173
- } catch (err) {
174
- handleError(err);
175
- }
176
- }
177
- export { watchAction };
178
-
179
- //# sourceMappingURL=watchAction-BQG5_hhl.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"watchAction-BQG5_hhl.js","names":["findPkgPath","tsdownBuild"],"sources":["../src/node/core/pkg/cssShimFileName.ts","../src/node/core/pkg/writeBundleCssExports.ts","../src/node/watch.ts","../src/cli/watchAction.ts"],"sourcesContent":["/**\n * The no-op JS shim file name for a CSS file under vanilla-extract compat mode.\n *\n * `bundle.css` → `bundle-css.js` — deliberately not `${cssFileName}.js` (`bundle.css.js`),\n * which vanilla-extract's `cssFileFilter` (`/\\.css\\.(js|cjs|mjs|jsx|ts|tsx)$/`) would treat as\n * a stylesheet module. Kept in sync with `cssShimFileName` in\n * `@sanity/vanilla-extract-rolldown-plugin`.\n *\n * @internal\n */\nexport function cssShimFileName(cssFileName: string): string {\n return `${cssFileName.replace(/\\.css$/, '-css')}.js`\n}\n\n/**\n * The `.d.ts` companion for {@link cssShimFileName}. `bundle.css` → `bundle-css.d.ts`.\n *\n * @internal\n */\nexport function cssShimDtsFileName(cssFileName: string): string {\n return `${cssFileName.replace(/\\.css$/, '-css')}.d.ts`\n}\n","import {readFile, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport type {Logger} from '../../logger.ts'\nimport {isRecord} from '../isRecord.ts'\nimport {cssShimDtsFileName, cssShimFileName} from './cssShimFileName.ts'\n\n/**\n * Build the conditional CSS export object that vanilla-extract compat mode expects, e.g.\n * ```json\n * {\n * \"types\": \"./dist/bundle-css.d.ts\",\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 * The shim is named `bundle-css.js` (not `bundle.css.js`) so it does not match\n * vanilla-extract's `cssFileFilter`. An explicit `types` condition (rather than relying on\n * TypeScript's extension-substitution fallback, which only works when the shim shares the CSS\n * file's basename, and which TypeScript is deprecating anyway - microsoft/TypeScript#50762)\n * points resolvers straight at the shim's declaration file.\n *\n * Kept in sync with `createConditionalCssExport` in `@sanity/vanilla-extract-tsdown-plugin`,\n * which writes the same entry through tsdown's `exports.customExports` during full builds.\n */\nfunction createConditionalCssExport(cssFile: string, shimFile: string, shimDtsFile: string) {\n return {types: shimDtsFile, browser: cssFile, style: cssFile, node: shimFile, default: shimFile}\n}\n\nfunction hasMatchingExport(value: unknown, expected: Record<string, string>): boolean {\n if (typeof value !== 'object' || value === null) return false\n const actual = Object.fromEntries(Object.entries(value))\n const keys = Object.keys(expected)\n return (\n keys.length === Object.keys(actual).length && keys.every((key) => actual[key] === expected[key])\n )\n}\n\n/**\n * Insert (or replace) the `\"./<cssName>\"` export in an `exports`-shaped map, preserving the existing\n * order and placing it before `./package.json` when present.\n */\nfunction 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\nfunction detectIndent(source: string): string | number {\n const match = source.match(/\\n([ \\t]+)\\S/)\n if (!match) return 2\n const indent = match[1]!\n return indent.includes('\\t') ? '\\t' : indent.length\n}\n\n/**\n * Write the conditional `\"./<cssName>\"` export to `package.json` (used by vanilla-extract compat\n * mode), so userland does not have to maintain it by hand. The write is idempotent: if the export\n * already matches, the file is left untouched.\n *\n * Full builds write this entry through tsdown's `exports.customExports` (the\n * `@sanity/vanilla-extract-tsdown-plugin` composition), but watch mode disables tsdown's\n * `exports` feature (a `package.json` write per rebuild would loop the watcher) — `pkg watch`\n * calls this once per context instead, like v11 did.\n *\n * When `publishConfig.exports` is present, the same conditional CSS export is mirrored into it. The\n * conditional CSS export has no `source`/`development`/`monorepo` conditions to strip, so the entry\n * is identical in both places. Keeping them in sync prevents the `publishConfig.exports` validation\n * from failing with a \"missing export path\" error for the auto-added `./<cssName>` export.\n *\n * @internal\n */\nexport async function writeBundleCssExports(options: {\n cwd: string\n distPath: string\n cssName: string\n logger: Logger\n}): Promise<void> {\n const {cwd, distPath, cssName, logger} = options\n\n const pkgPath = path.resolve(cwd, 'package.json')\n const source = await readFile(pkgPath, 'utf8')\n // oxlint-disable-next-line no-unsafe-type-assertion\n const pkg = JSON.parse(source) as {\n exports?: Record<string, unknown>\n publishConfig?: {exports?: Record<string, unknown>}\n }\n\n // Normalize to POSIX separators - `path.relative` uses `\\\\` on Windows, but `exports` paths in\n // package.json must always use `/`.\n const distRel = (path.relative(cwd, distPath) || 'dist').split(path.sep).join('/')\n const exportKey = `./${cssName}`\n const cssFile = `./${path.posix.join(distRel, cssName)}`\n const shimFile = `./${path.posix.join(distRel, cssShimFileName(cssName))}`\n const shimDtsFile = `./${path.posix.join(distRel, cssShimDtsFileName(cssName))}`\n const conditionalExport = createConditionalCssExport(cssFile, shimFile, shimDtsFile)\n\n // Only mirror into `publishConfig.exports` when it already exists; never create it here.\n const publishConfig = pkg.publishConfig\n const publishConfigExports = isRecord(publishConfig?.exports) ? publishConfig.exports : undefined\n\n const exportsMatch = hasMatchingExport(pkg.exports?.[exportKey], conditionalExport)\n const publishConfigExportsMatch =\n !publishConfigExports || hasMatchingExport(publishConfigExports[exportKey], conditionalExport)\n\n if (exportsMatch && publishConfigExportsMatch) {\n return\n }\n\n pkg.exports = insertCssExport(pkg.exports ?? {}, exportKey, conditionalExport)\n\n if (publishConfig && publishConfigExports) {\n publishConfig.exports = insertCssExport(publishConfigExports, exportKey, conditionalExport)\n }\n\n await writeFile(pkgPath, `${JSON.stringify(pkg, null, detectIndent(source))}\\n`)\n logger.log(\n `Updated package.json: added \\`exports[\"${exportKey}\"]\\`${\n publishConfigExports ? ` and \\`publishConfig.exports[\"${exportKey}\"]\\`` : ''\n } for vanilla-extract compat mode`,\n )\n}\n","import {up as findPkgPath} from 'empathic/package'\nimport type {Subscription} from 'rxjs'\nimport {switchMap} from 'rxjs'\nimport {build as tsdownBuild, type TsdownBundle} from 'tsdown'\nimport {loadConfig} from './core/config/loadConfig.ts'\nimport {isRecord} from './core/isRecord.ts'\nimport {loadPkgWithReporting} from './core/pkg/loadPkgWithReporting.ts'\nimport {writeBundleCssExports} from './core/pkg/writeBundleCssExports.ts'\nimport {createLogger} from './logger.ts'\nimport {resolveBuildContext} from './resolveBuildContext.ts'\nimport {resolveTsdownBuilds} from './tasks/tsdown/resolveTsdownBuilds.ts'\nimport {resolveTsdownConfig} from './tasks/tsdown/resolveTsdownConfig.ts'\n\nconst asyncDispose: typeof Symbol.asyncDispose =\n Symbol.asyncDispose || Symbol.for('Symbol.asyncDispose')\n\n/** @public */\nexport async function watch(options: {\n cwd: string\n strict?: boolean\n tsconfig?: string\n signal?: AbortSignal\n}): Promise<void> {\n const {cwd, strict = false, tsconfig: tsconfigOption, signal} = options\n\n const logger = createLogger()\n\n const {watchConfigFiles} = await import('./watchConfigFiles.ts')\n const configFiles$ = await watchConfigFiles({cwd, logger})\n\n // Every rebuild of the waterfall holds tsdown watchers (one per platform build); they are\n // disposed when the config files change (the waterfall restarts) or the signal aborts.\n // RxJS does not await async subscriber callbacks, so a monotonically increasing run id\n // guards the rebuilds: only the latest run may publish into `bundles`, and a run that turns\n // stale mid-flight (a newer config-file event, or the abort signal) disposes the watchers\n // it created instead of leaking them.\n let bundles: TsdownBundle[] = []\n let runId = 0\n const disposeBundles = async () => {\n const disposing = bundles\n bundles = []\n for (const bundle of disposing) {\n await bundle[asyncDispose]()\n }\n }\n\n const ctx$ = configFiles$.pipe(\n switchMap(async () => {\n const pkgPath = findPkgPath({cwd})\n if (!pkgPath) {\n throw new Error('missing package.json', {cause: {cwd}})\n }\n\n const config = await loadConfig({cwd, pkgPath})\n const {parseStrictOptions} = await import('./strict.ts')\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n const pkg = await loadPkgWithReporting({pkgPath, logger, strict, strictOptions})\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n return resolveBuildContext({config, cwd, logger, pkg, strict, tsconfig})\n }),\n )\n\n const ctxSubscription: Subscription = ctx$.subscribe(async (ctx) => {\n const id = ++runId\n const runBundles: TsdownBundle[] = []\n try {\n await disposeBundles()\n\n // Full builds write the conditional `./<css>` export through tsdown's\n // `exports.customExports` composition, but watch mode disables tsdown's `exports` feature\n // (a package.json write per rebuild would loop the watcher). Keep the export in sync here\n // instead, once per context, like v11 — the write is idempotent, so it won't loop.\n const vanillaExtract = ctx.config?.vanillaExtract\n if (vanillaExtract) {\n const veOptions = vanillaExtract === true ? {} : vanillaExtract\n // `@sanity/tsdown-config` defaults `inject` to `{nodeCompat: true}` (the conditional\n // CSS export pattern); an explicit user `inject` replaces that default\n const inject = veOptions.inject ?? {nodeCompat: true}\n if (isRecord(inject) && inject['nodeCompat']) {\n await writeBundleCssExports({\n cwd,\n distPath: ctx.distPath,\n cssName: veOptions.fileName || 'bundle.css',\n logger,\n })\n }\n }\n\n const builds = resolveTsdownBuilds(ctx)\n\n let first = true\n for (const buildDef of builds) {\n if (id !== runId) break\n\n const inlineConfig = await resolveTsdownConfig(ctx, buildDef, {\n clean: first,\n watch: true,\n })\n first = false\n\n runBundles.push(...(await tsdownBuild(inlineConfig)))\n }\n\n if (id !== runId) {\n // A newer run (or the abort signal) took over while this rebuild was in flight —\n // dispose everything this run created instead of publishing it\n for (const bundle of runBundles) {\n await bundle[asyncDispose]()\n }\n return\n }\n\n bundles = runBundles\n\n logger.success(`${ctx.pkg.name}: watching for file changes\\u2026`)\n logger.log()\n } catch (err) {\n ctx.logger.error(err)\n ctx.logger.log()\n\n process.exit(1)\n }\n })\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n runId++\n ctxSubscription.unsubscribe()\n void disposeBundles()\n },\n {once: true},\n )\n }\n}\n","import {watch} from '../node/watch.ts'\nimport {handleError} from './handleError.ts'\n\nexport async function watchAction(options: {strict?: boolean; tsconfig?: string}): Promise<void> {\n try {\n await watch({\n cwd: process.cwd(),\n str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