@sanity/pkg-utils 12.1.1 → 12.1.3

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.
@@ -1,7 +1,7 @@
1
1
  import { n as createLogger, r as isRecord, t as handleError } from "./handleError-83GwKIFM.js";
2
- import { a as loadPkgWithReporting, o as loadConfig, t as resolveBuildContext } from "./resolveBuildContext-DYZxWVVc.js";
2
+ import { a as loadPkgWithReporting, o as loadConfig, t as resolveBuildContext } from "./resolveBuildContext-vVTRkIDl.js";
3
3
  import { t as createSpinner } from "./spinner-DAHe7SuT.js";
4
- import { r as resolveTsdownBuilds, t as resolveTsdownConfig } from "./resolveTsdownConfig-D4boYIwx.js";
4
+ import { r as resolveTsdownBuilds, t as resolveTsdownConfig } from "./resolveTsdownConfig-I9zyPE-E.js";
5
5
  import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { up } from "empathic/package";
@@ -32,7 +32,7 @@ async function build$1(options) {
32
32
  let config = await loadConfig({
33
33
  cwd,
34
34
  pkgPath
35
- }), { parseStrictOptions } = await import("./resolveBuildContext-DYZxWVVc.js").then((n) => n.n), strictOptions = parseStrictOptions(config?.strictOptions ?? {}), pkg = await loadPkgWithReporting({
35
+ }), { parseStrictOptions } = await import("./resolveBuildContext-vVTRkIDl.js").then((n) => n.n), strictOptions = parseStrictOptions(config?.strictOptions ?? {}), pkg = await loadPkgWithReporting({
36
36
  pkgPath,
37
37
  logger,
38
38
  strict,
@@ -147,4 +147,4 @@ async function buildAction(options) {
147
147
  }
148
148
  export { buildAction };
149
149
 
150
- //# sourceMappingURL=buildAction-C8MCKsDz.js.map
150
+ //# sourceMappingURL=buildAction-HQvn8xA1.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"buildAction-C8MCKsDz.js","names":["build","findPkgPath","tsdownBuild","build"],"sources":["../src/node/build.ts","../src/cli/buildAction.ts"],"sourcesContent":["import {existsSync, readFileSync, rmSync, writeFileSync} from 'node:fs'\nimport path from 'node:path'\nimport {up as findPkgPath} from 'empathic/package'\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 {createLogger, type Logger} from './logger.ts'\nimport {resolveBuildContext} from './resolveBuildContext.ts'\nimport {createSpinner} from './spinner.ts'\nimport {\n resolveTsdownBuilds,\n type TsdownBuild as TsdownBuildDef,\n} from './tasks/tsdown/resolveTsdownBuilds.ts'\nimport {resolveTsdownConfig} from './tasks/tsdown/resolveTsdownConfig.ts'\n\nconst RE_TS_SOURCE = /\\.[cm]?tsx?$/\n\n/**\n * Build the distribution files of a npm package.\n *\n * @example\n * ```ts\n * import {build} from '@sanity/pkg-utils'\n *\n * build({\n * cwd: process.cwd(),\n * tsconfig: 'tsconfig.dist.json,\n * }).then(() => {\n * console.log('successfully built')\n * }).catch((err) => {\n * console.log(`build error: ${err.message}`)\n * })\n * ```\n *\n * @public\n */\nexport async function build(options: {\n cwd: string\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n const {\n cwd,\n emitDeclarationOnly,\n strict = false,\n tsconfig: tsconfigOption,\n // `--no-clean` skips cleaning for this run; `true` (the CLI default — `--clean` still\n // parses as a no-op for v11 compatibility) defers to the `clean` config option\n clean = true,\n quiet = false,\n } = options\n const logger = createLogger(quiet)\n\n const pkgPath = findPkgPath({cwd})\n if (!pkgPath) {\n throw new Error('no package.json found', {cause: {cwd}})\n }\n const config = await loadConfig({cwd, pkgPath})\n\n const {parseStrictOptions} = await import('./strict.ts')\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n const pkg = await loadPkgWithReporting({pkgPath, logger, strict, strictOptions})\n\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n const ctx = await resolveBuildContext({\n config,\n cwd,\n emitDeclarationOnly,\n logger,\n pkg,\n strict,\n tsconfig,\n })\n\n warnAboutTsdownConfigFiles(cwd, logger)\n\n const builds = resolveTsdownBuilds(ctx)\n\n let first = true\n for (const buildDef of builds) {\n // A types-only run skips builds without TypeScript sources entirely\n if (\n ctx.emitDeclarationOnly &&\n !buildDef.entries.some((entry) => RE_TS_SOURCE.test(entry.source))\n ) {\n continue\n }\n\n const taskName = buildTaskName(buildDef)\n const spinner = createSpinner(taskName, quiet)\n\n try {\n const inlineConfig = await resolveTsdownConfig(ctx, buildDef, {clean: first && clean})\n first = false\n\n const bundles = await tsdownBuild(inlineConfig)\n\n if (ctx.emitDeclarationOnly) {\n // `dts.emitDtsOnly` suppresses the JS chunks of the ES pass, but the CJS pass emits\n // its JS regardless (only its extra dts pass runs the dts plugin) — a types-only\n // build removes everything that is not a declaration file\n removeNonDeclarationOutputs(bundles)\n }\n\n if (buildDef.canonical) {\n restoreAuthoredTypes(ctx)\n }\n\n spinner.complete()\n ctx.logger.log()\n\n printBuildOutputs(ctx, bundles, buildDef)\n ctx.logger.log()\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(escapeRegExp(cwd), 'g')\n\n ctx.logger.error((err.stack || err.message).replace(RE_CWD, '.'))\n ctx.logger.log()\n }\n\n process.exit(1)\n }\n }\n}\n\nfunction buildTaskName(buildDef: TsdownBuildDef): string {\n const formats = Array.from(new Set(buildDef.entries.flatMap((entry) => entry.formats)))\n return `build ${buildDef.key} (${formats.join(', ') || 'types'})`\n}\n\nconst RE_DTS_OUTPUT = /\\.d\\.[mc]?ts(\\.map)?$/\n\n/** Removes every emitted file that is not a declaration file (or its sourcemap). */\nfunction removeNonDeclarationOutputs(bundles: TsdownBundle[]): void {\n for (const bundle of bundles) {\n for (const chunk of bundle.chunks) {\n if (RE_DTS_OUTPUT.test(chunk.fileName)) continue\n rmSync(path.join(chunk.outDir, chunk.fileName), {force: true})\n rmSync(path.join(chunk.outDir, `${chunk.fileName}.map`), {force: true})\n }\n }\n}\n\n/**\n * Prints `<pkg>: <source> → <output>` for every entry chunk (JS and `.d.ts`) that tsdown\n * emitted, mirroring the per-file output of previous majors.\n */\nfunction printBuildOutputs(\n ctx: {\n cwd: string\n distPath: string\n emitDeclarationOnly: boolean\n logger: Logger\n pkg: {name: string}\n },\n bundles: TsdownBundle[],\n buildDef: TsdownBuildDef,\n): void {\n const {cwd, logger, pkg} = ctx\n const lines = new Set<string>()\n\n // Stylesheets are emitted as assets, which carry no `facadeModuleId` back to their source,\n // so the stylesheet build's lines come from its entry map instead.\n if (buildDef.css) {\n for (const entry of buildDef.entries) {\n const output = `./${path\n .relative(cwd, path.join(ctx.distPath, `${entry.alias}.css`))\n .replaceAll('\\\\', '/')}`\n lines.add(\n `${pkg.name}: ./${path.relative(cwd, path.resolve(cwd, entry.source)).replaceAll('\\\\', '/')} \\u2192 ${output}`,\n )\n }\n }\n\n for (const bundle of bundles) {\n for (const chunk of bundle.chunks) {\n if (chunk.type !== 'chunk' || !chunk.isEntry || !chunk.facadeModuleId) continue\n if (ctx.emitDeclarationOnly && !RE_DTS_OUTPUT.test(chunk.fileName)) continue\n const source = `./${path\n .relative(cwd, chunk.facadeModuleId)\n .replaceAll('\\\\', '/')\n // the dts chunks facade the fake `.d.ts` module ids of rolldown-plugin-dts; print the\n // actual `.ts` source instead\n .replace(/\\.d\\.([mc]?)ts$/, '.$1ts')}`\n const output = `./${path\n .relative(cwd, path.join(chunk.outDir, chunk.fileName))\n .replaceAll('\\\\', '/')}`\n lines.add(`${pkg.name}: ${source} \\u2192 ${output}`)\n }\n }\n\n for (const line of Array.from(lines).toSorted()) {\n logger.log(line)\n }\n}\n\n/**\n * tsdown's exports generation rewrites the top-level `types` field alongside `main`/`module`\n * when the `legacy` fields are maintained, preferring the CJS declarations (`.d.cts`) for\n * dual-format packages. The hand-written value is authoritative here (the Sanity convention\n * points `types` at the ESM `.d.ts`), so it is restored after the canonical build.\n */\nfunction restoreAuthoredTypes(ctx: {cwd: string; pkg: {types?: string | undefined}}): void {\n const authoredTypes = ctx.pkg.types\n if (!authoredTypes) return\n\n const pkgPath = path.resolve(ctx.cwd, 'package.json')\n let text: string\n try {\n text = readFileSync(pkgPath, 'utf8')\n } catch {\n return\n }\n const json: unknown = JSON.parse(text)\n if (!isRecord(json) || json['types'] === authoredTypes) return\n json['types'] = authoredTypes\n\n const indent = /^([ \\t]+)\\S/m.exec(text)?.[1] ?? 2\n let output = JSON.stringify(json, null, indent)\n if (text.endsWith('\\n')) output += '\\n'\n writeFileSync(pkgPath, output, 'utf8')\n}\n\n/**\n * pkg-utils owns its own experience: `tsdown.config.*` files are never loaded in pkg-utils\n * mode (`package.config.ts` is the sole config source), so their presence is worth a warning.\n */\nfunction warnAboutTsdownConfigFiles(cwd: string, logger: Logger): void {\n const candidates = [\n 'tsdown.config.ts',\n 'tsdown.config.mts',\n 'tsdown.config.cts',\n 'tsdown.config.js',\n 'tsdown.config.mjs',\n 'tsdown.config.cjs',\n 'tsdown.config.json',\n ]\n const found = candidates.find((candidate) => existsSync(path.resolve(cwd, candidate)))\n if (found) {\n logger.warn(\n `found \\`${found}\\`, which @sanity/pkg-utils does not load — \\`package.config.ts\\` is the only config source of \\`pkg build\\`. Either migrate the package fully to tsdown (and drop @sanity/pkg-utils), or move the configuration into \\`package.config.ts\\`.`,\n )\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n","import {build} from '../node/build.ts'\nimport {handleError} from './handleError.ts'\n\nexport async function buildAction(options: {\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n try {\n await build({\n cwd: process.cwd(),\n emitDeclarationOnly: options.emitDeclarationOnly,\n strict: options.strict,\n tsconfig: options.tsconfig,\n clean: options.clean,\n quiet: options.quiet,\n })\n } catch (err) {\n handleError(err)\n }\n}\n"],"mappings":";;;;;;;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WAAW,MAAM,6OACnB;AAEJ;AAEA,SAAS,aAAa,OAAuB;CAC3C,OAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AC5PA,eAAsB,YAAY,SAMhB;CAChB,IAAI;EACF,MAAMC,QAAM;GACV,KAAK,QAAQ,IAAI;GACjB,qBAAqB,QAAQ;GAC7B,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,OAAO,QAAQ;GACf,OAAO,QAAQ;EACjB,CAAC;CACH,SAAS,KAAK;EACZ,YAAY,GAAG;CACjB;AACF"}
1
+ {"version":3,"file":"buildAction-HQvn8xA1.js","names":["build","findPkgPath","tsdownBuild","build"],"sources":["../src/node/build.ts","../src/cli/buildAction.ts"],"sourcesContent":["import {existsSync, readFileSync, rmSync, writeFileSync} from 'node:fs'\nimport path from 'node:path'\nimport {up as findPkgPath} from 'empathic/package'\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 {createLogger, type Logger} from './logger.ts'\nimport {resolveBuildContext} from './resolveBuildContext.ts'\nimport {createSpinner} from './spinner.ts'\nimport {\n resolveTsdownBuilds,\n type TsdownBuild as TsdownBuildDef,\n} from './tasks/tsdown/resolveTsdownBuilds.ts'\nimport {resolveTsdownConfig} from './tasks/tsdown/resolveTsdownConfig.ts'\n\nconst RE_TS_SOURCE = /\\.[cm]?tsx?$/\n\n/**\n * Build the distribution files of a npm package.\n *\n * @example\n * ```ts\n * import {build} from '@sanity/pkg-utils'\n *\n * build({\n * cwd: process.cwd(),\n * tsconfig: 'tsconfig.dist.json,\n * }).then(() => {\n * console.log('successfully built')\n * }).catch((err) => {\n * console.log(`build error: ${err.message}`)\n * })\n * ```\n *\n * @public\n */\nexport async function build(options: {\n cwd: string\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n const {\n cwd,\n emitDeclarationOnly,\n strict = false,\n tsconfig: tsconfigOption,\n // `--no-clean` skips cleaning for this run; `true` (the CLI default — `--clean` still\n // parses as a no-op for v11 compatibility) defers to the `clean` config option\n clean = true,\n quiet = false,\n } = options\n const logger = createLogger(quiet)\n\n const pkgPath = findPkgPath({cwd})\n if (!pkgPath) {\n throw new Error('no package.json found', {cause: {cwd}})\n }\n const config = await loadConfig({cwd, pkgPath})\n\n const {parseStrictOptions} = await import('./strict.ts')\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n const pkg = await loadPkgWithReporting({pkgPath, logger, strict, strictOptions})\n\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n const ctx = await resolveBuildContext({\n config,\n cwd,\n emitDeclarationOnly,\n logger,\n pkg,\n strict,\n tsconfig,\n })\n\n warnAboutTsdownConfigFiles(cwd, logger)\n\n const builds = resolveTsdownBuilds(ctx)\n\n let first = true\n for (const buildDef of builds) {\n // A types-only run skips builds without TypeScript sources entirely\n if (\n ctx.emitDeclarationOnly &&\n !buildDef.entries.some((entry) => RE_TS_SOURCE.test(entry.source))\n ) {\n continue\n }\n\n const taskName = buildTaskName(buildDef)\n const spinner = createSpinner(taskName, quiet)\n\n try {\n const inlineConfig = await resolveTsdownConfig(ctx, buildDef, {clean: first && clean})\n first = false\n\n const bundles = await tsdownBuild(inlineConfig)\n\n if (ctx.emitDeclarationOnly) {\n // `dts.emitDtsOnly` suppresses the JS chunks of the ES pass, but the CJS pass emits\n // its JS regardless (only its extra dts pass runs the dts plugin) — a types-only\n // build removes everything that is not a declaration file\n removeNonDeclarationOutputs(bundles)\n }\n\n if (buildDef.canonical) {\n restoreAuthoredTypes(ctx)\n }\n\n spinner.complete()\n ctx.logger.log()\n\n printBuildOutputs(ctx, bundles, buildDef)\n ctx.logger.log()\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(escapeRegExp(cwd), 'g')\n\n ctx.logger.error((err.stack || err.message).replace(RE_CWD, '.'))\n ctx.logger.log()\n }\n\n process.exit(1)\n }\n }\n}\n\nfunction buildTaskName(buildDef: TsdownBuildDef): string {\n const formats = Array.from(new Set(buildDef.entries.flatMap((entry) => entry.formats)))\n return `build ${buildDef.key} (${formats.join(', ') || 'types'})`\n}\n\nconst RE_DTS_OUTPUT = /\\.d\\.[mc]?ts(\\.map)?$/\n\n/** Removes every emitted file that is not a declaration file (or its sourcemap). */\nfunction removeNonDeclarationOutputs(bundles: TsdownBundle[]): void {\n for (const bundle of bundles) {\n for (const chunk of bundle.chunks) {\n if (RE_DTS_OUTPUT.test(chunk.fileName)) continue\n rmSync(path.join(chunk.outDir, chunk.fileName), {force: true})\n rmSync(path.join(chunk.outDir, `${chunk.fileName}.map`), {force: true})\n }\n }\n}\n\n/**\n * Prints `<pkg>: <source> → <output>` for every entry chunk (JS and `.d.ts`) that tsdown\n * emitted, mirroring the per-file output of previous majors.\n */\nfunction printBuildOutputs(\n ctx: {\n cwd: string\n distPath: string\n emitDeclarationOnly: boolean\n logger: Logger\n pkg: {name: string}\n },\n bundles: TsdownBundle[],\n buildDef: TsdownBuildDef,\n): void {\n const {cwd, logger, pkg} = ctx\n const lines = new Set<string>()\n\n // Stylesheets are emitted as assets, which carry no `facadeModuleId` back to their source,\n // so the stylesheet build's lines come from its entry map instead.\n if (buildDef.css) {\n for (const entry of buildDef.entries) {\n const output = `./${path\n .relative(cwd, path.join(ctx.distPath, `${entry.alias}.css`))\n .replaceAll('\\\\', '/')}`\n lines.add(\n `${pkg.name}: ./${path.relative(cwd, path.resolve(cwd, entry.source)).replaceAll('\\\\', '/')} \\u2192 ${output}`,\n )\n }\n }\n\n for (const bundle of bundles) {\n for (const chunk of bundle.chunks) {\n if (chunk.type !== 'chunk' || !chunk.isEntry || !chunk.facadeModuleId) continue\n if (ctx.emitDeclarationOnly && !RE_DTS_OUTPUT.test(chunk.fileName)) continue\n const source = `./${path\n .relative(cwd, chunk.facadeModuleId)\n .replaceAll('\\\\', '/')\n // the dts chunks facade the fake `.d.ts` module ids of rolldown-plugin-dts; print the\n // actual `.ts` source instead\n .replace(/\\.d\\.([mc]?)ts$/, '.$1ts')}`\n const output = `./${path\n .relative(cwd, path.join(chunk.outDir, chunk.fileName))\n .replaceAll('\\\\', '/')}`\n lines.add(`${pkg.name}: ${source} \\u2192 ${output}`)\n }\n }\n\n for (const line of Array.from(lines).toSorted()) {\n logger.log(line)\n }\n}\n\n/**\n * tsdown's exports generation rewrites the top-level `types` field alongside `main`/`module`\n * when the `legacy` fields are maintained, preferring the CJS declarations (`.d.cts`) for\n * dual-format packages. The hand-written value is authoritative here (the Sanity convention\n * points `types` at the ESM `.d.ts`), so it is restored after the canonical build.\n */\nfunction restoreAuthoredTypes(ctx: {cwd: string; pkg: {types?: string | undefined}}): void {\n const authoredTypes = ctx.pkg.types\n if (!authoredTypes) return\n\n const pkgPath = path.resolve(ctx.cwd, 'package.json')\n let text: string\n try {\n text = readFileSync(pkgPath, 'utf8')\n } catch {\n return\n }\n const json: unknown = JSON.parse(text)\n if (!isRecord(json) || json['types'] === authoredTypes) return\n json['types'] = authoredTypes\n\n const indent = /^([ \\t]+)\\S/m.exec(text)?.[1] ?? 2\n let output = JSON.stringify(json, null, indent)\n if (text.endsWith('\\n')) output += '\\n'\n writeFileSync(pkgPath, output, 'utf8')\n}\n\n/**\n * pkg-utils owns its own experience: `tsdown.config.*` files are never loaded in pkg-utils\n * mode (`package.config.ts` is the sole config source), so their presence is worth a warning.\n */\nfunction warnAboutTsdownConfigFiles(cwd: string, logger: Logger): void {\n const candidates = [\n 'tsdown.config.ts',\n 'tsdown.config.mts',\n 'tsdown.config.cts',\n 'tsdown.config.js',\n 'tsdown.config.mjs',\n 'tsdown.config.cjs',\n 'tsdown.config.json',\n ]\n const found = candidates.find((candidate) => existsSync(path.resolve(cwd, candidate)))\n if (found) {\n logger.warn(\n `found \\`${found}\\`, which @sanity/pkg-utils does not load — \\`package.config.ts\\` is the only config source of \\`pkg build\\`. Either migrate the package fully to tsdown (and drop @sanity/pkg-utils), or move the configuration into \\`package.config.ts\\`.`,\n )\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n","import {build} from '../node/build.ts'\nimport {handleError} from './handleError.ts'\n\nexport async function buildAction(options: {\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n try {\n await build({\n cwd: process.cwd(),\n emitDeclarationOnly: options.emitDeclarationOnly,\n strict: options.strict,\n tsconfig: options.tsconfig,\n clean: options.clean,\n quiet: options.quiet,\n })\n } catch (err) {\n handleError(err)\n }\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;AAqBrB,eAAsBA,QAAM,SAOV;CAChB,IAAM,EACJ,KACA,qBACA,SAAS,IACT,UAAU,gBAGV,QAAQ,IACR,QAAQ,OACN,SACE,SAAS,aAAa,KAAK,GAE3B,UAAUC,GAAY,EAAC,IAAG,CAAC;CACjC,IAAI,CAAC,SACH,MAAU,MAAM,yBAAyB,EAAC,OAAO,EAAC,IAAG,EAAC,CAAC;CAEzD,IAAM,SAAS,MAAM,WAAW;EAAC;EAAK;CAAO,CAAC,GAExC,EAAC,uBAAsB,MAAM,OAAO,oCAAc,CAAA,MAAA,MAAA,EAAA,CAAA,GAClD,gBAAgB,mBAAmB,QAAQ,iBAAiB,CAAC,CAAC,GAC9D,MAAM,MAAM,qBAAqB;EAAC;EAAS;EAAQ;EAAQ;CAAa,CAAC,GAEzE,WAAW,kBAAkB,QAAQ,YAAY,iBAEjD,MAAM,MAAM,oBAAoB;EACpC;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CAED,2BAA2B,KAAK,MAAM;CAEtC,IAAM,SAAS,oBAAoB,GAAG,GAElC,QAAQ;CACZ,KAAK,IAAM,YAAY,QAAQ;EAE7B,IACE,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AM,OAAgB,KAAK,MAAM,IAAI;CACrC,IAAI,CAAC,SAAS,IAAI,KAAK,KAAK,UAAa,eAAe;CACxD,KAAK,QAAW;CAEhB,IAAM,SAAS,eAAe,KAAK,IAAI,CAAC,GAAG,MAAM,GAC7C,SAAS,KAAK,UAAU,MAAM,MAAM,MAAM;CAE9C,AADI,KAAK,SAAS,IAAI,MAAG,UAAU,OACnC,cAAc,SAAS,QAAQ,MAAM;AACvC;;;;;AAMA,SAAS,2BAA2B,KAAa,QAAsB;CAUrE,IAAM,QAAQ;EARZ;EACA;EACA;EACA;EACA;EACA;EACA;CAEqB,CAAC,CAAC,MAAM,cAAc,WAAW,KAAK,QAAQ,KAAK,SAAS,CAAC,CAAC;CACrF,AAAI,SACF,OAAO,KACL,WAAW,MAAM,6OACnB;AAEJ;AAEA,SAAS,aAAa,OAAuB;CAC3C,OAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AC5PA,eAAsB,YAAY,SAMhB;CAChB,IAAI;EACF,MAAMC,QAAM;GACV,KAAK,QAAQ,IAAI;GACjB,qBAAqB,QAAQ;GAC7B,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,OAAO,QAAQ;GACf,OAAO,QAAQ;EACjB,CAAC;CACH,SAAS,KAAK;EACZ,YAAY,GAAG;CACjB;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { i as fileExists, n as createLogger, t as handleError } from "./handleError-83GwKIFM.js";
2
- import { a as loadPkgWithReporting, o as loadConfig, t as resolveBuildContext } from "./resolveBuildContext-DYZxWVVc.js";
2
+ import { a as loadPkgWithReporting, o as loadConfig, t as resolveBuildContext } from "./resolveBuildContext-vVTRkIDl.js";
3
3
  import { t as createSpinner } from "./spinner-DAHe7SuT.js";
4
4
  import { statSync } from "node:fs";
5
5
  import path from "node:path";
@@ -38,7 +38,7 @@ function printPackageTree(ctx) {
38
38
  import: void 0,
39
39
  default: fileInfo(entry.default)
40
40
  };
41
- return entry.browser ? (exp.browser = { source: fileInfo(entry.browser.source) }, entry.browser.import && (exp.browser.import = fileInfo(entry.browser.import)), entry.browser.require && (exp.browser.require = fileInfo(entry.browser.require))) : delete exp.browser, entry.require ? exp.require = fileInfo(entry.require) : delete exp.require, entry.node ? (exp.node = {}, entry.node.source && (exp.node.source = fileInfo(entry.node.source)), entry.node.import && (exp.node.import = fileInfo(entry.node.import)), entry.node.require && (exp.node.require = fileInfo(entry.node.require))) : delete exp.node, entry.import ? exp.import = fileInfo(entry.import) : delete exp.import, [chalk.cyan(path.join(pkg.name, exportPath)), exp];
41
+ return entry.browser ? (exp.browser = { source: fileInfo(entry.browser.source) }, entry.browser.import && (exp.browser.import = fileInfo(entry.browser.import)), entry.browser.require && (exp.browser.require = fileInfo(entry.browser.require)), entry.browser.default && (exp.browser.default = fileInfo(entry.browser.default))) : delete exp.browser, entry.require ? exp.require = fileInfo(entry.require) : delete exp.require, entry.node ? (exp.node = {}, entry.node.source && (exp.node.source = fileInfo(entry.node.source)), entry.node.import && (exp.node.import = fileInfo(entry.node.import)), entry.node.require && (exp.node.require = fileInfo(entry.node.require)), entry.node.default && (exp.node.default = fileInfo(entry.node.default))) : delete exp.node, entry.import ? exp.import = fileInfo(entry.import) : delete exp.import, [chalk.cyan(path.join(pkg.name, exportPath)), exp];
42
42
  })), logger.log(treeify.asTree(tree, !0, !0));
43
43
  }
44
44
  /** @public */
@@ -50,7 +50,7 @@ async function check(options) {
50
50
  let config = await loadConfig({
51
51
  cwd,
52
52
  pkgPath
53
- }), { parseStrictOptions } = await import("./resolveBuildContext-DYZxWVVc.js").then((n) => n.n), strictOptions = parseStrictOptions(config?.strictOptions ?? {}), pkg = await loadPkgWithReporting({
53
+ }), { parseStrictOptions } = await import("./resolveBuildContext-vVTRkIDl.js").then((n) => n.n), strictOptions = parseStrictOptions(config?.strictOptions ?? {}), pkg = await loadPkgWithReporting({
54
54
  pkgPath,
55
55
  logger,
56
56
  strict,
@@ -143,4 +143,4 @@ async function checkAction(options) {
143
143
  }
144
144
  export { checkAction };
145
145
 
146
- //# sourceMappingURL=checkAction-0QxzAxUd.js.map
146
+ //# sourceMappingURL=checkAction-DWSqzrZd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkAction-DWSqzrZd.js","names":["findPkgPath"],"sources":["../src/node/getFilesize.ts","../src/node/printPackageTree.ts","../src/node/check.ts","../src/cli/checkAction.ts"],"sourcesContent":["import {statSync} from 'node:fs'\nimport prettyBytes from 'pretty-bytes'\n\nexport function getFilesize(file: string): string {\n const stats = statSync(file)\n\n return prettyBytes(stats.size)\n}\n","import path from 'node:path'\nimport chalk from 'chalk'\nimport treeify from 'treeify'\nimport type {PkgExport} from './core/config/types.ts'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\nimport {fileExists} from './fileExists.ts'\nimport {getFilesize} from './getFilesize.ts'\n\nfunction getFileInfo(cwd: string, filePath: string) {\n const p = path.resolve(cwd, filePath)\n const exists = fileExists(p)\n const size = exists ? getFilesize(p) : undefined\n\n return {exists, size}\n}\n\nexport function printPackageTree(ctx: BuildContext): void {\n const {cwd, exports, logger, pkg} = ctx\n\n if (!exports) return\n\n logger.log(`${chalk.blue(pkg.name)}@${chalk.green(pkg.version)}`)\n\n const tree: Record<string, unknown> = {}\n\n if (pkg.type) {\n tree['type'] = chalk.yellow(pkg.type)\n }\n\n if (pkg.bin) {\n tree['bin'] = Object.fromEntries(\n Object.entries(pkg.bin).map(([name, file]) => [chalk.cyan(name), fileInfo(file)]),\n )\n }\n\n function fileInfo(file: string) {\n const info = getFileInfo(cwd, file)\n\n if (!info.size) {\n return `${chalk.gray(file)} ${chalk.red('does not exist')}`\n }\n\n return `${chalk.yellow(file)} ${chalk.gray(info.size)}`\n }\n\n tree['exports'] = Object.fromEntries(\n Object.entries(exports)\n .filter(([, entry]) => entry._exported)\n .map(([exportPath, entry]) => {\n const exp: Omit<PkgExport, '_exported'> = {\n source: fileInfo(entry.source),\n browser: undefined,\n require: undefined,\n node: undefined,\n import: undefined,\n default: fileInfo(entry.default),\n }\n\n if (entry.browser) {\n exp.browser = {source: fileInfo(entry.browser.source)}\n\n if (entry.browser.import) exp.browser.import = fileInfo(entry.browser.import)\n if (entry.browser.require) exp.browser.require = fileInfo(entry.browser.require)\n if (entry.browser.default) exp.browser.default = fileInfo(entry.browser.default)\n } else {\n delete exp.browser\n }\n\n if (entry.require) {\n exp.require = fileInfo(entry.require)\n } else {\n delete exp.require\n }\n\n if (entry.node) {\n exp.node = {}\n\n if (entry.node.source) exp.node.source = fileInfo(entry.node.source)\n if (entry.node.import) exp.node.import = fileInfo(entry.node.import)\n if (entry.node.require) exp.node.require = fileInfo(entry.node.require)\n if (entry.node.default) exp.node.default = fileInfo(entry.node.default)\n } else {\n delete exp.node\n }\n\n if (entry.import) {\n exp.import = fileInfo(entry.import)\n } else {\n delete exp.import\n }\n\n return [chalk.cyan(path.join(pkg.name, exportPath)), exp]\n }),\n )\n\n logger.log(treeify.asTree(tree as Record<string, any>, true, true))\n}\n","import path from 'node:path'\nimport {checkTsdoc} from '@sanity/tsdown-config/tsdoc'\nimport {up as findPkgPath} from 'empathic/package'\nimport {loadConfig} from './core/config/loadConfig.ts'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\nimport {loadPkgWithReporting} from './core/pkg/loadPkgWithReporting.ts'\nimport {fileExists} from './fileExists.ts'\nimport {createLogger} from './logger.ts'\nimport {printPackageTree} from './printPackageTree.ts'\nimport {resolveBuildContext} from './resolveBuildContext.ts'\nimport {createSpinner} from './spinner.ts'\n\n/** @public */\nexport async function check(options: {\n cwd: string\n strict?: boolean\n tsconfig?: string\n}): Promise<void> {\n const {cwd, strict = false, tsconfig: tsconfigOption} = options\n const logger = createLogger()\n const spinner = createSpinner('')\n try {\n const pkgPath = findPkgPath({cwd})\n if (!pkgPath) {\n throw new Error('no package.json found', {cause: {cwd}})\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 const ctx = await resolveBuildContext({config, cwd, logger, pkg, strict, tsconfig})\n\n printPackageTree(ctx)\n\n if (strict) {\n const missingFiles: string[] = []\n\n // Check if there are missing files\n for (const [, exp] of Object.entries(ctx.exports || {})) {\n if (exp.source && !fileExists(path.resolve(cwd, exp.source))) {\n missingFiles.push(exp.source)\n }\n\n if (exp.require && !fileExists(path.resolve(cwd, exp.require))) {\n missingFiles.push(exp.require)\n }\n\n if (exp.import && !fileExists(path.resolve(cwd, exp.import))) {\n missingFiles.push(exp.import)\n }\n }\n\n if (ctx.pkg.types && !fileExists(path.resolve(cwd, ctx.pkg.types))) {\n missingFiles.push(ctx.pkg.types)\n }\n\n if (missingFiles.length) {\n logger.error(`missing files: ${missingFiles.join(', ')}`)\n process.exit(1)\n }\n }\n\n // publint validates that the built package resolves in every runtime/bundler — it packs\n // the package (which applies `publishConfig`, so the source-condition convention checks\n // out the way consumers see it) and lints the result. This replaced the bespoke\n // esbuild-based resolution checks of previous majors.\n await runPublint(ctx)\n\n if (ctx.config?.tsdoc !== false) {\n await checkApiExtractorReleaseTags(ctx)\n }\n\n spinner.complete()\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(cwd.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g')\n\n logger.error((err.stack || err.message).replace(RE_CWD, '.'))\n logger.log()\n }\n\n process.exit(1)\n }\n}\n\nasync function runPublint(ctx: BuildContext): Promise<void> {\n const {cwd, logger, strict} = ctx\n const [{publint}, {formatMessage}] = await Promise.all([\n import('publint'),\n import('publint/utils'),\n ])\n\n const {messages, pkg} = await publint({pkgDir: cwd, strict})\n\n let hasErrors = false\n\n for (const message of messages) {\n const formatted = formatMessage(message, pkg)\n if (message.type === 'error') {\n hasErrors = true\n logger.error(`publint: ${formatted}`)\n } else if (message.type === 'warning') {\n logger.warn(`publint: ${formatted}`)\n } else {\n logger.log(`publint: ${formatted}`)\n }\n }\n\n if (hasErrors) {\n process.exit(1)\n }\n}\n\nasync function checkApiExtractorReleaseTags(ctx: BuildContext) {\n const tsdoc =\n ctx.config?.tsdoc === false || ctx.config?.tsdoc === true ? undefined : ctx.config?.tsdoc\n const entryDtsFiles: string[] = []\n const seen = new Set<string>()\n\n for (const exp of Object.values(ctx.exports || {})) {\n if (!exp._exported) continue\n // Prefer an explicit `types` condition; otherwise derive declarations from every runtime\n // file (`.js` → `.d.ts`, `.mjs` → `.d.mts`, `.cjs` → `.d.cts`) so dual-format / fixed-\n // extension packages are checked the same way as the build-time `tsdoc` hook.\n const candidates = new Set<string>()\n if (exp.types) candidates.add(exp.types)\n for (const js of [exp.default, exp.import, exp.require]) {\n if (!js) continue\n const dts = jsFileToDts(js)\n if (dts) candidates.add(dts)\n }\n for (const dtsPath of candidates) {\n const exportPath = path.resolve(ctx.cwd, dtsPath)\n // JS-only entries emit no declarations; there is nothing to check\n if (!fileExists(exportPath) || seen.has(exportPath)) continue\n seen.add(exportPath)\n entryDtsFiles.push(exportPath)\n }\n }\n\n if (entryDtsFiles.length === 0) return\n\n await checkTsdoc({\n cwd: ctx.cwd,\n entryDtsFiles,\n tsconfig: ctx.ts.configPath || 'tsconfig.json',\n outDir: ctx.ts.config?.options.outDir ?? ctx.distPath,\n bundledPackages: ctx.bundledPackages,\n customTags: tsdoc?.customTags,\n rules: tsdoc?.rules,\n logger: {\n log: (...args) => ctx.logger.log(...args),\n warn: (...args) => ctx.logger.warn(...args),\n error: (...args) => ctx.logger.error(...args),\n },\n })\n}\n\n/** `./dist/index.js` → `./dist/index.d.ts` (`.mjs` → `.d.mts`, `.cjs` → `.d.cts`). */\nfunction jsFileToDts(file: string): string | undefined {\n if (/\\.d\\.[mc]?ts$/.test(file)) return file\n if (file.endsWith('.mjs')) return file.replace(/\\.mjs$/, '.d.mts')\n if (file.endsWith('.cjs')) return file.replace(/\\.cjs$/, '.d.cts')\n if (file.endsWith('.js')) return file.replace(/\\.js$/, '.d.ts')\n return undefined\n}\n","import {check} from '../node/check.ts'\nimport {handleError} from './handleError.ts'\n\nexport async function checkAction(options: {strict?: boolean; tsconfig?: string}): Promise<void> {\n try {\n await check({\n cwd: process.cwd(),\n strict: options.strict,\n tsconfig: options.tsconfig,\n })\n } catch (err) {\n handleError(err)\n }\n}\n"],"mappings":";;;;;;;;;;AAGA,SAAgB,YAAY,MAAsB;CAChD,IAAM,QAAQ,SAAS,IAAI;CAE3B,OAAO,YAAY,MAAM,IAAI;AAC/B;ACCA,SAAS,YAAY,KAAa,UAAkB;CAClD,IAAM,IAAI,KAAK,QAAQ,KAAK,QAAQ,GAC9B,SAAS,WAAW,CAAC;CAG3B,OAAO;EAAC;EAAQ,MAFH,SAAS,YAAY,CAAC,IAAI,KAAA;CAEnB;AACtB;AAEA,SAAgB,iBAAiB,KAAyB;CACxD,IAAM,EAAC,KAAK,SAAS,QAAQ,QAAO;CAEpC,IAAI,CAAC,SAAS;CAEd,OAAO,IAAI,GAAG,MAAM,KAAK,IAAI,IAAI,EAAE,GAAG,MAAM,MAAM,IAAI,OAAO,GAAG;CAEhE,IAAM,OAAgC,CAAC;CAMvC,AAJI,IAAI,SACN,KAAK,OAAU,MAAM,OAAO,IAAI,IAAI,IAGlC,IAAI,QACN,KAAK,MAAS,OAAO,YACnB,OAAO,QAAQ,IAAI,GAAG,CAAC,CAAC,KAAK,CAAC,MAAM,UAAU,CAAC,MAAM,KAAK,IAAI,GAAG,SAAS,IAAI,CAAC,CAAC,CAClF;CAGF,SAAS,SAAS,MAAc;EAC9B,IAAM,OAAO,YAAY,KAAK,IAAI;EAMlC,OAJK,KAAK,OAIH,GAAG,MAAM,OAAO,IAAI,EAAE,GAAG,MAAM,KAAK,KAAK,IAAI,MAH3C,GAAG,MAAM,KAAK,IAAI,EAAE,GAAG,MAAM,IAAI,gBAAgB;CAI5D;CAoDA,AAlDA,KAAK,UAAa,OAAO,YACvB,OA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
1
  import { cac } from "cac";
2
- var version = "12.1.1";
2
+ var version = "12.1.3";
3
3
  const cli = cac();
4
4
  cli.command("", "Check").alias("check").option("--strict", "Strict mode").option("--tsconfig [tsconfig]", "[string] tsconfig.json").action(async (options) => {
5
- let { checkAction } = await import("./checkAction-0QxzAxUd.js");
5
+ let { checkAction } = await import("./checkAction-DWSqzrZd.js");
6
6
  return checkAction(options);
7
7
  }), cli.command("build", "Build package").option("--emitDeclarationOnly", "Emit d.ts only").option("--strict", "Strict mode").option("--tsconfig [tsconfig]", "[string] tsconfig.json").option("--check", "Run the check command after build (same as running `pkg build && pkg check`)").option("--no-clean", "Skip cleaning the `dist` folder before the build").option("--quiet", "Suppress all output except errors, warnings, and checks").action(async (options) => {
8
- let { check = !1, ...buildOptions } = options, { buildAction } = await import("./buildAction-C8MCKsDz.js");
8
+ let { check = !1, ...buildOptions } = options, { buildAction } = await import("./buildAction-HQvn8xA1.js");
9
9
  if (await buildAction(buildOptions), check) {
10
- let { checkAction } = await import("./checkAction-0QxzAxUd.js");
10
+ let { checkAction } = await import("./checkAction-DWSqzrZd.js");
11
11
  await checkAction({
12
12
  strict: options.strict,
13
13
  tsconfig: options.tsconfig
@@ -17,7 +17,7 @@ cli.command("", "Check").alias("check").option("--strict", "Strict mode").option
17
17
  let { initAction } = await import("./initAction-CmOO8eod.js");
18
18
  return initAction({ path: p });
19
19
  }), cli.command("watch", "Watch package").option("--strict", "Strict mode").option("--tsconfig [tsconfig]", "[string] tsconfig.json").action(async (options) => {
20
- let { watchAction } = await import("./watchAction-PjRXiQRe.js");
20
+ let { watchAction } = await import("./watchAction-BiD7pJr4.js");
21
21
  return watchAction(options);
22
22
  }), cli.help(), cli.version(version), cli.parse();
23
23
  export {};
@@ -330,14 +330,32 @@ async function loadPkg(options) {
330
330
  let { pkgPath } = options, raw = JSON.parse(await fs.readFile(pkgPath, "utf-8"));
331
331
  return validatePkg(raw), raw;
332
332
  }
333
+ /** The conditions that only resolve before publishing, and are stripped from the publish map. */
334
+ const devConditions = /* @__PURE__ */ new Set([
335
+ "source",
336
+ "development",
337
+ "monorepo"
338
+ ]);
339
+ /**
340
+ * A nested runtime condition (`node`, `browser`) may be condensed to a plain string when `default`
341
+ * is the only condition left once the dev-only ones are stripped: the resolver treats
342
+ * `"node": "./dist/index.node.js"` and `"node": {"default": "./dist/index.node.js"}` identically.
343
+ * This is the same condensation `publishConfig.exports["<subpath>"]` itself allows at entry level.
344
+ */
345
+ function condenseExportValue(value) {
346
+ if (typeof value != "object" || !value || Array.isArray(value)) return value;
347
+ let conditions = Object.entries(value).filter(([condition]) => !devConditions.has(condition)), [first] = conditions;
348
+ return conditions.length === 1 && first?.[0] === "default" && typeof first[1] == "string" ? first[1] : value;
349
+ }
333
350
  /**
334
351
  * Helper function to recursively compare export values, excluding source, development, and monorepo conditions
335
352
  */
336
- function areExportValuesEqual(value1, value2) {
353
+ function areExportValuesEqual(input1, input2) {
354
+ let value1 = condenseExportValue(input1), value2 = condenseExportValue(input2);
337
355
  if (typeof value1 == "string" && typeof value2 == "string") return value1 === value2;
338
356
  if (typeof value1 != typeof value2) return !1;
339
357
  if (typeof value1 == "object" && value1 && typeof value2 == "object" && value2 && !Array.isArray(value1) && !Array.isArray(value2)) {
340
- let obj1 = value1, obj2 = value2, keys1 = Object.keys(obj1).filter((k) => k !== "source" && k !== "development" && k !== "monorepo"), keys2 = Object.keys(obj2).filter((k) => k !== "source" && k !== "development" && k !== "monorepo");
358
+ let obj1 = value1, obj2 = value2, keys1 = Object.keys(obj1).filter((k) => !devConditions.has(k)), keys2 = Object.keys(obj2).filter((k) => !devConditions.has(k));
341
359
  if (keys1.length !== keys2.length) return !1;
342
360
  for (let key of keys1) {
343
361
  if (!keys2.includes(key)) return !1;
@@ -441,7 +459,7 @@ async function loadPkgWithReporting(options) {
441
459
  ].join(""));
442
460
  continue;
443
461
  }
444
- logger.error(issue);
462
+ logger.error(issue.path.length ? `\`${formatPath(issue.path)}\` in \`./package.json\` is invalid: ${issue.message}` : `\`./package.json\` is invalid: ${issue.message}`);
445
463
  }
446
464
  else logger.error(err);
447
465
  return process.exit(1);
@@ -672,8 +690,10 @@ async function resolveBuildContext(options) {
672
690
  exportEntry.require,
673
691
  exportEntry.browser?.import,
674
692
  exportEntry.browser?.require,
693
+ exportEntry.browser?.default,
675
694
  exportEntry.node?.source && exportEntry.node.import,
676
- exportEntry.node?.source && exportEntry.node.require
695
+ exportEntry.node?.source && exportEntry.node.require,
696
+ exportEntry.node?.default
677
697
  ].filter(isTruthy)).map((p) => path.resolve(cwd, p)));
678
698
  if (commonDistPath === cwd) throw Error("all output files must share a common parent directory which is not the root package directory");
679
699
  if (commonDistPath && !pathContains(cwd, commonDistPath)) throw Error("all output files must be located within the package");
@@ -739,4 +759,4 @@ function transformPackageName(packageName) {
739
759
  }
740
760
  export { loadPkgWithReporting as a, pkgExtMap as i, strict_exports as n, loadConfig as o, fileEnding as r, resolveBuildContext as t };
741
761
 
742
- //# sourceMappingURL=resolveBuildContext-DYZxWVVc.js.map
762
+ //# sourceMappingURL=resolveBuildContext-vVTRkIDl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveBuildContext-vVTRkIDl.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/** The conditions that only resolve before publishing, and are stripped from the publish map. */\nconst devConditions = new Set(['source', 'development', 'monorepo'])\n\n/**\n * A nested runtime condition (`node`, `browser`) may be condensed to a plain string when `default`\n * is the only condition left once the dev-only ones are stripped: the resolver treats\n * `\"node\": \"./dist/index.node.js\"` and `\"node\": {\"default\": \"./dist/index.node.js\"}` identically.\n * This is the same condensation `publishConfig.exports[\"<subpath>\"]` itself allows at entry level.\n */\nfunction condenseExportValue(value: unknown): unknown {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return value\n\n const conditions = Object.entries(value).filter(([condition]) => !devConditions.has(condition))\n const [first] = conditions\n\n if (conditions.length === 1 && first?.[0] === 'default' && typeof first[1] === 'string') {\n return first[1]\n }\n\n return value\n}\n\n/**\n * Helper function to recursively compare export values, excluding source, development, and monorepo conditions\n */\nfunction areExportValuesEqual(input1: unknown, input2: unknown): boolean {\n const value1 = condenseExportValue(input1)\n const value2 = condenseExportValue(input2)\n\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((k) => !devConditions.has(k))\n const keys2 = Object.keys(obj2).filter((k) => !devConditions.has(k))\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 // Every other issue carries its own message: report it against the path it was found at,\n // rather than dumping the raw issue object.\n logger.error(\n issue.path.length\n ? `\\`${formatPath(issue.path)}\\` in \\`./package.json\\` is invalid: ${issue.message}`\n : `\\`./package.json\\` is invalid: ${issue.message}`,\n )\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.browser?.default,\n exportEntry.node?.source && exportEntry.node.import,\n exportEntry.node?.source && exportEntry.node.require,\n exportEntry.node?.default,\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;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BACN,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-DYZxWVVc.js";
2
+ import { i as pkgExtMap, r as fileEnding } from "./resolveBuildContext-vVTRkIDl.js";
3
3
  import path from "node:path";
4
4
  import { mergeConfig } from "tsdown";
5
5
  import { defineConfig } from "@sanity/tsdown-config";
@@ -34,23 +34,30 @@ function resolveTsdownBuilds(ctx) {
34
34
  exportPath,
35
35
  formats
36
36
  });
37
- }, exports = Object.entries(ctx.exports || {}), hasRuntimeConditions = !1;
38
- for (let [exportPath, exp] of exports) addEntry("canonical", ctx.runtime, {
39
- source: exp.source,
40
- exportPath,
41
- import: exp.import,
42
- require: exp.require
43
- }), (exp.browser?.import || exp.browser?.require) && (hasRuntimeConditions = !0, addEntry("browser", "browser", {
44
- source: exp.browser.source || exp.source,
45
- exportPath,
46
- import: exp.browser.import,
47
- require: exp.browser.require
48
- })), (exp.node?.import || exp.node?.require) && (hasRuntimeConditions = !0, addEntry("node", "node", {
49
- source: exp.node.source || exp.source,
50
- exportPath,
51
- import: exp.node.import,
52
- require: exp.node.require
53
- }));
37
+ }, exports = Object.entries(ctx.exports || {}), packageType = ctx.pkg.type === "module" ? "module" : "commonjs", resolveRuntimeTargets = (condition) => ({
38
+ import: condition.import ?? (packageType === "module" ? condition.default : void 0),
39
+ require: condition.require ?? (packageType === "commonjs" ? condition.default : void 0)
40
+ }), hasRuntimeConditions = !1;
41
+ for (let [exportPath, exp] of exports) {
42
+ addEntry("canonical", ctx.runtime, {
43
+ source: exp.source,
44
+ exportPath,
45
+ import: exp.import,
46
+ require: exp.require
47
+ });
48
+ let browserTargets = exp.browser && resolveRuntimeTargets(exp.browser);
49
+ exp.browser && browserTargets && (browserTargets.import || browserTargets.require) && (hasRuntimeConditions = !0, addEntry("browser", "browser", {
50
+ source: exp.browser.source || exp.source,
51
+ exportPath,
52
+ ...browserTargets
53
+ }));
54
+ let nodeTargets = exp.node && resolveRuntimeTargets(exp.node);
55
+ exp.node && nodeTargets && (nodeTargets.import || nodeTargets.require) && (hasRuntimeConditions = !0, addEntry("node", "node", {
56
+ source: exp.node.source || exp.source,
57
+ exportPath,
58
+ ...nodeTargets
59
+ }));
60
+ }
54
61
  for (let bundle of config?.bundles || []) {
55
62
  let runtime = bundle.runtime || ctx.runtime;
56
63
  addEntry(runtime === ctx.runtime ? "bundles" : `bundles:${runtime}`, runtime, {
@@ -188,8 +195,9 @@ function createConditionalCssExport(cssName, distRel) {
188
195
  * - generated conditions for conditional entries are materialized in both `exports` and
189
196
  * `publishConfig.exports`, so they can be reordered directly in `package.json` and keep that
190
197
  * position on later builds (plain-string entries stay compact),
191
- * - a trailing `default` condition is kept on dual-format entries (tsdown emits bare
192
- * `import`/`require` pairs; the Sanity convention always ends with `default`),
198
+ * - a trailing `default` condition is kept on dual-format entries and nested runtime variants
199
+ * (tsdown emits bare `import`/`require` pairs; the Sanity convention always ends with
200
+ * `default`),
193
201
  * - hand-written subpaths that aren't build entries (`.css`/`.json` exports, `svelte`
194
202
  * entries) are carried over untouched, and
195
203
  * - the hand-written subpath and condition key order of each map is preserved.
@@ -245,7 +253,15 @@ function reconcileCssEntry(exportPath, options) {
245
253
  function reconcileEntry(exp, generated, options) {
246
254
  let { authored, isPublish, type } = options, authoredRecord = isRecord(authored) ? authored : {}, gen = typeof generated == "string" ? { default: generated } : isRecord(generated) ? generated : void 0;
247
255
  if (!gen) return generated;
248
- let browserOrder = isRecord(authoredRecord.browser) ? authoredRecord.browser : exp.browser, browser = exp.browser && (exp.browser.import || exp.browser.require) ? pickConditions(exp.browser, isPublish, browserOrder ?? exp.browser) : void 0, nodeOrder = isRecord(authoredRecord.node) ? authoredRecord.node : exp.node, node = exp.node && (exp.node.import || exp.node.require) ? pickConditions(exp.node, isPublish, nodeOrder ?? exp.node) : void 0, custom = pickCustomConditions(exp);
256
+ let browserOrder = isRecord(authoredRecord.browser) ? authoredRecord.browser : exp.browser, browser = exp.browser && (exp.browser.import || exp.browser.require || exp.browser.default) ? pickConditions(exp.browser, {
257
+ authored: browserOrder ?? exp.browser,
258
+ isPublish,
259
+ type
260
+ }) : void 0, nodeOrder = isRecord(authoredRecord.node) ? authoredRecord.node : exp.node, node = exp.node && (exp.node.import || exp.node.require || exp.node.default) ? pickConditions(exp.node, {
261
+ authored: nodeOrder ?? exp.node,
262
+ isPublish,
263
+ type
264
+ }) : void 0, custom = pickCustomConditions(exp);
249
265
  if (typeof generated == "string" && !exp.types && !browser && !node && custom.length === 0) return generated;
250
266
  let next = {};
251
267
  isPublish || (typeof gen.source == "string" ? next.source = gen.source : exp.source && (next.source = exp.source), exp.development && (next.development = exp.development), exp.monorepo && (next.monorepo = exp.monorepo)), exp.types && (next.types = exp.types), browser && (next.browser = browser), node && (next.node = node);
@@ -257,10 +273,16 @@ function reconcileEntry(exp, generated, options) {
257
273
  else for (let [condition, target] of Object.entries(gen)) condition in next || condition === "source" || (next[condition] = target);
258
274
  return preserveConditionOrder(next, authored);
259
275
  }
260
- /** The hand-written `browser`/`node` condition object, minus `source` for the publish map. */
261
- function pickConditions(conditions, isPublish, authored = conditions) {
262
- let next = {};
263
- return !isPublish && conditions.source && (next.source = conditions.source), conditions.import && (next.import = conditions.import), conditions.require && (next.require = conditions.require), preserveConditionOrder(next, authored);
276
+ /**
277
+ * The hand-written `browser`/`node` condition object, minus `source` for the publish map.
278
+ * A nested runtime condition must have its own fallback: once a resolver matches `node` or
279
+ * `browser`, an unmatched module-format condition otherwise backtracks to the outer entry.
280
+ */
281
+ function pickConditions(conditions, options) {
282
+ let { authored = conditions, isPublish, type } = options, next = {};
283
+ !isPublish && conditions.source && (next.source = conditions.source), conditions.import && (next.import = conditions.import), conditions.require && (next.require = conditions.require);
284
+ let fallback = conditions.default ?? (type === "module" ? conditions.import : conditions.require);
285
+ return fallback && (next.default = fallback), preserveConditionOrder(next, authored);
264
286
  }
265
287
  /**
266
288
  * Reorders reconciled conditions to match their hand-written order. Conditions generated by
@@ -399,7 +421,7 @@ function createWatchCssExportsHook(ctx, css) {
399
421
  return (hooks) => {
400
422
  hooks.hook("build:done", async ({ chunks }) => {
401
423
  if (mergedCssName === void 0 || !chunks.some((chunk) => chunk.type === "asset" && chunk.fileName === mergedCssName)) return;
402
- let { writeBundleCssExports } = await import("./writeBundleCssExports-DGTofClh.js").then((n) => n.n);
424
+ let { writeBundleCssExports } = await import("./writeBundleCssExports-BK5XC19e.js").then((n) => n.n);
403
425
  await writeBundleCssExports({
404
426
  cwd: ctx.cwd,
405
427
  distPath: ctx.distPath,
@@ -411,4 +433,4 @@ function createWatchCssExportsHook(ctx, css) {
411
433
  }
412
434
  export { createConditionalCssExport as n, resolveTsdownBuilds as r, resolveTsdownConfig as t };
413
435
 
414
- //# sourceMappingURL=resolveTsdownConfig-D4boYIwx.js.map
436
+ //# sourceMappingURL=resolveTsdownConfig-I9zyPE-E.js.map