@sanity/pkg-utils
Version:
Simple utilities for modern npm packages.
1 lines • 204 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","sources":["../../src/node/fileExists.ts","../../src/node/core/config/findConfigFile.ts","../../src/node/core/config/loadConfig.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/logger.ts","../../node_modules/.pnpm/browserslist-to-esbuild@2.1.1_browserslist@4.25.1/node_modules/browserslist-to-esbuild/src/index.js","../../src/node/core/config/resolveConfigProperty.ts","../../src/node/core/defaults.ts","../../src/node/core/findCommonPath.ts","../../src/node/tasks/dts/getTargetPaths.ts","../../src/node/core/isRecord.ts","../../src/node/core/pkg/pkgExt.ts","../../src/node/core/pkg/validateExports.ts","../../src/node/core/pkg/parseExports.ts","../../src/node/core/ts/loadTSConfig.ts","../../src/node/resolveBrowserTarget.ts","../../src/node/resolveNodeTarget.ts","../../src/node/strict.ts","../../src/node/resolveBuildContext.ts","../../src/node/resolveBuildTasks.ts","../../src/node/spinner.ts","../../src/node/printExtractMessages.ts","../../src/node/tasks/dts/printDiagnostic.ts","../../src/node/tasks/dts/buildTypes.ts","../../src/node/tasks/dts/DtsError.ts","../../src/node/tasks/dts/createApiExtractorConfig.ts","../../src/node/tasks/dts/createTSDocConfig.ts","../../src/node/tasks/dts/extractModuleBlocks.ts","../../src/node/tasks/dts/getExtractMessagesConfig.ts","../../src/node/tasks/dts/extractTypes.ts","../../src/node/tasks/dts/doExtract.ts","../../src/node/tasks/dts/dtsTask.ts","../../src/node/tasks/dts/dtsWatchTask.ts","../../src/node/consoleSpy.ts","../../src/node/tasks/rolldown/rolldownDtsTask.ts","../../src/node/tasks/rollup/resolveRollupConfig.ts","../../src/node/tasks/rollup/rollupTask.ts","../../src/node/tasks/rollup/rollupWatchTask.ts","../../src/node/tasks/index.ts","../../src/node/build.ts","../../src/node/getFilesize.ts","../../src/node/printPackageTree.ts","../../src/node/check.ts","../../src/node/core/config/defineConfig.ts","../../src/node/core/template/define.ts","../../src/node/core/template/createFromTemplate.ts","../../src/node/isEmptyDirectory.ts","../../node_modules/.pnpm/@sanity+prettier-config@1.0.6_prettier@3.6.2/node_modules/@sanity/prettier-config/dist/index.js","../../src/node/templates/default/template.ts","../../src/node/init.ts","../../src/node/resolveWatchTasks.ts","../../src/node/globFiles.ts","../../src/node/watchFiles.ts","../../src/node/watchConfigFiles.ts","../../src/node/watch.ts"],"sourcesContent":["import {statSync} from 'node:fs'\n\n/** @internal */\nexport function fileExists(filePath: string): boolean {\n try {\n statSync(filePath)\n\n return true\n } catch {\n return false\n }\n}\n","import path from 'node:path'\nimport findConfig from 'find-config'\nimport {fileExists} from '../../fileExists'\n\nconst CONFIG_FILE_NAMES = [\n 'package.config.ts',\n 'package.config.js',\n 'package.config.cjs',\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","import {createRequire} from 'node:module'\nimport path from 'node:path'\nimport {register} from 'esbuild-register/dist/node'\nimport pkgUp from 'pkg-up'\nimport {findConfigFile} from './findConfigFile'\nimport type {PkgConfigOptions} from './types'\n\nconst require = createRequire(import.meta.url)\n\n/** @alpha */\nexport async function loadConfig(options: {cwd: string}): Promise<PkgConfigOptions | undefined> {\n const {cwd} = options\n\n const pkgPath = await pkgUp({cwd})\n\n if (!pkgPath) return undefined\n\n const root = path.dirname(pkgPath)\n\n const configFile = await 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 esbuildOptions = {extensions: ['.js', '.mjs', '.ts']}\n\n const {unregister} = globalThis.__DEV__ ? {unregister: () => undefined} : register(esbuildOptions)\n\n const mod = require(configFile)\n\n unregister()\n\n return mod?.default || mod || undefined\n}\n","/** @internal */\nexport function assertFirst<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 === 0\n}\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 {z} from 'zod'\nimport type {PackageJSON} from './types'\n\nconst pkgSchema = z.object({\n type: z.optional(z.enum(['commonjs', 'module'])),\n name: z.string(),\n version: z.string(),\n license: z.string(),\n bin: z.optional(z.record(z.string())),\n dependencies: z.optional(z.record(z.string())),\n devDependencies: z.optional(z.record(z.string())),\n peerDependencies: z.optional(z.record(z.string())),\n source: z.optional(z.string()),\n main: z.optional(z.string()),\n browser: z.optional(z.record(z.string())),\n module: z.optional(z.string()),\n types: z.optional(z.string()),\n exports: z.optional(\n z.record(\n z.union([\n z.custom<`./${string}.json`>((val) => /^\\.\\/.*\\.json$/.test(val as string)),\n z.custom<`./${string}.css`>((val) => /^\\.\\/.*\\.css$/.test(val as string)),\n z.object({\n types: z.optional(z.string()),\n source: z.optional(z.string()),\n browser: z.optional(\n z.object({\n source: z.string(),\n import: z.optional(z.string()),\n require: z.optional(z.string()),\n }),\n ),\n node: z.optional(\n z.object({\n source: z.optional(z.string()),\n import: z.optional(z.string()),\n require: z.optional(z.string()),\n }),\n ),\n import: z.optional(z.string()),\n require: z.optional(z.string()),\n default: z.string(),\n }),\n z.object({\n types: z.optional(z.string()),\n svelte: z.string(),\n default: z.optional(z.string()),\n }),\n ]),\n ),\n ),\n browserslist: z.optional(z.union([z.string(), z.array(z.string())])),\n sideEffects: z.optional(z.union([z.boolean(), z.array(z.string())])),\n // @TODO type this properly\n typesVersions: z.optional(z.any()),\n})\n\n// Create a map over known keys to catch casing mistakes\nconst typoMap = new Map<string, string>()\n\nfor (const key of pkgSchema.keyof()._def.values) {\n typoMap.set(key.toUpperCase(), key)\n}\n\nexport function validatePkg(input: unknown): PackageJSON {\n const pkg = pkgSchema.parse(input)\n\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 pkgUp from 'pkg-up'\nimport type {PackageJSON} from './types'\nimport {validatePkg} from './validatePkg'\n\n/** @internal */\nexport async function loadPkg(options: {cwd: string}): Promise<PackageJSON> {\n const {cwd} = options\n\n const pkgPath = await pkgUp({cwd})\n\n if (!pkgPath) throw new Error('no package.json found')\n\n const buf = await fs.readFile(pkgPath)\n\n const raw = JSON.parse(buf.toString())\n\n validatePkg(raw)\n\n return raw\n}\n","import chalk from 'chalk'\nimport {ZodError} from 'zod'\nimport type {Logger} from '../../logger'\nimport {assertLast, assertOrder} from './helpers'\nimport {loadPkg} from './loadPkg'\nimport type {PackageJSON} from './types'\n\n/** @alpha */\nexport async function loadPkgWithReporting(options: {\n cwd: string\n logger: Logger\n strict: boolean\n}): Promise<PackageJSON> {\n const {cwd, logger, strict} = options\n\n try {\n const pkg = await loadPkg({cwd})\n let shouldError = false\n\n if (strict) {\n if (!pkg.type) {\n shouldError = true\n logger.error(\n `the \\`type\\` field in \\`./package.json\\` must be either \"module\" or \"commonjs\")`,\n )\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 if (typeof exp === 'string' || '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.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 if (shouldError) {\n process.exit(1)\n }\n\n return pkg\n } catch (err) {\n if (err instanceof ZodError) {\n for (const issue of err.issues) {\n if (issue.code === 'invalid_type') {\n logger.error(\n [\n `\\`${formatPath(issue.path)}\\` `,\n `in \\`./package.json\\` must be of type ${chalk.magenta(issue.expected)} `,\n `(received ${chalk.magenta(issue.received)})`,\n ].join(''),\n )\n continue\n }\n\n logger.error(issue)\n }\n } else {\n logger.error(err)\n }\n\n 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","// oxlint-disable no-console\nimport chalk from 'chalk'\n\n/** @alpha */\nexport interface Logger {\n log: (...args: unknown[]) => void\n info: (...args: unknown[]) => void\n warn: (...args: unknown[]) => void\n error: (...args: unknown[]) => void\n success: (...args: unknown[]) => void\n}\n\n/** @alpha */\nexport function createLogger(quiet = false): Logger {\n return {\n log: (...args) => {\n if (!quiet) console.log(...args)\n },\n info: (...args) => {\n if (!quiet) console.log(chalk.blue('[info]'), ...args)\n },\n warn: (...args) => {\n console.log(chalk.yellow('[warning]'), ...args)\n },\n error: (...args) => {\n console.log(chalk.red('[error]'), ...args)\n },\n success: (...args) => {\n if (!quiet) console.log(chalk.green('[success]'), ...args)\n },\n }\n}\n","import browserslist from 'browserslist'\n\n// convert the browserslist field in package.json to\n// esbuild compatible array of browsers\nexport default function browserslistToEsbuild(browserslistConfig, options = {}) {\n if (!browserslistConfig) {\n // the path from where the script is run\n const path = process.cwd()\n\n // read config if none is passed\n browserslistConfig = browserslist.loadConfig({ path, ...options })\n }\n\n const SUPPORTED_ESBUILD_TARGETS = [\n 'es',\n 'chrome',\n 'edge',\n 'firefox',\n 'ios',\n 'node',\n 'safari',\n 'opera',\n 'ie',\n ]\n\n // https://github.com/eBay/browserslist-config/issues/16#issuecomment-863870093\n const UNSUPPORTED = ['android 4']\n\n const replaces = {\n ios_saf: 'ios',\n android: 'chrome',\n }\n\n const separator = ' '\n\n return (\n browserslist(browserslistConfig, options)\n // filter out the unsupported ones\n .filter((b) => !UNSUPPORTED.some((u) => b.startsWith(u)))\n // replaces safari TP with latest safari version\n .map((b) => {\n if (b === 'safari TP') {\n return browserslist('last 1 safari version')[0]\n }\n\n return b\n })\n // transform into ['chrome', '88']\n .map((b) => b.split(separator))\n // replace the similar browser\n .map((b) => {\n if (replaces[b[0]]) {\n b[0] = replaces[b[0]]\n }\n\n return b\n })\n // 11.0-12.0 --> 11.0\n .map((b) => {\n if (b[1].includes('-')) {\n b[1] = b[1].slice(0, b[1].indexOf('-'))\n }\n\n return b\n })\n // 11.0 --> 11\n .map((b) => {\n if (b[1].endsWith('.0')) {\n b[1] = b[1].slice(0, -2)\n }\n\n return b\n })\n // removes invalid versions that will break esbuild\n // https://github.com/evanw/esbuild/blob/35c0d65b9d4f29a26176404d2890d1b499634e9f/compat-table/src/caniuse.ts#L119-L122\n .filter((b) => /^\\d+(\\.\\d+)*$/.test(b[1]))\n // only get the targets supported by esbuild\n .filter((b) => SUPPORTED_ESBUILD_TARGETS.includes(b[0]))\n // only get the oldest version, assuming that the older version\n // is last in the array\n .reduce((acc, b) => {\n const existingIndex = acc.findIndex((br) => br[0] === b[0])\n\n if (existingIndex !== -1) {\n acc[existingIndex][1] = b[1]\n } else {\n acc.push(b)\n }\n return acc\n }, [])\n // remove separator\n .map((b) => b.join(''))\n )\n}\n","import type {PkgConfigProperty, PkgConfigPropertyResolver} from './types'\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 (typeof prop === 'function') {\n return (prop as PkgConfigPropertyResolver<T>)(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 dirPath = path.dirname(dirPath)\n\n if (dirPath === ret) {\n break\n }\n\n if (pathContains(dirPath, ret)) {\n ret = dirPath\n break\n }\n\n if (dirPath === '.') return undefined\n }\n }\n\n return ret\n}\n","import type {PkgBundle, PkgExport} from '../../core/config/types'\nimport type {PackageJSON} from '../../core/pkg/types'\n\n/** @internal */\nexport const fileEnding: RegExp = /\\.[mc]?js$/\n/** @internal */\nexport const dtsEnding = '.d.ts' as const\n/** @internal */\nexport const defaultEnding = '.js' as const\n/** @internal */\nexport const mjsEnding = '.mjs' as const\n/** @internal */\nexport const cjsEnding = '.cjs' as const\nconst mtsEnding = '.d.mts' as const\nconst ctsEnding = '.d.cts' as const\n\n/** @internal */\nexport function getTargetPaths(\n _type: PackageJSON['type'],\n expOrBundle: PkgExport | PkgExport['browser'] | PkgExport['node'] | PkgBundle,\n): string[] {\n const type = (_type === 'module' ? 'module' : 'commonjs') satisfies PackageJSON['type']\n\n const set = new Set<string>()\n\n if (expOrBundle?.import) {\n set.add(expOrBundle.import.replace(fileEnding, type === 'module' ? dtsEnding : mtsEnding))\n }\n\n if (expOrBundle?.require) {\n set.add(expOrBundle.require.replace(fileEnding, type === 'commonjs' ? dtsEnding : ctsEnding))\n }\n\n if (isPkgExport(expOrBundle)) {\n if (!expOrBundle.browser?.source) {\n if (expOrBundle.browser?.import) {\n set.add(\n expOrBundle.browser.import.replace(fileEnding, type === 'module' ? dtsEnding : mtsEnding),\n )\n }\n\n if (expOrBundle.browser?.require) {\n set.add(\n expOrBundle.browser.require.replace(\n fileEnding,\n type === 'commonjs' ? dtsEnding : ctsEnding,\n ),\n )\n }\n }\n\n if (!expOrBundle.node?.source) {\n if (expOrBundle.node?.import) {\n set.add(\n expOrBundle.node.import.replace(fileEnding, type === 'module' ? dtsEnding : mtsEnding),\n )\n }\n\n if (expOrBundle.node?.require) {\n set.add(\n expOrBundle.node.require.replace(fileEnding, type === 'commonjs' ? dtsEnding : ctsEnding),\n )\n }\n }\n }\n\n return Array.from(set)\n}\n\nfunction isPkgExport(exp: any): exp is PkgExport {\n return exp?.browser || exp?.node || exp?.default\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && !Array.isArray(value) && typeof value === 'object'\n}\n","import {cjsEnding, defaultEnding, mjsEnding} from '../../tasks/dts/getTargetPaths'\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 {PkgExport} from '../config/types'\nimport {pkgExtMap as extMap} from './pkgExt'\nimport type {PackageJSON} from './types'\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.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 type {Logger} from '../../logger'\nimport type {StrictOptions} from '../../strict'\nimport {defaultEnding, fileEnding} from '../../tasks/dts/getTargetPaths'\nimport type {PkgExport} from '../config/types'\nimport {isRecord} from '../isRecord'\nimport {pkgExtMap} from './pkgExt'\nimport type {PackageJSON} from './types'\nimport {validateExports} from './validateExports'\n\n/** @alpha */\nexport function parseExports(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 (!pkg.main && strict && strictOptions.alwaysPackageJsonMain !== 'off') {\n report(strictOptions.alwaysPackageJsonMain, 'package.json: `main` must be declared')\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(Boolean) as string[]),\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: (PkgExport & {_path: string})[] = []\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' && !existsSync(resolvePath(cwd, exportEntry))) {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: file does not exist.`,\n )\n } else if (typeof exportEntry !== 'string') {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: export conditions not supported for CSS files.`,\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\n _exports.push(exp)\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","import ts from 'typescript'\n\n/** @internal */\nexport async function loadTSConfig(options: {\n cwd: string\n tsconfigPath: string\n}): Promise<ts.ParsedCommandLine | undefined> {\n const {cwd, tsconfigPath} = options\n\n const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath)\n\n if (!configPath) {\n return undefined\n }\n\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 {z} from 'zod'\nimport {errorMap} from 'zod-validation-error'\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 alwaysPackageJsonMain: toggle.default('error'),\n alwaysPackageJsonFiles: toggle.default('error'),\n noCheckTypes: toggle.default('warn'),\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 * A lot of analysis tooling requiers the `main` field to work (like bundlephobia) and so it's best practice to always include it\n * @defaultValue 'error'\n */\n alwaysPackageJsonMain: 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\n/** @alpha */\nexport function parseStrictOptions(input: unknown): StrictOptions {\n return validationSchema.parse({strictOptions: input}, {errorMap}).strictOptions\n}\n","import path from 'node:path'\nimport browserslistToEsbuild from 'browserslist-to-esbuild'\nimport {resolveConfigProperty} from './core/config/resolveConfigProperty'\nimport {type PkgConfigOptions, type PkgExports, type PkgRuntime} from './core/config/types'\nimport type {BuildContext} from './core/contexts/buildContext'\nimport {DEFAULT_BROWSERSLIST_QUERY} from './core/defaults'\nimport {findCommonDirPath, pathContains} from './core/findCommonPath'\nimport {parseExports} from './core/pkg/parseExports'\nimport type {PackageJSON} from './core/pkg/types'\nimport {loadTSConfig} from './core/ts/loadTSConfig'\nimport type {Logger} from './logger'\nimport {resolveBrowserTarget} from './resolveBrowserTarget'\nimport {resolveNodeTarget} from './resolveNodeTarget'\nimport {parseStrictOptions} from './strict'\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 if (strictOptions.noCheckTypes !== 'off' && tsconfig?.options && config?.dts !== 'rolldown') {\n if (tsconfig.options.noCheck !== false && !tsconfig.options.noCheck) {\n if (strictOptions.noCheckTypes === 'error') {\n throw new Error(\n '`noCheck` is not set to `true` in the tsconfig.json file used by `package.config.ts`. This makes generating dts files slower than it needs to be, as it will perform type checking on the dts files while at it.',\n )\n } else {\n logger.warn(\n '`noCheck` is not set to `true` in the tsconfig.json file used by `package.config.ts`. This makes generating dts files slower than it needs to be, as it will perform type checking on the dts files while at it.',\n )\n }\n }\n }\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 = parseExports({\n cwd,\n pkg,\n strict,\n strictOptions,\n logger,\n }).reduce<PkgExports>(\n (acc, {_path: exportPath, ...exportEntry}) => Object.assign(acc, {[exportPath]: exportEntry}),\n {},\n )\n\n const exports = resolveConfigProperty(config?.exports, parsedExports)\n\n const parsedExternal = [\n ...(pkg.dependencies ? Object.keys(pkg.dependencies) : []),\n ...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []),\n ]\n\n // Merge externals if an array is provided, replace if it's a function\n const external =\n config && Array.isArray(config.external)\n ? [...parsedExternal, ...config.external]\n : resolveConfigProperty(config?.external, parsedExternal)\n // Merge bundledPackages with dev deps, replace if it's a function\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 config && Array.isArray(config.extract?.bundledPackages)\n ? [...bundledDependencies, ...config.extract.bundledPackages]\n : resolveConfigProperty(config?.extract?.bundledPackages, bundledDependencies)\n\n const outputPaths = Object.values(exports)\n .flatMap((exportEntry) => {\n return [\n exportEntry.import,\n exportEntry.require,\n exportEntry.browser?.import,\n exportEntry.browser?.require,\n exportEntry.node?.source && exportEntry.node.import,\n exportEntry.node?.source && exportEntry.node.require,\n ].filter(Boolean) as string[]\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 distPath,\n emitDeclarationOnly,\n exports,\n external,\n bundledPackages,\n files: [],\n logger,\n pkg,\n runtime: config?.runtime ?? '*',\n strict,\n target,\n ts: {\n config: tsconfig,\n configPath: tsconfigPath,\n },\n dts: config?.dts === 'rolldown' ? 'rolldown' : 'api-extractor',\n }\n\n return ctx\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","import path from 'node:path'\nimport type {PkgExport, PkgFormat, PkgRuntime} from './core/config/types'\nimport type {BuildContext} from './core/contexts/buildContext'\nimport {getTargetPaths} from './tasks/dts/getTargetPaths'\nimport type {DtsTask} from './tasks/dts/types'\nimport type {BuildTask, RolldownDtsTask, RollupTask, RollupTaskEntry} from './tasks/types'\n\n/** @internal */\nexport function resolveBuildTasks(ctx: BuildContext): BuildTask[] {\n const {config, pkg, target} = ctx\n\n const bundles = config?.bundles || []\n\n const tasks: BuildTask[] = []\n\n const exports = Object.entries(ctx.exports || {}).map(\n ([_path, exp]) => ({_path, ...exp}) as PkgExport & {_path: string},\n )\n\n const dtsTask: DtsTask = {\n type: 'build:dts',\n entries: [],\n }\n\n const rolldownDtsTask: Record<string, RolldownDtsTask> = {}\n const rollupTasks: Record<string, RollupTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\n if (ctx.dts === 'rolldown') {\n if (rolldownDtsTask[buildId]) {\n rolldownDtsTask[buildId].entries.push(entry)\n } else {\n rolldownDtsTask[buildId] = {\n type: 'rolldown:dts',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n\n if (!ctx.emitDeclarationOnly) {\n if (rollupTasks[buildId]) {\n rollupTasks[buildId].entries.push(entry)\n } else {\n rollupTasks[buildId] = {\n type: 'build:js',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n }\n\n if (ctx.dts === 'api-extractor') {\n // Parse `dts` tasks\n for (const exp of exports) {\n const importId = path.join(pkg.name, exp._path)\n\n if (exp.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.source,\n targetPaths: getTargetPaths(pkg.type, exp),\n })\n }\n\n if (exp.browser?.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.browser.source,\n targetPaths: getTargetPaths(pkg.type, exp.browser),\n })\n }\n\n if (exp.node?.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.node.source,\n targetPaths: getTargetPaths(pkg.type, exp.node),\n })\n }\n }\n\n // Handle dts tasks for bundles\n for (const bundle of bundles) {\n if (bundle.source?.endsWith('.ts')) {\n // importId needs to be how the bundle is used, like `@sanity/pkg-utils/dist/cli`\n // exportPath needs to be the path to the bundle, like `./dist/cli`\n // targetPaths is then: [./dist/cli.d.ts, ./dist/cli.d.cts]\n const exportPath = (bundle.import || bundle.require)!.replace(/\\.[mc]?js$/, '')\n const importId = path.join(pkg.name, exportPath)\n\n dtsTask.entries.push({\n importId,\n exportPath,\n sourcePath: bundle.source,\n targetPaths: getTargetPaths(pkg.type, bundle),\n })\n }\n }\n\n // Add dts task\n if (dtsTask.entries.length) {\n tasks.push(dtsTask)\n }\n }\n\n // Parse rollup:commonjs:* tasks\n for (const exp of exports) {\n const output = exp.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:* tasks\n for (const exp of exports) {\n const output = exp.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n for (const bundle of bundles) {\n const idx = bundles.indexOf(bundle)\n\n if (bundle.require) {\n addRollupTaskEntry('commonjs', bundle.runtime || ctx.runtime, {\n path: `__$$bundle_cjs_${idx}$$__`,\n source: bundle.source,\n output: bundle.require,\n })\n }\n\n if (bundle.import) {\n addRollupTaskEntry('esm', bundle.runtime || ctx.runtime, {\n path: `__$$bundle_esm_${idx}$$__`,\n source: bundle.source,\n output: bundle.import,\n })\n }\n }\n\n // Perform rolldown dts tasks first, as they have special logic for removing non .d.ts chunks\n tasks.push(...Object.values(rolldownDtsTask))\n // Then run api-extractor tsdoc release tag checking (if rolldown is used for dts bundling, otherwise api-extractor performs both in the build:dts task)\n // @TODO\n // Then run rollup tasks\n tasks.push(...Object.values(rollupTasks))\n\n return tasks\n}\n","// oxlint-disable no-console\nimport chalk from 'chalk'\n\nexport function createSpinner(\n msg: string,\n quiet = false,\n): {complete: () => void; error: () => void} {\n const startTime = Date.now()\n\n if (!quiet) console.log(msg)\n\n return {\n complete: () => {\n if (!quiet)\n console.log(`${chalk.green('[success]')} ${chalk.gray(`${Date.now() - startTime}ms`)}`)\n },\n error: () => {\n console.log(`${chalk.red('[error]')} ${chalk.gray(`${Date.now() - startTime}ms`)}`)\n },\n }\n}\n","import path from 'node:path'\nimport type {ExtractorMessage} from '@microsoft/api-extractor'\nimport chalk from 'chalk'\nimport type {BuildContext} from './core/contexts/buildContext'\n\nexport function printExtractMessages(ctx: BuildContext, messages: ExtractorMessage[]): void {\n const {cwd, logger} = ctx\n\n const warnings = messages.filter((msg) => msg.logLevel === 'warning')\n\n if (warnings.length) {\n logger.log()\n }\n\n for (const msg of warnings) {\n const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath)\n\n if (msg.messageId === 'TS6307') {\n // Ignore this warning:\n // > TS6307: <filename> is not in project file list.\n // > Projects must list all files or use an 'include' pattern.\n continue\n }\n\n logger.log(\n [\n `${chalk.cyan(sourceFilePath || '?')}`,\n `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,\n ` - ${chalk.yellow('warning')} ${chalk.gray(msg.messageId)}\\n`,\n msg.text,\n '\\n',\n ].join(''),\n )\n }\n\n const errors: ExtractorMessage[] = messages.filter((msg) => msg.logLevel === 'error')\n\n if (!warnings.length && errors.length) {\n logger.log('')\n }\n\n for (const msg of errors) {\n const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath)\n\n logger.log(\n [\n `${chalk.cyan(sourceFilePath || '?')}`,\n `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,\n ` - ${chalk.red('error')} ${chalk.gray(msg.messageId)}\\n`,\n msg.text,\n '\\n',\n ].join(''),\n )\n }\n\n if (errors.length) {\n process.exit(1)\n }\n}\n","import path from 'node:path'\nimport chalk from 'chalk'\nimport ts from 'typescript'\nimport type {Logger} from '../../logger'\n\nexport function printDiagnostic(options: {\n cwd: string\n logger: Logger\n diagnostic: ts.Diagnostic\n}): void {\n const {cwd, logger, diagnostic} = options\n\n if (diagnostic.file && diagnostic.start) {\n const {line, character} = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start)\n const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n')\n\n const file = path.relative(cwd, diagnostic.file.fileName)\n\n const output = [\n `${chalk.yellow(file)}:${chalk.blue(line + 1)}:${chalk.blue(character + 1)} - `,\n `${chalk.gray(`TS${diagnostic.code}:`)} ${message}`,\n ].join('')\n\n if (diagnostic.category === ts.DiagnosticCategory.Error) {\n logger.error(output)\n }\n\n if (diagnostic.category === ts.DiagnosticCategory.Warning) {\n logger.warn(output)\n }\n\n if (diagnostic.category === ts.DiagnosticCategory.Message) {\n logger.log(output)\n }\n\n if (diagnostic.category === ts.DiagnosticCategory.Suggestion) {\n logger.log(output)\n }\n } else {\n logger.log(ts.flattenDiagno