@sanity/pkg-utils 7.2.8-canary.0 → 7.2.8-canary.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/pkg-utils.cjs +0 -1
- package/dist/_chunks-cjs/build.cjs +4 -4
- package/dist/_chunks-cjs/build.cjs.map +1 -1
- package/dist/_chunks-cjs/check.cjs +14 -14
- package/dist/_chunks-cjs/check.cjs.map +1 -1
- package/dist/_chunks-cjs/consoleSpy.cjs +153 -83
- package/dist/_chunks-cjs/consoleSpy.cjs.map +1 -1
- package/dist/_chunks-cjs/index.cjs +0 -1
- package/dist/_chunks-cjs/index.cjs.map +1 -1
- package/dist/_chunks-cjs/init.cjs +11 -11
- package/dist/_chunks-cjs/init.cjs.map +1 -1
- package/dist/_chunks-cjs/isRecord.cjs +39 -0
- package/dist/_chunks-cjs/isRecord.cjs.map +1 -0
- package/dist/_chunks-cjs/watch.cjs +8 -8
- package/dist/_chunks-cjs/watch.cjs.map +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +130 -127
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/node/build.ts +4 -2
- package/src/node/check.ts +2 -3
- package/src/node/core/config/findConfigFile.ts +0 -2
- package/src/node/core/config/loadConfig.ts +0 -2
- package/src/node/core/config/types.ts +0 -4
- package/src/node/core/contexts/buildContext.ts +2 -3
- package/src/node/core/pkg/loadPkg.ts +0 -2
- package/src/node/core/pkg/loadPkgWithReporting.ts +0 -1
- package/src/node/core/pkg/parseExports.ts +1 -2
- package/src/node/core/pkg/validateExports.ts +1 -1
- package/src/node/core/pkg/validatePkg.ts +0 -1
- package/src/node/core/template/createFromTemplate.ts +0 -2
- package/src/node/getFilesize.ts +0 -1
- package/src/node/globFiles.ts +0 -1
- package/src/node/index.ts +64 -8
- package/src/node/init.ts +2 -4
- package/src/node/printExtractMessages.ts +1 -3
- package/src/node/printPackageTree.ts +2 -3
- package/src/node/resolveBuildContext.ts +11 -14
- package/src/node/resolveBuildTasks.ts +4 -3
- package/src/node/resolveWatchTasks.ts +4 -3
- package/src/node/strict.test-d.ts +0 -1
- package/src/node/tasks/dts/buildTypes.ts +0 -1
- package/src/node/tasks/dts/createApiExtractorConfig.ts +0 -1
- package/src/node/tasks/dts/createTSDocConfig.ts +0 -1
- package/src/node/tasks/dts/doExtract.ts +1 -1
- package/src/node/tasks/dts/dtsTask.ts +0 -1
- package/src/node/tasks/dts/extractTypes.ts +2 -1
- package/src/node/tasks/dts/getExtractMessagesConfig.ts +1 -2
- package/src/node/tasks/dts/getTargetPaths.ts +2 -1
- package/src/node/tasks/dts/printDiagnostic.ts +0 -2
- package/src/node/tasks/index.ts +4 -6
- package/src/node/tasks/rollup/resolveRollupConfig.ts +3 -1
- package/src/node/tasks/rollup/rollupTask.ts +1 -3
- package/src/node/tasks/rollup/rollupWatchTask.ts +1 -3
- package/src/node/tasks/types.ts +4 -4
- package/src/node/templates/default/template.ts +4 -7
- package/src/node/watch.ts +4 -4
- package/src/node/watchConfigFiles.ts +0 -2
- package/dist/_chunks-cjs/logger.cjs +0 -107
- package/dist/_chunks-cjs/logger.cjs.map +0 -1
- package/src/node/core/index.ts +0 -7
- package/src/node/tasks/dts/index.ts +0 -4
- package/src/node/tasks/rollup/index.ts +0 -2
package/bin/pkg-utils.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var path = require("node:path"), rimraf = require("rimraf"), consoleSpy = require("./consoleSpy.cjs"),
|
|
2
|
+
var path = require("node:path"), rimraf = require("rimraf"), consoleSpy = require("./consoleSpy.cjs"), isRecord = require("./isRecord.cjs"), chalk = require("chalk"), index = require("./index.cjs");
|
|
3
3
|
function _interopDefaultCompat(e) {
|
|
4
4
|
return e && typeof e == "object" && "default" in e ? e : { default: e };
|
|
5
5
|
}
|
|
@@ -118,16 +118,16 @@ async function build(options) {
|
|
|
118
118
|
strict = !1,
|
|
119
119
|
tsconfig: tsconfigOption,
|
|
120
120
|
clean = !1
|
|
121
|
-
} = options, logger
|
|
121
|
+
} = options, logger = isRecord.createLogger(), config = await consoleSpy.loadConfig({ cwd }), pkg = await consoleSpy.loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config?.tsconfig || "tsconfig.json", ctx = await consoleSpy.resolveBuildContext({
|
|
122
122
|
config,
|
|
123
123
|
cwd,
|
|
124
124
|
emitDeclarationOnly,
|
|
125
|
-
logger
|
|
125
|
+
logger,
|
|
126
126
|
pkg,
|
|
127
127
|
strict,
|
|
128
128
|
tsconfig
|
|
129
129
|
});
|
|
130
|
-
clean && (logger
|
|
130
|
+
clean && (logger.log(
|
|
131
131
|
`Deleting the \`dist\` folder: './${path__default.default.relative(cwd, ctx.distPath)}' before building...`
|
|
132
132
|
), await rimraf.rimraf(ctx.distPath));
|
|
133
133
|
const buildTasks = resolveBuildTasks(ctx);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.cjs","sources":["../../src/node/resolveBuildTasks.ts","../../src/node/spinner.ts","../../src/node/build.ts"],"sourcesContent":["import path from 'node:path'\n\nimport type {BuildContext, PkgExport, PkgFormat, PkgRuntime} from './core'\nimport type {BuildTask, DtsTask, RollupTask, RollupTaskEntry} from './tasks'\nimport {getTargetPaths} from './tasks/dts/getTargetPaths'\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 rollupTasks: Record<string, RollupTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\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 // 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 if (!ctx.emitDeclarationOnly) {\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 tasks.push(...Object.values(rollupTasks))\n }\n\n return tasks\n}\n","// oxlint-disable no-console\nimport chalk from 'chalk'\n\nexport function createSpinner(msg: string): {complete: () => void; error: () => void} {\n const startTime = Date.now()\n\n console.log(msg)\n\n return {\n complete: () => {\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 {rimraf} from 'rimraf'\nimport {loadConfig, loadPkgWithReporting} from './core'\nimport {createLogger} from './logger'\nimport {resolveBuildContext} from './resolveBuildContext'\nimport {resolveBuildTasks} from './resolveBuildTasks'\nimport {createSpinner} from './spinner'\nimport {buildTaskHandlers, type BuildTask, type TaskHandler} from './tasks'\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}): Promise<void> {\n const {\n cwd,\n emitDeclarationOnly,\n strict = false,\n tsconfig: tsconfigOption,\n clean = false,\n } = options\n const logger = createLogger()\n\n const config = await loadConfig({cwd})\n\n const pkg = await loadPkgWithReporting({cwd, logger, strict})\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 if (clean) {\n logger.log(\n `Deleting the \\`dist\\` folder: './${path.relative(cwd, ctx.distPath)}' before building...`,\n )\n await rimraf(ctx.distPath)\n }\n\n const buildTasks = resolveBuildTasks(ctx)\n\n for (const task of buildTasks) {\n const handler = buildTaskHandlers[task.type] as TaskHandler<BuildTask>\n const taskName = handler.name(ctx, task)\n\n const spinner = createSpinner(taskName)\n\n try {\n const result = await handler.exec(ctx, task).toPromise()\n\n spinner.complete()\n ctx.logger.log()\n\n handler.complete(ctx, task, result)\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(`${cwd}`, 'g')\n\n ctx.logger.error(err.message.replace(RE_CWD, '.'))\n ctx.logger.log()\n }\n\n handler.error(ctx, task, err)\n\n process.exit(1)\n }\n }\n}\n"],"names":["exports","path","getTargetPaths","chalk","logger","createLogger","loadConfig","loadPkgWithReporting","resolveBuildContext","rimraf","buildTaskHandlers"],"mappings":";;;;;;AAOO,SAAS,kBAAkB,KAAgC;AAC1D,QAAA,EAAC,QAAQ,KAAK,OAAA,IAAU,KAExB,UAAU,QAAQ,WAAW,CAAA,GAE7B,QAAqB,IAErBA,WAAU,OAAO,QAAQ,IAAI,WAAW,CAAE,CAAA,EAAE;AAAA,IAChD,CAAC,CA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AAAA,QAAK,SAAS,KAAK,IAAI,QAAQ,CAAC;AAAA,EAEtE,GAAA,MAAMQ,OAAO,OAAA,IAAI,QAAQ;AAGrB,QAAA,aAAa,kBAAkB,GAAG;AAExC,aAAW,QAAQ,YAAY;AAC7B,UAAM,UAAUC,MAAA,kBAAkB,KAAK,IAAI,GACrC,WAAW,QAAQ,KAAK,KAAK,IAAI,GAEjC,UAAU,cAAc,QAAQ;AAElC,QAAA;AACF,YAAM,SAAS,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE,UAAU;AAE/C,cAAA,SAAA,GACR,IAAI,OAAO,OAEX,QAAQ,SAAS,KAAK,MAAM,MAAM;AAAA,aAC3B,KAAK;AAGZ,UAFA,QAAQ,SAEJ,eAAe,OAAO;AACxB,cAAM,SAAS,IAAI,OAAO,GAAG,GAAG,IAAI,GAAG;AAEnC,YAAA,OAAO,MAAM,IAAI,QAAQ,QAAQ,QAAQ,GAAG,CAAC,GACjD,IAAI,OAAO,IAAI;AAAA,MAAA;AAGjB,cAAQ,MAAM,KAAK,MAAM,GAAG,GAE5B,QAAQ,KAAK,CAAC;AAAA,IAAA;AAAA,EAChB;AAEJ;;;"}
|
|
1
|
+
{"version":3,"file":"build.cjs","sources":["../../src/node/resolveBuildTasks.ts","../../src/node/spinner.ts","../../src/node/build.ts"],"sourcesContent":["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, 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 rollupTasks: Record<string, RollupTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\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 // 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 if (!ctx.emitDeclarationOnly) {\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 tasks.push(...Object.values(rollupTasks))\n }\n\n return tasks\n}\n","// oxlint-disable no-console\nimport chalk from 'chalk'\n\nexport function createSpinner(msg: string): {complete: () => void; error: () => void} {\n const startTime = Date.now()\n\n console.log(msg)\n\n return {\n complete: () => {\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 {rimraf} from 'rimraf'\nimport {loadConfig} from './core/config/loadConfig'\nimport {loadPkgWithReporting} from './core/pkg/loadPkgWithReporting'\nimport {createLogger} from './logger'\nimport {resolveBuildContext} from './resolveBuildContext'\nimport {resolveBuildTasks} from './resolveBuildTasks'\nimport {createSpinner} from './spinner'\nimport {buildTaskHandlers} from './tasks'\nimport {type BuildTask, type TaskHandler} from './tasks/types'\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}): Promise<void> {\n const {\n cwd,\n emitDeclarationOnly,\n strict = false,\n tsconfig: tsconfigOption,\n clean = false,\n } = options\n const logger = createLogger()\n\n const config = await loadConfig({cwd})\n\n const pkg = await loadPkgWithReporting({cwd, logger, strict})\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 if (clean) {\n logger.log(\n `Deleting the \\`dist\\` folder: './${path.relative(cwd, ctx.distPath)}' before building...`,\n )\n await rimraf(ctx.distPath)\n }\n\n const buildTasks = resolveBuildTasks(ctx)\n\n for (const task of buildTasks) {\n const handler = buildTaskHandlers[task.type] as TaskHandler<BuildTask>\n const taskName = handler.name(ctx, task)\n\n const spinner = createSpinner(taskName)\n\n try {\n const result = await handler.exec(ctx, task).toPromise()\n\n spinner.complete()\n ctx.logger.log()\n\n handler.complete(ctx, task, result)\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(`${cwd}`, 'g')\n\n ctx.logger.error(err.message.replace(RE_CWD, '.'))\n ctx.logger.log()\n }\n\n handler.error(ctx, task, err)\n\n process.exit(1)\n }\n }\n}\n"],"names":["exports","path","getTargetPaths","chalk","createLogger","loadConfig","loadPkgWithReporting","resolveBuildContext","rimraf","buildTaskHandlers"],"mappings":";;;;;;AAQO,SA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AEjD,MAAM,MAAMC,WAAAA,oBAAoB;AAAA,IACpC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAEG,YACF,OAAO;AAAA,IACL,oCAAoCN,cAAAA,QAAK,SAAS,KAAK,IAAI,QAAQ,CAAC;AAAA,EAEtE,GAAA,MAAMO,OAAO,OAAA,IAAI,QAAQ;AAGrB,QAAA,aAAa,kBAAkB,GAAG;AAExC,aAAW,QAAQ,YAAY;AAC7B,UAAM,UAAUC,MAAA,kBAAkB,KAAK,IAAI,GACrC,WAAW,QAAQ,KAAK,KAAK,IAAI,GAEjC,UAAU,cAAc,QAAQ;AAElC,QAAA;AACF,YAAM,SAAS,MAAM,QAAQ,KAAK,KAAK,IAAI,EAAE,UAAU;AAE/C,cAAA,SAAA,GACR,IAAI,OAAO,OAEX,QAAQ,SAAS,KAAK,MAAM,MAAM;AAAA,aAC3B,KAAK;AAGZ,UAFA,QAAQ,SAEJ,eAAe,OAAO;AACxB,cAAM,SAAS,IAAI,OAAO,GAAG,GAAG,IAAI,GAAG;AAEnC,YAAA,OAAO,MAAM,IAAI,QAAQ,QAAQ,QAAQ,GAAG,CAAC,GACjD,IAAI,OAAO,IAAI;AAAA,MAAA;AAGjB,cAAQ,MAAM,KAAK,MAAM,GAAG,GAE5B,QAAQ,KAAK,CAAC;AAAA,IAAA;AAAA,EAChB;AAEJ;;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var path = require("node:path"), esbuild = require("esbuild"), consoleSpy = require("./consoleSpy.cjs"),
|
|
2
|
+
var path = require("node:path"), esbuild = require("esbuild"), consoleSpy = require("./consoleSpy.cjs"), isRecord = require("./isRecord.cjs"), chalk = require("chalk"), treeify = require("treeify"), node_fs = require("node:fs"), prettyBytes = require("pretty-bytes");
|
|
3
3
|
function _interopDefaultCompat(e) {
|
|
4
4
|
return e && typeof e == "object" && "default" in e ? e : { default: e };
|
|
5
5
|
}
|
|
@@ -9,13 +9,13 @@ function getFilesize(file) {
|
|
|
9
9
|
return prettyBytes__default.default(stats.size);
|
|
10
10
|
}
|
|
11
11
|
function getFileInfo(cwd, filePath) {
|
|
12
|
-
const p = path__default.default.resolve(cwd, filePath), exists =
|
|
12
|
+
const p = path__default.default.resolve(cwd, filePath), exists = isRecord.fileExists(p), size = exists ? getFilesize(p) : void 0;
|
|
13
13
|
return { exists, size };
|
|
14
14
|
}
|
|
15
15
|
function printPackageTree(ctx) {
|
|
16
|
-
const { cwd, exports: exports2, logger
|
|
16
|
+
const { cwd, exports: exports2, logger, pkg } = ctx;
|
|
17
17
|
if (!exports2) return;
|
|
18
|
-
|
|
18
|
+
logger.log(`${chalk__default.default.blue(pkg.name)}@${chalk__default.default.green(pkg.version)}`);
|
|
19
19
|
const tree = {};
|
|
20
20
|
pkg.type && (tree.type = chalk__default.default.yellow(pkg.type)), pkg.bin && (tree.bin = Object.fromEntries(
|
|
21
21
|
Object.entries(pkg.bin).map(([name, file]) => [chalk__default.default.cyan(name), fileInfo(file)])
|
|
@@ -36,15 +36,15 @@ function printPackageTree(ctx) {
|
|
|
36
36
|
};
|
|
37
37
|
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__default.default.cyan(path__default.default.join(pkg.name, exportPath)), exp];
|
|
38
38
|
})
|
|
39
|
-
),
|
|
39
|
+
), logger.log(treeify__default.default.asTree(tree, !0, !0));
|
|
40
40
|
}
|
|
41
41
|
async function check(options) {
|
|
42
|
-
const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger
|
|
42
|
+
const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = isRecord.createLogger(), config = await consoleSpy.loadConfig({ cwd }), pkg = await consoleSpy.loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config?.tsconfig || "tsconfig.json", ctx = await consoleSpy.resolveBuildContext({ config, cwd, logger, pkg, strict, tsconfig });
|
|
43
43
|
if (printPackageTree(ctx), strict) {
|
|
44
44
|
const missingFiles = [];
|
|
45
45
|
for (const [, exp] of Object.entries(ctx.exports || {}))
|
|
46
|
-
exp.source && !
|
|
47
|
-
ctx.pkg.types && !
|
|
46
|
+
exp.source && !isRecord.fileExists(path__default.default.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !isRecord.fileExists(path__default.default.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !isRecord.fileExists(path__default.default.resolve(cwd, exp.import)) && missingFiles.push(exp.import);
|
|
47
|
+
ctx.pkg.types && !isRecord.fileExists(path__default.default.resolve(cwd, ctx.pkg.types)) && missingFiles.push(ctx.pkg.types), missingFiles.length && (logger.error(`missing files: ${missingFiles.join(", ")}`), process.exit(1));
|
|
48
48
|
const exportPaths = {
|
|
49
49
|
require: [],
|
|
50
50
|
import: []
|
|
@@ -55,11 +55,11 @@ async function check(options) {
|
|
|
55
55
|
...Object.keys(pkg.dependencies || {}),
|
|
56
56
|
...Object.keys(pkg.devDependencies || {})
|
|
57
57
|
], consoleSpy$1 = consoleSpy.createConsoleSpy();
|
|
58
|
-
exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger
|
|
58
|
+
exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger }), exportPaths.require.length && checkExports(exportPaths.require, { cwd, external, format: "cjs", logger }), consoleSpy$1.restore();
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
async function checkExports(exportPaths, options) {
|
|
62
|
-
const { cwd, external, format, logger
|
|
62
|
+
const { cwd, external, format, logger } = options, code = exportPaths.map((id) => format ? `import('${id}');` : `require('${id}');`).join(`
|
|
63
63
|
`);
|
|
64
64
|
try {
|
|
65
65
|
const esbuildResult = await esbuild__default.default.build({
|
|
@@ -78,20 +78,20 @@ async function checkExports(exportPaths, options) {
|
|
|
78
78
|
});
|
|
79
79
|
if (esbuildResult.errors.length > 0) {
|
|
80
80
|
for (const msg of esbuildResult.errors)
|
|
81
|
-
printEsbuildMessage(
|
|
81
|
+
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
82
82
|
process.exit(1);
|
|
83
83
|
}
|
|
84
84
|
const esbuildWarnings = esbuildResult.warnings.filter((msg) => {
|
|
85
85
|
(msg.detail || msg.text).includes("does not affect esbuild's own target setting");
|
|
86
86
|
});
|
|
87
87
|
for (const msg of esbuildWarnings)
|
|
88
|
-
printEsbuildMessage(
|
|
88
|
+
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
89
89
|
} catch (err) {
|
|
90
90
|
if (isEsbuildFailure(err)) {
|
|
91
91
|
const { errors } = err;
|
|
92
92
|
for (const msg of errors)
|
|
93
|
-
printEsbuildMessage(
|
|
94
|
-
} else err instanceof Error ? (
|
|
93
|
+
printEsbuildMessage(logger.error, msg), logger.log();
|
|
94
|
+
} else err instanceof Error ? (logger.error(err.stack || err.message), logger.log()) : (logger.error(`${err}`), logger.log());
|
|
95
95
|
process.exit(1);
|
|
96
96
|
}
|
|
97
97
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"check.cjs","sources":["../../src/node/getFilesize.ts","../../src/node/printPackageTree.ts","../../src/node/check.ts"],"sourcesContent":["import {statSync} from 'node:fs'\n\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'\n\nimport chalk from 'chalk'\nimport treeify from 'treeify'\n\nimport type {BuildContext, PkgExport} from './core'\nimport {fileExists} from './fileExists'\nimport {getFilesize} from './getFilesize'\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 } 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 } 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'\n\nimport esbuild, {type BuildFailure, type Message} from 'esbuild'\n\nimport {createConsoleSpy} from './consoleSpy'\nimport {loadConfig, loadPkgWithReporting} from './core'\nimport {fileExists} from './fileExists'\nimport {createLogger, type Logger} from './logger'\nimport {printPackageTree} from './printPackageTree'\nimport {resolveBuildContext} from './resolveBuildContext'\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\n const config = await loadConfig({cwd})\n const pkg = await loadPkgWithReporting({cwd, logger, strict})\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 // Check if the files are resolved\n const exportPaths: {require: string[]; import: string[]} = {\n require: [],\n import: [],\n }\n\n for (const exp of Object.values(ctx.exports || {})) {\n if (!exp._exported) continue\n if (exp.require) exportPaths.require.push(exp.require)\n if (exp.import) exportPaths.import.push(exp.import)\n }\n\n const external = [\n ...Object.keys(pkg.dependencies || {}),\n ...Object.keys(pkg.devDependencies || {}),\n ]\n\n const consoleSpy = createConsoleSpy()\n\n if (exportPaths.import.length) {\n checkExports(exportPaths.import, {cwd, external, format: 'esm', logger})\n }\n\n if (exportPaths.require.length) {\n checkExports(exportPaths.require, {cwd, external, format: 'cjs', logger})\n }\n\n consoleSpy.restore()\n }\n}\n\nasync function checkExports(\n exportPaths: string[],\n options: {cwd: string; external: string[]; format: 'esm' | 'cjs'; logger: Logger},\n) {\n const {cwd, external, format, logger} = options\n\n const code = exportPaths\n .map((id) => (format ? `import('${id}');` : `require('${id}');`))\n .join('\\n')\n\n try {\n const esbuildResult = await esbuild.build({\n bundle: true,\n external,\n format,\n logLevel: 'silent',\n // otherwise output maps to stdout as we're using stdin\n outfile: '/dev/null',\n platform: 'node',\n stdin: {\n contents: code,\n loader: 'js',\n resolveDir: cwd,\n },\n })\n\n if (esbuildResult.errors.length > 0) {\n for (const msg of esbuildResult.errors) {\n printEsbuildMessage(logger.warn, msg)\n\n logger.log()\n }\n\n process.exit(1)\n }\n\n const esbuildWarnings = esbuildResult.warnings.filter((msg) => {\n !(msg.detail || msg.text).includes(`does not affect esbuild's own target setting`)\n })\n\n for (const msg of esbuildWarnings) {\n printEsbuildMessage(logger.warn, msg)\n\n logger.log()\n }\n } catch (err) {\n if (isEsbuildFailure(err)) {\n const {errors} = err\n\n for (const msg of errors) {\n printEsbuildMessage(logger.error, msg)\n\n logger.log()\n }\n } else if (err instanceof Error) {\n logger.error(err.stack || err.message)\n\n logger.log()\n } else {\n logger.error(`${err}`)\n\n logger.log()\n }\n\n process.exit(1)\n }\n}\n\nfunction printEsbuildMessage(log: (...args: unknown[]) => void, msg: esbuild.Message) {\n if (msg.location) {\n log(\n [\n `${msg.detail || msg.text}\\n`,\n `${msg.location.line} | ${msg.location.lineText}\\n`,\n `in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`,\n ].join(''),\n )\n } else {\n log(msg.detail || msg.text)\n }\n}\n\nfunction isEsbuildFailure(err: unknown): err is BuildFailure {\n return (\n err instanceof Error &&\n 'errors' in err &&\n Array.isArray(err.errors) &&\n err.errors.every(isEsbuildMessage) &&\n 'warnings' in err &&\n Array.isArray(err.warnings) &&\n err.warnings.every(isEsbuildMessage)\n )\n}\n\nfunction isEsbuildMessage(msg: unknown): msg is Message {\n return (\n typeof msg === 'object' &&\n msg !== null &&\n 'text' in msg &&\n typeof msg.text === 'string' &&\n 'location' in msg &&\n (msg.location === null || typeof msg.location === 'object')\n )\n}\n"],"names":["statSync","prettyBytes","path","fileExists","exports","logger","chalk","treeify","createLogger","loadConfig","loadPkgWithReporting","resolveBuildContext","consoleSpy","createConsoleSpy","esbuild"],"mappings":";;;;;;AAIO,SAAS,YAAY,MAAsB;AAC1C,QAAA,QAAQA,iBAAS,IAAI;AAEpB,SAAAC,qBAAA,QAAY,MAAM,IAAI;AAC/B;ACCA,SAAS,YAAY,KAAa,UAAkB;AAClD,QAAM,IAAIC,cAAAA,QAAK,QAAQ,KAAK,QAAQ,GAC9B,SAASC,OAAW,WAAA,CAAC,GACrB,OAAO,SAAS,YAAY,CAAC,IAAI;AAEhC,SAAA,EAAC,QAAQ,KAAI;AACtB;AAEO,SAAS,iBAAiB,KAAyB;AACxD,QAAM,EAAC,KAAK,SAAAC,UAAS,QAAAC,SAAQ,IAAO,IAAA;AAEpC,MAAI,CAACD,SAAS;AAEd,EAAAC,QAAO,IAAI,GAAGC,eAAAA,QAAM,KAAK,IAAI,IAAI,CAAC,IAAIA,eAAM,QAAA,MAAM,IAAI,OAAO,CAAC,EAAE;AAEhE,QAAM,OAAgC,CAAC;AAEnC,MAAI,SACN,KAAK,OAAUA,eAAM,QAAA,OAAO,IAAI,IAAI,IAGlC,IAAI,QACN,KAAK,MAAS,OAAO;AAAA,IACnB,OAAO,QAAQ,IAAI,GAAG,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM,CAACA,uBAAM,KAAK,IAAI,GAAG,SAAS,IAAI,CAAC,CAAC;AAAA,EAAA;AAIpF,WAAS,SAAS,MAAc;AACxB,UAAA,OAAO,YAAY,KAAK,IAAI;AAE7B,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AA,CAClF;AAED,eAAW,OAAO;AAChB,0BAAoBA,QAAO,MAAM,GAAG,GAEpCA,QAAO,IAAI;AAAA,WAEN,KAAK;AACR,QAAA,iBAAiB,GAAG,GAAG;AACnB,YAAA,EAAC,WAAU;AAEjB,iBAAW,OAAO;AAChB,4BAAoBA,QAAO,OAAO,GAAG,GAErCA,QAAO,IAAI;AAAA,IAAA,MAEJ,gBAAe,SACxBA,QAAO,MAAM,IAAI,SAAS,IAAI,OAAO,GAErCA,QAAO,UAEPA,QAAO,MAAM,GAAG,GAAG,EAAE,GAErBA,QAAO;AAGT,YAAQ,KAAK,CAAC;AAAA,EAAA;AAElB;AAEA,SAAS,oBAAoB,KAAmC,KAAsB;AAChF,MAAI,WACN;AAAA,IACE;AAAA,MACE,GAAG,IAAI,UAAU,IAAI,IAAI;AAAA;AAAA,MACzB,GAAG,IAAI,SAAS,IAAI,MAAM,IAAI,SAAS,QAAQ;AAAA;AAAA,MAC/C,QAAQ,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,MAAM;AAAA,IACvE,EAAE,KAAK,EAAE;AAAA,EAGX,IAAA,IAAI,IAAI,UAAU,IAAI,IAAI;AAE9B;AAEA,SAAS,iBAAiB,KAAmC;AAEzD,SAAA,eAAe,SACf,YAAY,OACZ,MAAM,QAAQ,IAAI,MAAM,KACxB,IAAI,OAAO,MAAM,gBAAgB,KACjC,cAAc,OACd,MAAM,QAAQ,IAAI,QAAQ,KAC1B,IAAI,SAAS,MAAM,gBAAgB;AAEvC;AAEA,SAAS,iBAAiB,KAA8B;AACtD,SACE,OAAO,OAAQ,YACf,QAAQ,QACR,UAAU,OACV,OAAO,IAAI,QAAS,YACpB,cAAc,QACb,IAAI,aAAa,QAAQ,OAAO,IAAI,YAAa;AAEtD;;"}
|
|
1
|
+
{"version":3,"file":"check.cjs","sources":["../../src/node/getFilesize.ts","../../src/node/printPackageTree.ts","../../src/node/check.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'\nimport type {BuildContext} from './core/contexts/buildContext'\nimport {fileExists} from './fileExists'\nimport {getFilesize} from './getFilesize'\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 } 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 } 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 esbuild, {type BuildFailure, type Message} from 'esbuild'\nimport {createConsoleSpy} from './consoleSpy'\nimport {loadConfig} from './core/config/loadConfig'\nimport {loadPkgWithReporting} from './core/pkg/loadPkgWithReporting'\nimport {fileExists} from './fileExists'\nimport {createLogger, type Logger} from './logger'\nimport {printPackageTree} from './printPackageTree'\nimport {resolveBuildContext} from './resolveBuildContext'\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\n const config = await loadConfig({cwd})\n const pkg = await loadPkgWithReporting({cwd, logger, strict})\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 // Check if the files are resolved\n const exportPaths: {require: string[]; import: string[]} = {\n require: [],\n import: [],\n }\n\n for (const exp of Object.values(ctx.exports || {})) {\n if (!exp._exported) continue\n if (exp.require) exportPaths.require.push(exp.require)\n if (exp.import) exportPaths.import.push(exp.import)\n }\n\n const external = [\n ...Object.keys(pkg.dependencies || {}),\n ...Object.keys(pkg.devDependencies || {}),\n ]\n\n const consoleSpy = createConsoleSpy()\n\n if (exportPaths.import.length) {\n checkExports(exportPaths.import, {cwd, external, format: 'esm', logger})\n }\n\n if (exportPaths.require.length) {\n checkExports(exportPaths.require, {cwd, external, format: 'cjs', logger})\n }\n\n consoleSpy.restore()\n }\n}\n\nasync function checkExports(\n exportPaths: string[],\n options: {cwd: string; external: string[]; format: 'esm' | 'cjs'; logger: Logger},\n) {\n const {cwd, external, format, logger} = options\n\n const code = exportPaths\n .map((id) => (format ? `import('${id}');` : `require('${id}');`))\n .join('\\n')\n\n try {\n const esbuildResult = await esbuild.build({\n bundle: true,\n external,\n format,\n logLevel: 'silent',\n // otherwise output maps to stdout as we're using stdin\n outfile: '/dev/null',\n platform: 'node',\n stdin: {\n contents: code,\n loader: 'js',\n resolveDir: cwd,\n },\n })\n\n if (esbuildResult.errors.length > 0) {\n for (const msg of esbuildResult.errors) {\n printEsbuildMessage(logger.warn, msg)\n\n logger.log()\n }\n\n process.exit(1)\n }\n\n const esbuildWarnings = esbuildResult.warnings.filter((msg) => {\n !(msg.detail || msg.text).includes(`does not affect esbuild's own target setting`)\n })\n\n for (const msg of esbuildWarnings) {\n printEsbuildMessage(logger.warn, msg)\n\n logger.log()\n }\n } catch (err) {\n if (isEsbuildFailure(err)) {\n const {errors} = err\n\n for (const msg of errors) {\n printEsbuildMessage(logger.error, msg)\n\n logger.log()\n }\n } else if (err instanceof Error) {\n logger.error(err.stack || err.message)\n\n logger.log()\n } else {\n logger.error(`${err}`)\n\n logger.log()\n }\n\n process.exit(1)\n }\n}\n\nfunction printEsbuildMessage(log: (...args: unknown[]) => void, msg: esbuild.Message) {\n if (msg.location) {\n log(\n [\n `${msg.detail || msg.text}\\n`,\n `${msg.location.line} | ${msg.location.lineText}\\n`,\n `in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`,\n ].join(''),\n )\n } else {\n log(msg.detail || msg.text)\n }\n}\n\nfunction isEsbuildFailure(err: unknown): err is BuildFailure {\n return (\n err instanceof Error &&\n 'errors' in err &&\n Array.isArray(err.errors) &&\n err.errors.every(isEsbuildMessage) &&\n 'warnings' in err &&\n Array.isArray(err.warnings) &&\n err.warnings.every(isEsbuildMessage)\n )\n}\n\nfunction isEsbuildMessage(msg: unknown): msg is Message {\n return (\n typeof msg === 'object' &&\n msg !== null &&\n 'text' in msg &&\n typeof msg.text === 'string' &&\n 'location' in msg &&\n (msg.location === null || typeof msg.location === 'object')\n )\n}\n"],"names":["statSync","prettyBytes","path","fileExists","exports","chalk","treeify","createLogger","loadConfig","loadPkgWithReporting","resolveBuildContext","consoleSpy","createConsoleSpy","esbuild"],"mappings":";;;;;;AAGO,SAAS,YAAY,MAAsB;AAC1C,QAAA,QAAQA,iBAAS,IAAI;AAEpB,SAAAC,qBAAA,QAAY,MAAM,IAAI;AAC/B;ACCA,SAAS,YAAY,KAAa,UAAkB;AAClD,QAAM,IAAIC,cAAAA,QAAK,QAAQ,KAAK,QAAQ,GAC9B,SAASC,SAAW,WAAA,CAAC,GACrB,OAAO,SAAS,YAAY,CAAC,IAAI;AAEhC,SAAA,EAAC,QAAQ,KAAI;AACtB;AAEO,SAAS,iBAAiB,KAAyB;AACxD,QAAM,EAAC,KAAK,SAAAC,UAAS,QAAQ,IAAO,IAAA;AAEpC,MAAI,CAACA,SAAS;AAEd,SAAO,IAAI,GAAGC,eAAAA,QAAM,KAAK,IAAI,IAAI,CAAC,IAAIA,eAAM,QAAA,MAAM,IAAI,OAAO,CAAC,EAAE;AAEhE,QAAM,OAAgC,CAAC;AAEnC,MAAI,SACN,KAAK,OAAUA,eAAM,QAAA,OAAO,IAAI,IAAI,IAGlC,IAAI,QACN,KAAK,MAAS,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QACb,IAAI,aAAa,QAAQ,OAAO,IAAI,YAAa;AAEtD;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var path = require("node:path"), node = require("esbuild-register/dist/node"), pkgUp = require("pkg-up"), findConfig = require("find-config"),
|
|
2
|
+
var path = require("node:path"), node = require("esbuild-register/dist/node"), pkgUp = require("pkg-up"), findConfig = require("find-config"), isRecord = require("./isRecord.cjs"), chalk = require("chalk"), zod = require("zod"), fs = require("node:fs/promises"), browserslist = require("browserslist"), config = require("@sanity/browserslist-config"), node_fs = require("node:fs"), ts = require("typescript"), zodValidationError = require("zod-validation-error");
|
|
3
3
|
function _interopDefaultCompat(e) {
|
|
4
4
|
return e && typeof e == "object" && "default" in e ? e : { default: e };
|
|
5
5
|
}
|
|
@@ -16,7 +16,7 @@ function findConfigFile(cwd) {
|
|
|
16
16
|
const pkgPath = path__default.default.dirname(pkgJsonPath);
|
|
17
17
|
for (const fileName of CONFIG_FILE_NAMES) {
|
|
18
18
|
const configPath = path__default.default.resolve(pkgPath, fileName);
|
|
19
|
-
if (
|
|
19
|
+
if (isRecord.fileExists(configPath))
|
|
20
20
|
return configPath;
|
|
21
21
|
}
|
|
22
22
|
}
|
|
@@ -30,16 +30,6 @@ async function loadConfig(options) {
|
|
|
30
30
|
} } : node.register(esbuildOptions), mod = require(configFile);
|
|
31
31
|
return unregister(), mod?.default || mod || void 0;
|
|
32
32
|
}
|
|
33
|
-
function resolveConfigProperty(prop, initialValue) {
|
|
34
|
-
return prop ? typeof prop == "function" ? prop(initialValue) : prop : initialValue;
|
|
35
|
-
}
|
|
36
|
-
const DEFAULT_BROWSERSLIST_QUERY = config__default.default;
|
|
37
|
-
async function loadPkg(options) {
|
|
38
|
-
const { cwd } = options, pkgPath = await pkgUp__default.default({ cwd });
|
|
39
|
-
if (!pkgPath) throw new Error("no package.json found");
|
|
40
|
-
const buf = await fs__default.default.readFile(pkgPath), raw = JSON.parse(buf.toString());
|
|
41
|
-
return logger.validatePkg(raw), raw;
|
|
42
|
-
}
|
|
43
33
|
function assertLast(a, arr) {
|
|
44
34
|
const aIdx = arr.indexOf(a);
|
|
45
35
|
return aIdx === -1 ? !0 : aIdx === arr.length - 1;
|
|
@@ -48,12 +38,85 @@ function assertOrder(a, b, arr) {
|
|
|
48
38
|
const aIdx = arr.indexOf(a), bIdx = arr.indexOf(b);
|
|
49
39
|
return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
|
|
50
40
|
}
|
|
41
|
+
const pkgSchema = zod.z.object({
|
|
42
|
+
type: zod.z.optional(zod.z.enum(["commonjs", "module"])),
|
|
43
|
+
name: zod.z.string(),
|
|
44
|
+
version: zod.z.string(),
|
|
45
|
+
license: zod.z.string(),
|
|
46
|
+
bin: zod.z.optional(zod.z.record(zod.z.string())),
|
|
47
|
+
dependencies: zod.z.optional(zod.z.record(zod.z.string())),
|
|
48
|
+
devDependencies: zod.z.optional(zod.z.record(zod.z.string())),
|
|
49
|
+
peerDependencies: zod.z.optional(zod.z.record(zod.z.string())),
|
|
50
|
+
source: zod.z.optional(zod.z.string()),
|
|
51
|
+
main: zod.z.optional(zod.z.string()),
|
|
52
|
+
browser: zod.z.optional(zod.z.record(zod.z.string())),
|
|
53
|
+
module: zod.z.optional(zod.z.string()),
|
|
54
|
+
types: zod.z.optional(zod.z.string()),
|
|
55
|
+
exports: zod.z.optional(
|
|
56
|
+
zod.z.record(
|
|
57
|
+
zod.z.union([
|
|
58
|
+
zod.z.custom((val) => /^\.\/.*\.json$/.test(val)),
|
|
59
|
+
zod.z.custom((val) => /^\.\/.*\.css$/.test(val)),
|
|
60
|
+
zod.z.object({
|
|
61
|
+
types: zod.z.optional(zod.z.string()),
|
|
62
|
+
source: zod.z.optional(zod.z.string()),
|
|
63
|
+
browser: zod.z.optional(
|
|
64
|
+
zod.z.object({
|
|
65
|
+
source: zod.z.string(),
|
|
66
|
+
import: zod.z.optional(zod.z.string()),
|
|
67
|
+
require: zod.z.optional(zod.z.string())
|
|
68
|
+
})
|
|
69
|
+
),
|
|
70
|
+
node: zod.z.optional(
|
|
71
|
+
zod.z.object({
|
|
72
|
+
source: zod.z.optional(zod.z.string()),
|
|
73
|
+
import: zod.z.optional(zod.z.string()),
|
|
74
|
+
require: zod.z.optional(zod.z.string())
|
|
75
|
+
})
|
|
76
|
+
),
|
|
77
|
+
import: zod.z.optional(zod.z.string()),
|
|
78
|
+
require: zod.z.optional(zod.z.string()),
|
|
79
|
+
default: zod.z.string()
|
|
80
|
+
}),
|
|
81
|
+
zod.z.object({
|
|
82
|
+
types: zod.z.optional(zod.z.string()),
|
|
83
|
+
svelte: zod.z.string(),
|
|
84
|
+
default: zod.z.optional(zod.z.string())
|
|
85
|
+
})
|
|
86
|
+
])
|
|
87
|
+
)
|
|
88
|
+
),
|
|
89
|
+
browserslist: zod.z.optional(zod.z.union([zod.z.string(), zod.z.array(zod.z.string())])),
|
|
90
|
+
sideEffects: zod.z.optional(zod.z.union([zod.z.boolean(), zod.z.array(zod.z.string())])),
|
|
91
|
+
// @TODO type this properly
|
|
92
|
+
typesVersions: zod.z.optional(zod.z.any())
|
|
93
|
+
}), typoMap = /* @__PURE__ */ new Map();
|
|
94
|
+
for (const key of pkgSchema.keyof()._def.values)
|
|
95
|
+
typoMap.set(key.toUpperCase(), key);
|
|
96
|
+
function validatePkg(input) {
|
|
97
|
+
const pkg = pkgSchema.parse(input), invalidKey = Object.keys(input).find((key) => {
|
|
98
|
+
const needle = key.toUpperCase();
|
|
99
|
+
return typoMap.has(needle) ? typoMap.get(needle) !== key : !1;
|
|
100
|
+
});
|
|
101
|
+
if (invalidKey)
|
|
102
|
+
throw new TypeError(
|
|
103
|
+
`
|
|
104
|
+
- package.json: "${invalidKey}" is not a valid key. Did you mean "${typoMap.get(invalidKey.toUpperCase())}"?`
|
|
105
|
+
);
|
|
106
|
+
return pkg;
|
|
107
|
+
}
|
|
108
|
+
async function loadPkg(options) {
|
|
109
|
+
const { cwd } = options, pkgPath = await pkgUp__default.default({ cwd });
|
|
110
|
+
if (!pkgPath) throw new Error("no package.json found");
|
|
111
|
+
const buf = await fs__default.default.readFile(pkgPath), raw = JSON.parse(buf.toString());
|
|
112
|
+
return validatePkg(raw), raw;
|
|
113
|
+
}
|
|
51
114
|
async function loadPkgWithReporting(options) {
|
|
52
|
-
const { cwd, logger
|
|
115
|
+
const { cwd, logger, strict } = options;
|
|
53
116
|
try {
|
|
54
117
|
const pkg = await loadPkg({ cwd });
|
|
55
118
|
let shouldError = !1;
|
|
56
|
-
if (strict && (pkg.type || (shouldError = !0,
|
|
119
|
+
if (strict && (pkg.type || (shouldError = !0, logger.error(
|
|
57
120
|
'the `type` field in `./package.json` must be either "module" or "commonjs")'
|
|
58
121
|
))), pkg.exports) {
|
|
59
122
|
const _exports = Object.entries(pkg.exports);
|
|
@@ -61,23 +124,23 @@ async function loadPkgWithReporting(options) {
|
|
|
61
124
|
if (typeof exp == "string" || "svelte" in exp)
|
|
62
125
|
continue;
|
|
63
126
|
const keys = Object.keys(exp);
|
|
64
|
-
exp.types && (shouldError = !0,
|
|
127
|
+
exp.types && (shouldError = !0, logger.error(
|
|
65
128
|
`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`
|
|
66
|
-
)), exp.module && (shouldError = !0,
|
|
129
|
+
)), exp.module && (shouldError = !0, logger.error(
|
|
67
130
|
`exports["${expPath}"]: the \`module\` condition shouldn't be used as it's not well supported in all bundlers.`
|
|
68
|
-
)), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0,
|
|
131
|
+
)), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0, logger.error(
|
|
69
132
|
`exports["${expPath}"]: the \`node\` property should come before the \`import\` property`
|
|
70
|
-
)), exp.node.module && (shouldError = !0,
|
|
133
|
+
)), exp.node.module && (shouldError = !0, logger.error(
|
|
71
134
|
`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"`
|
|
72
|
-
)), !exp.node.source && exp.node.import && (exp.node.require || exp.require) && (exp.node.import.endsWith(".cjs.js") || exp.node.import.endsWith(".cjs.mjs")) && (shouldError = !0,
|
|
135
|
+
)), !exp.node.source && exp.node.import && (exp.node.require || exp.require) && (exp.node.import.endsWith(".cjs.js") || exp.node.import.endsWith(".cjs.mjs")) && (shouldError = !0, logger.error(
|
|
73
136
|
`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"`
|
|
74
|
-
)), exp.require && exp.node.require && exp.require === exp.node.require ? (shouldError = !0,
|
|
137
|
+
)), exp.require && exp.node.require && exp.require === exp.node.require ? (shouldError = !0, logger.error(
|
|
75
138
|
`exports["${expPath}"]: the \`node.require\` property isn't necessary as it's identical to \`require\``
|
|
76
|
-
)) : exp.require && exp.node.require && !assertOrder("node", "require", keys) && (shouldError = !0,
|
|
139
|
+
)) : exp.require && exp.node.require && !assertOrder("node", "require", keys) && (shouldError = !0, logger.error(
|
|
77
140
|
`exports["${expPath}"]: the \`node\` property should come before the \`require\` property`
|
|
78
|
-
))) : assertOrder("import", "require", keys) ||
|
|
141
|
+
))) : assertOrder("import", "require", keys) || logger.warn(
|
|
79
142
|
`exports["${expPath}"]: the \`import\` property should come before the \`require\` property`
|
|
80
|
-
), assertLast("default", keys) || (shouldError = !0,
|
|
143
|
+
), assertLast("default", keys) || (shouldError = !0, logger.error(
|
|
81
144
|
`exports["${expPath}"]: the \`default\` property should be the last property`
|
|
82
145
|
));
|
|
83
146
|
}
|
|
@@ -87,7 +150,7 @@ async function loadPkgWithReporting(options) {
|
|
|
87
150
|
if (err instanceof zod.ZodError)
|
|
88
151
|
for (const issue of err.issues) {
|
|
89
152
|
if (issue.code === "invalid_type") {
|
|
90
|
-
|
|
153
|
+
logger.error(
|
|
91
154
|
[
|
|
92
155
|
`\`${formatPath(issue.path)}\` `,
|
|
93
156
|
`in \`./package.json\` must be of type ${chalk__default.default.magenta(issue.expected)} `,
|
|
@@ -96,16 +159,65 @@ async function loadPkgWithReporting(options) {
|
|
|
96
159
|
);
|
|
97
160
|
continue;
|
|
98
161
|
}
|
|
99
|
-
|
|
162
|
+
logger.error(issue);
|
|
100
163
|
}
|
|
101
164
|
else
|
|
102
|
-
|
|
165
|
+
logger.error(err);
|
|
103
166
|
process.exit(1);
|
|
104
167
|
}
|
|
105
168
|
}
|
|
106
169
|
function formatPath(segments) {
|
|
107
170
|
return segments.map((s, idx) => idx === 0 ? s : typeof s == "number" ? `[${s}]` : s.startsWith(".") ? `["${s}"]` : `.${s}`).join("");
|
|
108
171
|
}
|
|
172
|
+
function browserslistToEsbuild(browserslistConfig, options = {}) {
|
|
173
|
+
if (!browserslistConfig) {
|
|
174
|
+
const path2 = process.cwd();
|
|
175
|
+
browserslistConfig = browserslist__default.default.loadConfig({ path: path2, ...options });
|
|
176
|
+
}
|
|
177
|
+
const SUPPORTED_ESBUILD_TARGETS = [
|
|
178
|
+
"es",
|
|
179
|
+
"chrome",
|
|
180
|
+
"edge",
|
|
181
|
+
"firefox",
|
|
182
|
+
"ios",
|
|
183
|
+
"node",
|
|
184
|
+
"safari",
|
|
185
|
+
"opera",
|
|
186
|
+
"ie"
|
|
187
|
+
], UNSUPPORTED = ["android 4"], replaces = {
|
|
188
|
+
ios_saf: "ios",
|
|
189
|
+
android: "chrome"
|
|
190
|
+
}, separator = " ";
|
|
191
|
+
return browserslist__default.default(browserslistConfig, options).filter((b) => !UNSUPPORTED.some((u) => b.startsWith(u))).map((b) => b === "safari TP" ? browserslist__default.default("last 1 safari version")[0] : b).map((b) => b.split(separator)).map((b) => (replaces[b[0]] && (b[0] = replaces[b[0]]), b)).map((b) => (b[1].includes("-") && (b[1] = b[1].slice(0, b[1].indexOf("-"))), b)).map((b) => (b[1].endsWith(".0") && (b[1] = b[1].slice(0, -2)), b)).filter((b) => /^\d+(\.\d+)*$/.test(b[1])).filter((b) => SUPPORTED_ESBUILD_TARGETS.includes(b[0])).reduce((acc, b) => {
|
|
192
|
+
const existingIndex = acc.findIndex((br) => br[0] === b[0]);
|
|
193
|
+
return existingIndex !== -1 ? acc[existingIndex][1] = b[1] : acc.push(b), acc;
|
|
194
|
+
}, []).map((b) => b.join(""));
|
|
195
|
+
}
|
|
196
|
+
function resolveConfigProperty(prop, initialValue) {
|
|
197
|
+
return prop ? typeof prop == "function" ? prop(initialValue) : prop : initialValue;
|
|
198
|
+
}
|
|
199
|
+
const DEFAULT_BROWSERSLIST_QUERY = config__default.default;
|
|
200
|
+
function pathContains(containerPath, itemPath) {
|
|
201
|
+
return !path__default.default.relative(containerPath, itemPath).startsWith("..");
|
|
202
|
+
}
|
|
203
|
+
function findCommonDirPath(filePaths) {
|
|
204
|
+
let ret;
|
|
205
|
+
for (const filePath of filePaths) {
|
|
206
|
+
let dirPath = path__default.default.dirname(filePath);
|
|
207
|
+
if (!ret) {
|
|
208
|
+
ret = dirPath;
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
for (; dirPath !== ret && (dirPath = path__default.default.dirname(dirPath), dirPath !== ret); ) {
|
|
212
|
+
if (pathContains(dirPath, ret)) {
|
|
213
|
+
ret = dirPath;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
if (dirPath === ".") return;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return ret;
|
|
220
|
+
}
|
|
109
221
|
const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
|
|
110
222
|
function getTargetPaths(_type, expOrBundle) {
|
|
111
223
|
const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
|
|
@@ -148,8 +260,8 @@ function validateExports(_exports, options) {
|
|
|
148
260
|
return errors;
|
|
149
261
|
}
|
|
150
262
|
function parseExports(options) {
|
|
151
|
-
const { cwd, pkg, strict, strictOptions: strictOptions2, logger
|
|
152
|
-
kind === "warn" ? logger
|
|
263
|
+
const { cwd, pkg, strict, strictOptions: strictOptions2, logger } = options, type = pkg.type || "commonjs", errors = [], report = (kind, message) => {
|
|
264
|
+
kind === "warn" ? logger.warn(message) : errors.push(message);
|
|
153
265
|
};
|
|
154
266
|
if (!pkg.main && strict && strictOptions2.alwaysPackageJsonMain !== "off" && report(strictOptions2.alwaysPackageJsonMain, "package.json: `main` must be declared"), !Array.isArray(pkg.files) && strict && strictOptions2.alwaysPackageJsonFiles !== "off" && report(
|
|
155
267
|
strictOptions2.alwaysPackageJsonFiles,
|
|
@@ -227,7 +339,7 @@ function parseExports(options) {
|
|
|
227
339
|
) : typeof exportEntry != "string" && errors.push(
|
|
228
340
|
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
|
|
229
341
|
);
|
|
230
|
-
else if (!(
|
|
342
|
+
else if (!(isRecord.isRecord(exportEntry) && "svelte" in exportEntry))
|
|
231
343
|
if (isPkgExport(exportEntry)) {
|
|
232
344
|
const exp = {
|
|
233
345
|
_exported: !0,
|
|
@@ -243,7 +355,7 @@ function parseExports(options) {
|
|
|
243
355
|
), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
|
|
244
356
|
'package.json: mismatch between "module" and "exports.import" These must be equal.'
|
|
245
357
|
)), _exports.push(exp);
|
|
246
|
-
} else
|
|
358
|
+
} else isRecord.isRecord(exportEntry) || errors.push("package.json: exports must be an object");
|
|
247
359
|
if (errors.push(...validateExports(_exports, { pkg })), errors.length)
|
|
248
360
|
throw new Error(`
|
|
249
361
|
- ` + errors.join(`
|
|
@@ -251,7 +363,7 @@ function parseExports(options) {
|
|
|
251
363
|
return _exports;
|
|
252
364
|
}
|
|
253
365
|
function isPkgExport(value) {
|
|
254
|
-
return
|
|
366
|
+
return isRecord.isRecord(value) && "source" in value && typeof value.source == "string";
|
|
255
367
|
}
|
|
256
368
|
async function loadTSConfig(options) {
|
|
257
369
|
const { cwd, tsconfigPath } = options, configPath = ts__default.default.findConfigFile(cwd, ts__default.default.sys.fileExists, tsconfigPath);
|
|
@@ -260,51 +372,6 @@ async function loadTSConfig(options) {
|
|
|
260
372
|
const configFile = ts__default.default.readConfigFile(configPath, ts__default.default.sys.readFile);
|
|
261
373
|
return ts__default.default.parseJsonConfigFileContent(configFile.config, ts__default.default.sys, cwd);
|
|
262
374
|
}
|
|
263
|
-
function browserslistToEsbuild(browserslistConfig, options = {}) {
|
|
264
|
-
if (!browserslistConfig) {
|
|
265
|
-
const path2 = process.cwd();
|
|
266
|
-
browserslistConfig = browserslist__default.default.loadConfig({ path: path2, ...options });
|
|
267
|
-
}
|
|
268
|
-
const SUPPORTED_ESBUILD_TARGETS = [
|
|
269
|
-
"es",
|
|
270
|
-
"chrome",
|
|
271
|
-
"edge",
|
|
272
|
-
"firefox",
|
|
273
|
-
"ios",
|
|
274
|
-
"node",
|
|
275
|
-
"safari",
|
|
276
|
-
"opera",
|
|
277
|
-
"ie"
|
|
278
|
-
], UNSUPPORTED = ["android 4"], replaces = {
|
|
279
|
-
ios_saf: "ios",
|
|
280
|
-
android: "chrome"
|
|
281
|
-
}, separator = " ";
|
|
282
|
-
return browserslist__default.default(browserslistConfig, options).filter((b) => !UNSUPPORTED.some((u) => b.startsWith(u))).map((b) => b === "safari TP" ? browserslist__default.default("last 1 safari version")[0] : b).map((b) => b.split(separator)).map((b) => (replaces[b[0]] && (b[0] = replaces[b[0]]), b)).map((b) => (b[1].includes("-") && (b[1] = b[1].slice(0, b[1].indexOf("-"))), b)).map((b) => (b[1].endsWith(".0") && (b[1] = b[1].slice(0, -2)), b)).filter((b) => /^\d+(\.\d+)*$/.test(b[1])).filter((b) => SUPPORTED_ESBUILD_TARGETS.includes(b[0])).reduce((acc, b) => {
|
|
283
|
-
const existingIndex = acc.findIndex((br) => br[0] === b[0]);
|
|
284
|
-
return existingIndex !== -1 ? acc[existingIndex][1] = b[1] : acc.push(b), acc;
|
|
285
|
-
}, []).map((b) => b.join(""));
|
|
286
|
-
}
|
|
287
|
-
function pathContains(containerPath, itemPath) {
|
|
288
|
-
return !path__default.default.relative(containerPath, itemPath).startsWith("..");
|
|
289
|
-
}
|
|
290
|
-
function findCommonDirPath(filePaths) {
|
|
291
|
-
let ret;
|
|
292
|
-
for (const filePath of filePaths) {
|
|
293
|
-
let dirPath = path__default.default.dirname(filePath);
|
|
294
|
-
if (!ret) {
|
|
295
|
-
ret = dirPath;
|
|
296
|
-
continue;
|
|
297
|
-
}
|
|
298
|
-
for (; dirPath !== ret && (dirPath = path__default.default.dirname(dirPath), dirPath !== ret); ) {
|
|
299
|
-
if (pathContains(dirPath, ret)) {
|
|
300
|
-
ret = dirPath;
|
|
301
|
-
break;
|
|
302
|
-
}
|
|
303
|
-
if (dirPath === ".") return;
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
return ret;
|
|
307
|
-
}
|
|
308
375
|
function resolveBrowserTarget(versions) {
|
|
309
376
|
const target = versions.filter(
|
|
310
377
|
(version) => version.startsWith("chrome") || version.startsWith("edge") || version.startsWith("firefox") || version.startsWith("ios") || version.startsWith("safari") || version.startsWith("opera")
|
|
@@ -335,7 +402,7 @@ async function resolveBuildContext(options) {
|
|
|
335
402
|
config: config2,
|
|
336
403
|
cwd,
|
|
337
404
|
emitDeclarationOnly = !1,
|
|
338
|
-
logger
|
|
405
|
+
logger,
|
|
339
406
|
pkg,
|
|
340
407
|
strict,
|
|
341
408
|
tsconfig: tsconfigPath
|
|
@@ -347,7 +414,7 @@ async function resolveBuildContext(options) {
|
|
|
347
414
|
throw new Error(
|
|
348
415
|
'\n- package.json: "browserslist" is missing, set it to `"browserslist": "extends @sanity/browserslist-config"`'
|
|
349
416
|
);
|
|
350
|
-
|
|
417
|
+
logger.warn(
|
|
351
418
|
'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `"browserslist": "extends @sanity/browserslist-config"` to silence this warning.'
|
|
352
419
|
);
|
|
353
420
|
}
|
|
@@ -358,7 +425,7 @@ async function resolveBuildContext(options) {
|
|
|
358
425
|
const msg = "package.json: `sideEffects` is missing, see https://webpack.js.org/guides/tree-shaking/#clarifying-tree-shaking-and-sideeffects for how to define `sideEffects`";
|
|
359
426
|
if (strictOptions2.noImplicitSideEffects === "error")
|
|
360
427
|
throw new Error(msg);
|
|
361
|
-
|
|
428
|
+
logger.warn(msg);
|
|
362
429
|
}
|
|
363
430
|
const nodeTarget = resolveNodeTarget(targetVersions), webTarget = resolveBrowserTarget(targetVersions);
|
|
364
431
|
if (!nodeTarget)
|
|
@@ -374,8 +441,11 @@ async function resolveBuildContext(options) {
|
|
|
374
441
|
pkg,
|
|
375
442
|
strict,
|
|
376
443
|
strictOptions: strictOptions2,
|
|
377
|
-
logger
|
|
378
|
-
}).reduce(
|
|
444
|
+
logger
|
|
445
|
+
}).reduce(
|
|
446
|
+
(acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
|
|
447
|
+
{}
|
|
448
|
+
), exports2 = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
|
|
379
449
|
...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
|
|
380
450
|
...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
|
|
381
451
|
], external = config2 && Array.isArray(config2.external) ? [...parsedExternal, ...config2.external] : resolveConfigProperty(config2?.external, parsedExternal), externalWithTypes = /* @__PURE__ */ new Set([pkg.name, ...external, ...external.map(transformPackageName)]), bundledDependencies = (pkg.devDependencies ? Object.keys(pkg.devDependencies) : []).filter(
|
|
@@ -397,7 +467,7 @@ async function resolveBuildContext(options) {
|
|
|
397
467
|
throw new Error("all output files must be located within the package");
|
|
398
468
|
const configDistPath = config2?.dist ? path__default.default.resolve(cwd, config2.dist) : void 0;
|
|
399
469
|
if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
|
|
400
|
-
throw
|
|
470
|
+
throw logger.log(`did you mean to configure \`dist: './${path__default.default.relative(cwd, commonDistPath)}'\`?`), new Error("all output files must be located with the configured `dist` path");
|
|
401
471
|
const distPath = configDistPath || commonDistPath;
|
|
402
472
|
if (!distPath)
|
|
403
473
|
throw new Error("could not detect `dist` path");
|
|
@@ -410,7 +480,7 @@ async function resolveBuildContext(options) {
|
|
|
410
480
|
external,
|
|
411
481
|
bundledPackages,
|
|
412
482
|
files: [],
|
|
413
|
-
logger
|
|
483
|
+
logger,
|
|
414
484
|
pkg,
|
|
415
485
|
runtime: config2?.runtime ?? "*",
|
|
416
486
|
strict,
|