@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
@@ -5,7 +5,7 @@ import path, { resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { tsImport } from "tsx/esm/api";
7
7
  import findConfig from "find-config";
8
- import { ZodError, _typoMap, parseExports, parsePackage } from "@sanity/parse-package-json";
8
+ import { ZodError, _typoMap, parseCssExports, parseExports, parsePackage } from "@sanity/parse-package-json";
9
9
  import chalk from "chalk";
10
10
  import fs from "node:fs/promises";
11
11
  import browserslistToEsbuild from "browserslist-to-esbuild";
@@ -170,13 +170,24 @@ function runLegacyConfigChecks(config) {
170
170
  ...dts === "rolldown" ? ["`dts: 'rolldown'` is the default behavior now: delete the option. Options that", "accompanied it move into the object, e.g. `tsgo: true` becomes `dts: {tsgo: true}`."] : [
171
171
  "`dts: 'api-extractor'` type generation was removed. Types are generated with",
172
172
  "tsdown (rolldown-plugin-dts); api-extractor remains as the TSDoc/release-tag",
173
- "checking that runs during `pkg check` — configure it with the `tsdoc` option."
173
+ "checking that runs during `pkg build`/`pkg check` — configure it with the",
174
+ "`tsdoc` option."
174
175
  ],
175
176
  "",
176
177
  `Full migration guide: ${MIGRATION_GUIDE_URL}`,
177
178
  "Set `legacyChecks: false` in package.config.ts to skip this validation (it is also",
178
179
  "skipped when NODE_ENV=production)."
179
180
  ].join("\n"));
181
+ for (let option of ["vanillaExtract", "css"]) {
182
+ let value = config[option];
183
+ if (typeof value != "object" || !value) continue;
184
+ let inject = value.inject;
185
+ typeof inject != "object" || !inject || inject.nodeCompat !== void 0 && console.warn([
186
+ `package.config.ts: \`${option}.inject.nodeCompat\` is deprecated. Use`,
187
+ `\`${option}: {inject: true, exports: {nodeCompat: true}}\` instead — \`nodeCompat\``,
188
+ "configures the package exports, not the injected import."
189
+ ].join("\n"));
190
+ }
180
191
  config.external !== void 0 && console.warn([
181
192
  "package.config.ts: `external` is deprecated. Use `deps: {neverBundle: [...]}` to mark",
182
193
  "dependencies as external, and `deps: {alwaysBundle: [...]}` to bundle a dependency",
@@ -375,10 +386,15 @@ async function loadPkgWithReporting(options) {
375
386
  }
376
387
  }
377
388
  if (strict && pkg.exports && Object.keys(pkg.exports).length > 0 && Object.entries(pkg.exports).some(([, exp]) => typeof exp == "string" || typeof exp == "object" && "svelte" in exp ? !1 : !!(exp.source || exp.development || exp.monorepo))) if (pkg.publishConfig?.exports) {
378
- let publishExports = pkg.publishConfig.exports;
379
- for (let exportPath of Object.keys(pkg.exports)) exportPath in publishExports || (shouldError = !0, logger.error(`publishConfig.exports: missing export path "${exportPath}" that exists in exports`));
389
+ let publishExports = pkg.publishConfig.exports, isBuiltCssExport = (exportPath) => {
390
+ if (!exportPath.endsWith(".css")) return !1;
391
+ let exp = pkg.exports?.[exportPath];
392
+ return typeof exp == "object" && !!exp && "source" in exp;
393
+ };
394
+ for (let exportPath of Object.keys(pkg.exports)) !(exportPath in publishExports) && !isBuiltCssExport(exportPath) && (shouldError = !0, logger.error(`publishConfig.exports: missing export path "${exportPath}" that exists in exports`));
380
395
  for (let exportPath of Object.keys(publishExports)) exportPath in pkg.exports || (shouldError = !0, logger.error(`publishConfig.exports: unexpected export path "${exportPath}" that does not exist in exports`));
381
396
  for (let [exportPath, exp] of Object.entries(pkg.exports)) {
397
+ if (isBuiltCssExport(exportPath)) continue;
382
398
  if (typeof exp == "string" || "svelte" in exp) {
383
399
  let publishExp = publishExports[exportPath];
384
400
  typeof publishExp != "string" && (typeof publishExp != "object" || !("svelte" in publishExp)) && (shouldError = !0, logger.error(`publishConfig.exports["${exportPath}"]: should be a string matching exports["${exportPath}"]`));
@@ -525,7 +541,13 @@ function parseAndValidateExports(options) {
525
541
  strict && strictOptions.noPackageJsonTypings !== "off" && "typings" in pkg && report(strictOptions.noPackageJsonTypings, "package.json: `typings` should be `types`"), strict && strictOptions.alwaysPackageJsonTypes !== "off" && !pkg.types && typeof pkg.exports?.["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source?.endsWith(".ts") && report(strictOptions.alwaysPackageJsonTypes, "package.json: `types` must be declared for the npm listing to show as a TypeScript module."), strict && !pkg.exports["./package.json"] && errors.push("package.json: `exports[\"./package.json\"] must be declared.");
526
542
  for (let [exportPath, exportEntry] of Object.entries(pkg.exports)) if (exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json")) exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push("package.json: `exports[\"./package.json\"]` must be \"./package.json\".");
527
543
  else if (exportPath.endsWith(".css")) if (typeof exportEntry == "string") existsSync(resolve(cwd, exportEntry)) || errors.push(`package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`);
528
- else if (isRecord(exportEntry)) for (let [condition, target] of Object.entries(exportEntry)) typeof target != "string" && errors.push(`package.json: \`exports[${JSON.stringify(exportPath)}][${JSON.stringify(condition)}]\`: must be a string path.`);
544
+ else if (isRecord(exportEntry)) for (let [condition, target] of Object.entries(exportEntry)) {
545
+ if (typeof target != "string") {
546
+ errors.push(`package.json: \`exports[${JSON.stringify(exportPath)}][${JSON.stringify(condition)}]\`: must be a string path.`);
547
+ continue;
548
+ }
549
+ condition === "source" && !existsSync(resolve(cwd, target)) && errors.push(`package.json: \`exports[${JSON.stringify(exportPath)}].source\`: file does not exist.`);
550
+ }
529
551
  else errors.push(`package.json: \`exports[${JSON.stringify(exportPath)}]\`: must be a string path or an object of export conditions.`);
530
552
  else if (!(isRecord(exportEntry) && "svelte" in exportEntry)) if (isPkgExport(exportEntry)) {
531
553
  let exp = {
@@ -627,7 +649,7 @@ async function resolveBuildContext(options) {
627
649
  strict,
628
650
  strictOptions,
629
651
  logger
630
- }).reduce((acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }), {}), exports = resolveConfigProperty(config?.exports, parsedExports), parsedExternal = [...pkg.dependencies ? Object.keys(pkg.dependencies) : [], ...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []], external = config && Array.isArray(config.external) ? [...parsedExternal, ...config.external] : resolveConfigProperty(config?.external, parsedExternal), packagePattern = (name) => RegExp(`^${escapeRegExp(name)}(/|$)`), neverBundleAdditions = external.filter((name) => !parsedExternal.includes(name)).map(packagePattern);
652
+ }).reduce((acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }), {}), exports = resolveConfigProperty(config?.exports, parsedExports), cssExports = parseCssExports({ pkg }), parsedExternal = [...pkg.dependencies ? Object.keys(pkg.dependencies) : [], ...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []], external = config && Array.isArray(config.external) ? [...parsedExternal, ...config.external] : resolveConfigProperty(config?.external, parsedExternal), packagePattern = (name) => RegExp(`^${escapeRegExp(name)}(/|$)`), neverBundleAdditions = external.filter((name) => !parsedExternal.includes(name)).map(packagePattern);
631
653
  neverBundleAdditions.push(packagePattern(pkg.name));
632
654
  let alwaysBundleNames = parsedExternal.filter((name) => !external.includes(name)), deps = mergeDeps(config?.deps, {
633
655
  neverBundle: neverBundleAdditions,
@@ -661,6 +683,7 @@ async function resolveBuildContext(options) {
661
683
  distPath,
662
684
  emitDeclarationOnly,
663
685
  exports,
686
+ cssExports,
664
687
  external,
665
688
  bundledPackages,
666
689
  logger,
@@ -711,4 +734,4 @@ function transformPackageName(packageName) {
711
734
  }
712
735
  export { loadPkgWithReporting as a, pkgExtMap as i, strict_exports as n, loadConfig as o, fileEnding as r, resolveBuildContext as t };
713
736
 
714
- //# sourceMappingURL=resolveBuildContext-CbwvYKj1.js.map
737
+ //# sourceMappingURL=resolveBuildContext-clvZ-QQy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveBuildContext-clvZ-QQy.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 build`/`pkg check` — configure it with the',\n '`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: `inject: {nodeCompat: true}` still works (it means\n // `{inject: true, exports: {nodeCompat: true}}`), with a nudge toward its successor. The\n // option configures how the CSS file is published, not how the import is injected.\n for (const option of ['vanillaExtract', 'css'] as const) {\n const value = config[option]\n if (typeof value !== 'object' || value === null) continue\n // oxlint-disable-next-line no-unsafe-type-assertion\n const inject = (value as {inject?: unknown}).inject\n if (typeof inject !== 'object' || inject === null) continue\n // oxlint-disable-next-line no-unsafe-type-assertion\n if ((inject as {nodeCompat?: unknown}).nodeCompat === undefined) continue\n // eslint-disable-next-line no-console -- config-load-time deprecation warning\n console.warn(\n [\n `package.config.ts: \\`${option}.inject.nodeCompat\\` is deprecated. Use`,\n `\\`${option}: {inject: true, exports: {nodeCompat: true}}\\` instead — \\`nodeCompat\\``,\n 'configures the package exports, not the injected import.',\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 // A `.css` subpath with a `source` is a stylesheet built by the CSS pipeline, which\n // fills the subpath into both maps. Until the first build runs, `exports` holds\n // nothing but the `source` the author wrote and `publishConfig.exports` holds\n // nothing at all — the documented way to declare one — so it is exempt from the\n // cross-map checks below.\n const isBuiltCssExport = (exportPath: string): boolean => {\n if (!exportPath.endsWith('.css')) return false\n const exp = pkg.exports?.[exportPath]\n return typeof exp === 'object' && exp !== null && 'source' in exp\n }\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) && !isBuiltCssExport(exportPath)) {\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 (isBuiltCssExport(exportPath)) continue\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 continue\n }\n // With a `source`, the subpath is a build entry: the stylesheet is compiled by the\n // CSS pipeline, so unlike the generated conditions the source has to exist now.\n if (condition === 'source' && !existsSync(resolvePath(cwd, target))) {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}].source\\`: file does not exist.`,\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 {parseCssExports, 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 cssExports = parseCssExports({pkg})\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 TSDoc check\n // (`tsdoc.bundledPackages`): devDependencies that are not external (like v11), plus any\n // string entries of the `deps.alwaysBundle` passthrough (force-bundled deps inline 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 cssExports,\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;GAC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AChD,IAAM,WAAW,UAAU;EAC3B,eAAe,IAAI,UAAU,eAC3B,SAAS,MAAM,YACb,OAAO,WAAY,WAAW,YAAY,KAAK,QAAQ,KAAK,EAAE,CAChE,KAAK,gBAAgB,IAAI,UAAU,UAAU;CACjD,OAAO,AAGL,cAHS,MAAM,QAAQ,eAAe,IACxB,CAAC,GAAG,UAAU,aAAa,GAAG,eAAe,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,5 +1,5 @@
1
1
  import { r as isRecord } from "./handleError-83GwKIFM.js";
2
- import { i as pkgExtMap, r as fileEnding } from "./resolveBuildContext-CbwvYKj1.js";
2
+ import { i as pkgExtMap, r as fileEnding } from "./resolveBuildContext-clvZ-QQy.js";
3
3
  import path from "node:path";
4
4
  import { mergeConfig } from "tsdown";
5
5
  import { defineConfig } from "@sanity/tsdown-config";
@@ -71,7 +71,20 @@ function resolveTsdownBuilds(ctx) {
71
71
  " `tsdown.config.ts` with one config per `platform` — the fully supported path for",
72
72
  " this level of customization."
73
73
  ].join("\n"));
74
- let builds = [], toBuild = (key, runtime, canonical) => {
74
+ let builds = [], cssEntries = ctx.cssExports.map((cssExport) => ({
75
+ alias: cssEntryAlias(cssExport._path),
76
+ source: cssExport.source,
77
+ exportPath: cssExport._path,
78
+ formats: ["esm"]
79
+ }));
80
+ cssEntries.length && builds.push({
81
+ key: "css",
82
+ runtime: ctx.runtime,
83
+ canonical: !1,
84
+ entries: cssEntries,
85
+ css: !0
86
+ });
87
+ let toBuild = (key, runtime, canonical) => {
75
88
  let drafts = draftsByBuild.get(key);
76
89
  return !drafts || drafts.size === 0 ? null : {
77
90
  key,
@@ -94,6 +107,67 @@ function resolveTsdownBuilds(ctx) {
94
107
  return canonical && builds.push(canonical), builds;
95
108
  }
96
109
  /**
110
+ * The tsdown entry alias of a `.css` export subpath: the subpath without its leading `./` and
111
+ * `.css` ending, so `@tsdown/css` (with `splitting`) emits the stylesheet at exactly the path
112
+ * the subpath promises — `"./ui/styles.css"` -> alias `ui/styles` -> `dist/ui/styles.css`.
113
+ */
114
+ function cssEntryAlias(exportPath) {
115
+ return exportPath.replace(/^\.\//, "").replace(/\.css$/, "");
116
+ }
117
+ /**
118
+ * The no-op JS shim file name for a CSS file under vanilla-extract compat mode.
119
+ *
120
+ * `bundle.css` → `bundle-css.js` — deliberately not `${cssFileName}.js` (`bundle.css.js`),
121
+ * which vanilla-extract's `cssFileFilter` (`/\.css\.(js|cjs|mjs|jsx|ts|tsx)$/`) would treat as
122
+ * a stylesheet module. Kept in sync with `cssShimFileName` in
123
+ * `@sanity/vanilla-extract-rolldown-plugin`.
124
+ *
125
+ * @internal
126
+ */
127
+ function cssShimFileName(cssFileName) {
128
+ return `${cssFileName.replace(/\.css$/, "-css")}.js`;
129
+ }
130
+ /**
131
+ * The `.d.ts` companion for {@link cssShimFileName}. `bundle.css` → `bundle-css.d.ts`.
132
+ *
133
+ * @internal
134
+ */
135
+ function cssShimDtsFileName(cssFileName) {
136
+ return `${cssFileName.replace(/\.css$/, "-css")}.d.ts`;
137
+ }
138
+ /**
139
+ * Build the conditional CSS export object that `exports.nodeCompat` expects, e.g.
140
+ * ```json
141
+ * {
142
+ * "types": "./dist/bundle-css.d.ts",
143
+ * "browser": "./dist/bundle.css",
144
+ * "style": "./dist/bundle.css",
145
+ * "node": "./dist/bundle-css.js",
146
+ * "default": "./dist/bundle-css.js"
147
+ * }
148
+ * ```
149
+ * The shim is named `bundle-css.js` (not `bundle.css.js`) so it does not match
150
+ * vanilla-extract's `cssFileFilter`. An explicit `types` condition (rather than relying on
151
+ * TypeScript's extension-substitution fallback, which only works when the shim shares the CSS
152
+ * file's basename, and which TypeScript is deprecating anyway - microsoft/TypeScript#50762)
153
+ * points resolvers straight at the shim's declaration file.
154
+ *
155
+ * Kept in sync with `createConditionalCssExport` in `@sanity/vanilla-extract-tsdown-plugin`,
156
+ * which writes the same entry through tsdown's `exports.customExports` during full builds.
157
+ *
158
+ * @internal
159
+ */
160
+ function createConditionalCssExport(cssName, distRel) {
161
+ let cssFile = `./${path.posix.join(distRel, cssName)}`, shimFile = `./${path.posix.join(distRel, cssShimFileName(cssName))}`;
162
+ return {
163
+ types: `./${path.posix.join(distRel, cssShimDtsFileName(cssName))}`,
164
+ browser: cssFile,
165
+ style: cssFile,
166
+ node: shimFile,
167
+ default: shimFile
168
+ };
169
+ }
170
+ /**
97
171
  * The pkg-utils opinion layer over tsdown's generated `exports` map, composed into
98
172
  * `exports.customExports` of the canonical build (the same composition hook
99
173
  * `@sanity/vanilla-extract-tsdown-plugin` uses for its conditional CSS export).
@@ -122,7 +196,9 @@ function resolveTsdownBuilds(ctx) {
122
196
  * @internal
123
197
  */
124
198
  function createExportsComposer(ctx, build) {
125
- let { pkg } = ctx, type = pkg.type === "module" ? "module" : "commonjs", aliasToExportPath = /* @__PURE__ */ new Map();
199
+ let { pkg } = ctx, type = pkg.type === "module" ? "module" : "commonjs", distRel = (path.relative(ctx.cwd, ctx.distPath) || "dist").split(path.sep).join("/"), cssExportPaths = new Set(ctx.cssExports.map((cssExport) => cssExport._path)), cssSources = {};
200
+ for (let cssExport of ctx.cssExports) cssSources[cssExport._path] = cssExport.source;
201
+ let aliasToExportPath = /* @__PURE__ */ new Map();
126
202
  for (let entry of build.entries) entry.exportPath !== void 0 && aliasToExportPath.set(entry.alias, entry.exportPath);
127
203
  return (exportsMap, context) => {
128
204
  let { isPublish } = context, remapped = {};
@@ -141,12 +217,28 @@ function createExportsComposer(ctx, build) {
141
217
  });
142
218
  }, authoredPaths = Object.keys(authoredRaw);
143
219
  for (let exportPath of Object.keys(sourceRaw)) Object.prototype.hasOwnProperty.call(authoredRaw, exportPath) || authoredPaths.push(exportPath);
144
- for (let exportPath of authoredPaths) result[exportPath] = exportPath in remapped ? reconcile(exportPath, remapped[exportPath]) : Object.prototype.hasOwnProperty.call(authoredRaw, exportPath) ? authoredRaw[exportPath] : sourceRaw[exportPath];
220
+ for (let exportPath of authoredPaths) result[exportPath] = exportPath in remapped ? reconcile(exportPath, remapped[exportPath]) : cssExportPaths.has(exportPath) ? reconcileCssEntry(exportPath, {
221
+ distRel,
222
+ source: cssSources[exportPath],
223
+ isPublish
224
+ }) : Object.prototype.hasOwnProperty.call(authoredRaw, exportPath) ? authoredRaw[exportPath] : sourceRaw[exportPath];
145
225
  for (let [exportPath, value] of Object.entries(remapped)) exportPath in result || (result[exportPath] = reconcile(exportPath, value));
146
226
  return result;
147
227
  };
148
228
  }
149
229
  /**
230
+ * The conditional CSS export of a `.css` subpath built by the stylesheet build. `source`
231
+ * resolves at development time, so it is kept in `exports` and stripped from the publish
232
+ * variant — the same split the build entries get.
233
+ */
234
+ function reconcileCssEntry(exportPath, options) {
235
+ let { distRel, source, isPublish } = options, conditions = createConditionalCssExport(exportPath.replace(/^\.\//, ""), distRel);
236
+ return isPublish || source === void 0 ? conditions : {
237
+ source,
238
+ ...conditions
239
+ };
240
+ }
241
+ /**
150
242
  * Rebuilds a generated subpath entry in its authored condition order, re-inserting the
151
243
  * hand-written conditions tsdown's generator cannot express.
152
244
  */
@@ -235,19 +327,25 @@ async function resolveTsdownConfig(ctx, build, options) {
235
327
  ctx.logger.warn(`${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.`);
236
328
  }
237
329
  }
238
- let format = [...formats.has("esm") ? ["esm"] : [], ...formats.has("commonjs") ? ["cjs"] : []], platform = build.runtime === "node" ? "node" : build.runtime === "browser" ? "browser" : "neutral", define = {};
330
+ let format = [...formats.has("esm") ? ["esm"] : [], ...formats.has("commonjs") ? ["cjs"] : []], platform = build.runtime === "node" ? "node" : build.runtime === "browser" ? "browser" : "neutral", css = config?.css || ctx.cssExports.length ? {
331
+ ...config?.css,
332
+ ...build.css ? { splitting: !0 } : {}
333
+ } : void 0, define = {};
239
334
  pkg.name !== "@sanity/pkg-utils" && (define["process.env.PKG_VERSION"] = JSON.stringify(process.env.PKG_VERSION || pkg.version));
240
335
  for (let [key, value] of Object.entries(config?.define || {})) define[key] = JSON.stringify(value);
241
- let hasTsSources = build.entries.some((buildEntry) => RE_TS_SOURCE.test(buildEntry.source)), dtsPassthrough = typeof config?.dts == "object" ? config.dts : void 0, dts = hasTsSources && config?.dts !== !1 ? {
336
+ let hasTsSources = !build.css && build.entries.some((buildEntry) => RE_TS_SOURCE.test(buildEntry.source)), dtsPassthrough = typeof config?.dts == "object" ? config.dts : void 0, dts = hasTsSources && config?.dts !== !1 ? {
242
337
  ...typeof pkg.devDependencies == "object" && "@typescript/native-preview" in pkg.devDependencies ? { tsgo: !0 } : {},
243
338
  newContext: !0,
244
339
  ...dtsPassthrough,
245
340
  ...ctx.emitDeclarationOnly ? { emitDtsOnly: !0 } : {}
246
- } : !1, exports = build.canonical && !ctx.emitDeclarationOnly && !options.watch ? {
341
+ } : !1, exports = build.canonical && !ctx.emitDeclarationOnly && !options.watch && !build.css ? {
247
342
  devExports: "source",
248
343
  customExports: createExportsComposer(ctx, build),
249
344
  ...pkg.main || pkg.module ? { legacy: !0 } : {}
250
- } : !1, base = await defineConfig({
345
+ } : !1, tsdocOption = config?.tsdoc !== !1 && {
346
+ ...typeof config?.tsdoc == "object" ? config.tsdoc : {},
347
+ bundledPackages: ctx.bundledPackages
348
+ }, base = await defineConfig({
251
349
  cwd,
252
350
  tsconfig: ctx.ts.configPath,
253
351
  platform,
@@ -261,9 +359,11 @@ async function resolveTsdownConfig(ctx, build, options) {
261
359
  dts,
262
360
  deps: ctx.deps,
263
361
  exports,
362
+ css,
264
363
  reactCompiler: config?.reactCompiler,
265
364
  styledComponents: config?.styledComponents,
266
- vanillaExtract: config?.vanillaExtract
365
+ vanillaExtract: config?.vanillaExtract,
366
+ tsdoc: !options.watch && tsdocOption
267
367
  }), extMap = pkgExtMap[pkg.type === "module" ? "module" : "commonjs"], outExtensions = ({ format: outputFormat }) => ({ js: outputFormat === "cjs" ? extMap.commonjs : extMap.esm });
268
368
  return {
269
369
  ...mergeConfig(base, {
@@ -271,13 +371,44 @@ async function resolveTsdownConfig(ctx, build, options) {
271
371
  publint: !1,
272
372
  report: !1,
273
373
  ...config?.minify === !0 ? { minify: !0 } : {},
274
- ...config?.plugins === void 0 ? {} : { plugins: config.plugins }
374
+ ...config?.plugins === void 0 ? {} : { plugins: config.plugins },
375
+ ...options.watch && css ? { hooks: createWatchCssExportsHook(ctx, css) } : {}
275
376
  }),
276
377
  config: !1,
277
378
  logLevel: "warn",
278
379
  ...options.watch ? { watch: !0 } : {}
279
380
  };
280
381
  }
281
- export { resolveTsdownBuilds as n, resolveTsdownConfig as t };
382
+ /**
383
+ * Declares the conditional export of every CSS file a watch rebuild emitted.
384
+ *
385
+ * A full build leaves this to `cssNodeCompatPlugin`, which composes into tsdown's
386
+ * `exports.customExports`. Watch mode turns tsdown's `exports` feature off (a `package.json`
387
+ * write per rebuild would loop the watcher), so `pkg watch` maintains the exports itself. Most
388
+ * of them are known before the build and are written once per context in `watch.ts`, but the
389
+ * merged `style.css` of CSS imported from JS only exists when something actually imports CSS —
390
+ * declaring it from the config alone would point the export at files nobody produced.
391
+ *
392
+ * `build:done` is the only place that knows: in watch mode `build()` resolves before the first
393
+ * rebuild runs, so the returned bundle's chunks are still empty. The write is idempotent, so
394
+ * the `package.json` watcher settles after one extra rebuild rather than looping.
395
+ * @internal
396
+ */
397
+ function createWatchCssExportsHook(ctx, css) {
398
+ let mergedCssName = css.splitting ? void 0 : css.fileName || "style.css";
399
+ return (hooks) => {
400
+ hooks.hook("build:done", async ({ chunks }) => {
401
+ if (mergedCssName === void 0 || !chunks.some((chunk) => chunk.type === "asset" && chunk.fileName === mergedCssName)) return;
402
+ let { writeBundleCssExports } = await import("./writeBundleCssExports-8AIeBdCf.js").then((n) => n.n);
403
+ await writeBundleCssExports({
404
+ cwd: ctx.cwd,
405
+ distPath: ctx.distPath,
406
+ cssNames: [mergedCssName],
407
+ logger: ctx.logger
408
+ });
409
+ });
410
+ };
411
+ }
412
+ export { createConditionalCssExport as n, resolveTsdownBuilds as r, resolveTsdownConfig as t };
282
413
 
283
- //# sourceMappingURL=resolveTsdownConfig-CGE_7cMM.js.map
414
+ //# sourceMappingURL=resolveTsdownConfig-fBDvhjvu.js.map