@sanity/pkg-utils 6.13.3 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks-cjs/build.cjs +6 -58
- package/dist/_chunks-cjs/build.cjs.map +1 -1
- package/dist/_chunks-cjs/check.cjs +3 -3
- package/dist/_chunks-cjs/check.cjs.map +1 -1
- package/dist/_chunks-cjs/consoleSpy.cjs +23 -67
- package/dist/_chunks-cjs/consoleSpy.cjs.map +1 -1
- package/dist/_chunks-cjs/index.cjs +10 -133
- package/dist/_chunks-cjs/index.cjs.map +1 -1
- package/dist/_chunks-cjs/logger.cjs +2 -12
- package/dist/_chunks-cjs/logger.cjs.map +1 -1
- package/dist/_chunks-cjs/watch.cjs +5 -21
- package/dist/_chunks-cjs/watch.cjs.map +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/index.cjs +0 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -48
- package/dist/index.d.ts +12 -48
- package/dist/index.js +40 -283
- package/dist/index.js.map +1 -1
- package/package.json +3 -4
- package/src/node/build.ts +1 -2
- package/src/node/check.ts +1 -2
- package/src/node/core/config/types.ts +11 -16
- package/src/node/core/pkg/loadPkgWithReporting.ts +2 -10
- package/src/node/core/pkg/parseExports.ts +7 -46
- package/src/node/core/pkg/pkgExt.ts +1 -4
- package/src/node/core/pkg/validateExports.ts +0 -1
- package/src/node/core/pkg/validatePkg.ts +7 -17
- package/src/node/resolveBuildContext.ts +0 -3
- package/src/node/resolveBuildTasks.ts +4 -108
- package/src/node/resolveWatchTasks.ts +1 -23
- package/src/node/tasks/dts/createApiExtractorConfig.ts +1 -0
- package/src/node/tasks/dts/getExtractMessagesConfig.ts +5 -1
- package/src/node/tasks/dts/getTargetPaths.ts +0 -13
- package/src/node/tasks/index.ts +1 -3
- package/src/node/tasks/rollup/index.ts +0 -2
- package/src/node/tasks/rollup/resolveRollupConfig.ts +7 -15
- package/src/node/tasks/types.ts +1 -22
- package/src/node/watch.ts +1 -2
- package/src/node/tasks/rollup/rollupLegacyTask.ts +0 -145
- package/src/node/tasks/rollup/rollupReactCompilerTask.ts +0 -140
|
@@ -1,22 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var path = require("node:path"), rimraf = require("rimraf"), consoleSpy = require("./consoleSpy.cjs"), logger = require("./logger.cjs"),
|
|
2
|
+
var path = require("node:path"), rimraf = require("rimraf"), consoleSpy = require("./consoleSpy.cjs"), logger = require("./logger.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
|
}
|
|
6
|
-
var path__default = /* @__PURE__ */ _interopDefaultCompat(path), rimraf__default = /* @__PURE__ */ _interopDefaultCompat(rimraf),
|
|
6
|
+
var path__default = /* @__PURE__ */ _interopDefaultCompat(path), rimraf__default = /* @__PURE__ */ _interopDefaultCompat(rimraf), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk);
|
|
7
7
|
function resolveBuildTasks(ctx) {
|
|
8
|
-
const { config,
|
|
8
|
+
const { config, pkg, target } = ctx, bundles = config?.bundles || [], tasks = [], exports2 = Object.entries(ctx.exports || {}).map(
|
|
9
9
|
([_path, exp]) => ({ _path, ...exp })
|
|
10
10
|
), dtsTask = {
|
|
11
11
|
type: "build:dts",
|
|
12
12
|
entries: []
|
|
13
|
-
}, rollupTasks = {}
|
|
14
|
-
type: "build:react-compiler",
|
|
15
|
-
runtime: "browser",
|
|
16
|
-
format: "esm",
|
|
17
|
-
entries: [],
|
|
18
|
-
target: target.browser
|
|
19
|
-
};
|
|
13
|
+
}, rollupTasks = {};
|
|
20
14
|
function addRollupTaskEntry(format, runtime, entry) {
|
|
21
15
|
const buildId = `${format}:${runtime}`;
|
|
22
16
|
rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
|
|
@@ -28,21 +22,6 @@ function resolveBuildTasks(ctx) {
|
|
|
28
22
|
target: target[runtime]
|
|
29
23
|
};
|
|
30
24
|
}
|
|
31
|
-
function addRollupLegacyTaskEntry(runtime, entry) {
|
|
32
|
-
const buildId = `esm:${runtime}`;
|
|
33
|
-
rollupLegacyTasks[buildId] ? rollupLegacyTasks[buildId].entries.push(entry) : rollupLegacyTasks[buildId] = {
|
|
34
|
-
type: "build:legacy",
|
|
35
|
-
buildId,
|
|
36
|
-
entries: [entry],
|
|
37
|
-
runtime,
|
|
38
|
-
format: "esm",
|
|
39
|
-
// @TODO set a different target here that is compatible with legacy bundlers and testing tools like brownfield jest
|
|
40
|
-
target: target[runtime]
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
function addRollupReactCompilerTaskEntry(entry) {
|
|
44
|
-
rollupReactCompilerTask.entries.push(entry);
|
|
45
|
-
}
|
|
46
25
|
for (const exp of exports2) {
|
|
47
26
|
const importId = path__default.default.join(pkg.name, exp._path);
|
|
48
27
|
exp.source?.endsWith(".ts") && dtsTask.entries.push({
|
|
@@ -105,25 +84,6 @@ function resolveBuildTasks(ctx) {
|
|
|
105
84
|
output
|
|
106
85
|
});
|
|
107
86
|
}
|
|
108
|
-
for (const exp of exports2) {
|
|
109
|
-
const output = exp["react-compiler"]?.default;
|
|
110
|
-
output && addRollupReactCompilerTaskEntry({
|
|
111
|
-
path: exp._path,
|
|
112
|
-
source: exp["react-compiler"]?.source || exp.source,
|
|
113
|
-
output
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
if (rollupReactCompilerTask.entries.length && tasks.push(rollupReactCompilerTask), config?.legacyExports)
|
|
117
|
-
for (const exp of exports2) {
|
|
118
|
-
const runtime = exp.browser?.import ? "browser" : ctx.runtime, output = exp.browser?.import || exp.import;
|
|
119
|
-
if (!output) continue;
|
|
120
|
-
const legacyOutput = output.replace(consoleSpy.fileEnding, consoleSpy.legacyEnding);
|
|
121
|
-
addRollupLegacyTaskEntry(runtime, {
|
|
122
|
-
path: exp._path,
|
|
123
|
-
source: exp.browser?.source || exp.source,
|
|
124
|
-
output: legacyOutput
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
87
|
for (const bundle of bundles) {
|
|
128
88
|
const idx = bundles.indexOf(bundle);
|
|
129
89
|
bundle.require && addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
|
|
@@ -136,19 +96,7 @@ function resolveBuildTasks(ctx) {
|
|
|
136
96
|
output: bundle.import
|
|
137
97
|
});
|
|
138
98
|
}
|
|
139
|
-
|
|
140
|
-
for (const exp of exports2)
|
|
141
|
-
if (exp._exported && exp._path !== ".") {
|
|
142
|
-
const relativeTargetPath = (exp.browser?.import || exp.import || "").replace(consoleSpy.fileEnding, consoleSpy.legacyEnding).replace(/\.[^/.]+$/, "");
|
|
143
|
-
relativeTargetPath && fs__default.default.writeFileSync(
|
|
144
|
-
path__default.default.resolve(cwd, `${exp._path}.js`),
|
|
145
|
-
["// AUTO-GENERATED \u2013 DO NOT EDIT", `export * from '${relativeTargetPath}'`, ""].join(
|
|
146
|
-
`
|
|
147
|
-
`
|
|
148
|
-
)
|
|
149
|
-
);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
99
|
+
tasks.push(...Object.values(rollupTasks));
|
|
152
100
|
}
|
|
153
101
|
return tasks;
|
|
154
102
|
}
|
|
@@ -170,7 +118,7 @@ async function build(options) {
|
|
|
170
118
|
strict = !1,
|
|
171
119
|
tsconfig: tsconfigOption,
|
|
172
120
|
clean = !1
|
|
173
|
-
} = options, logger$1 = logger.createLogger(), config = await consoleSpy.loadConfig({ cwd }),
|
|
121
|
+
} = options, logger$1 = logger.createLogger(), config = await consoleSpy.loadConfig({ cwd }), pkg = await consoleSpy.loadPkgWithReporting({ cwd, logger: logger$1, strict }), tsconfig = tsconfigOption || config?.tsconfig || "tsconfig.json", ctx = await consoleSpy.resolveBuildContext({
|
|
174
122
|
config,
|
|
175
123
|
cwd,
|
|
176
124
|
emitDeclarationOnly,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.cjs","sources":["../../src/node/resolveBuildTasks.ts","../../src/node/spinner.ts","../../src/node/build.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport type {BuildContext, PkgExport, PkgFormat, PkgRuntime} from './core'\nimport type {\n BuildTask,\n DtsTask,\n RollupLegacyTask,\n RollupReactCompilerTask,\n RollupTask,\n RollupTaskEntry,\n} from './tasks'\nimport {fileEnding, getTargetPaths, legacyEnding} from './tasks/dts/getTargetPaths'\n\n/** @internal */\nexport function resolveBuildTasks(ctx: BuildContext): BuildTask[] {\n const {config, cwd, 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 const rollupLegacyTasks: Record<string, RollupLegacyTask> = {}\n const rollupReactCompilerTask: RollupReactCompilerTask = {\n type: 'build:react-compiler',\n runtime: 'browser',\n format: 'esm',\n entries: [],\n target: target.browser,\n }\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 function addRollupLegacyTaskEntry(runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `esm:${runtime}`\n\n if (rollupLegacyTasks[buildId]) {\n rollupLegacyTasks[buildId].entries.push(entry)\n } else {\n rollupLegacyTasks[buildId] = {\n type: 'build:legacy',\n buildId,\n entries: [entry],\n runtime,\n format: 'esm',\n // @TODO set a different target here that is compatible with legacy bundlers and testing tools like brownfield jest\n target: target[runtime],\n }\n }\n }\n\n function addRollupReactCompilerTaskEntry(entry: RollupTaskEntry) {\n rollupReactCompilerTask.entries.push(entry)\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 // @TODO implement this\n // if (exp['react-compiler']?.source?.endsWith('.ts')) {\n // dtsTask.entries.push({\n // importId,\n // exportPath: exp._path,\n // sourcePath: exp['react-compiler'].source,\n // targetPaths: getTargetPaths(pkg.type, exp['react-compiler']),\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 // Parse rollup:react-compiler tasks\n for (const exp of exports) {\n const output = exp['react-compiler']?.default\n\n if (!output) continue\n\n addRollupReactCompilerTaskEntry({\n path: exp._path,\n source: exp['react-compiler']?.source || exp.source,\n output,\n })\n }\n\n // Add react-compiler task\n if (rollupReactCompilerTask.entries.length) {\n tasks.push(rollupReactCompilerTask)\n }\n\n // Create rollup bundles that legacy export files will re-export\n if (config?.legacyExports) {\n for (const exp of exports) {\n const runtime = exp.browser?.import ? 'browser' : ctx.runtime\n const output = exp.browser?.import || exp.import\n\n if (!output) continue\n\n // Change the suffix to what the legacy exports will use\n const legacyOutput = output.replace(fileEnding, legacyEnding)\n\n addRollupLegacyTaskEntry(runtime, {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output: legacyOutput,\n })\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), ...Object.values(rollupLegacyTasks))\n\n // Write legacy exports files\n if (config?.legacyExports) {\n for (const exp of exports) {\n if (exp._exported && exp._path !== '.') {\n const output = (exp.browser?.import || exp.import || '').replace(fileEnding, legacyEnding)\n const relativeTargetPath = output.replace(/\\.[^/.]+$/, '')\n\n if (relativeTargetPath) {\n fs.writeFileSync(\n path.resolve(cwd, `${exp._path}.js`),\n ['// AUTO-GENERATED – DO NOT EDIT', `export * from '${relativeTargetPath}'`, ''].join(\n '\\n',\n ),\n )\n }\n }\n }\n }\n }\n\n return tasks\n}\n","/* eslint-disable no-console */\n\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'\n\nimport rimraf from 'rimraf'\n\nimport {loadConfig, loadPkgWithReporting} from './core'\nimport {createLogger} from './logger'\nimport {resolveBuildContext} from './resolveBuildContext'\nimport {resolveBuildTasks} from './resolveBuildTasks'\nimport {createSpinner} from './spinner'\nimport {type BuildTask, buildTaskHandlers, 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 legacyExports = config?.legacyExports ?? false\n const pkg = await loadPkgWithReporting({cwd, logger, strict, legacyExports})\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","fileEnding","legacyEnding","fs","chalk","logger","createLogger","loadConfig","loadPkgWithReporting","resolveBuildContext","rimraf","buildTaskHandlers"],"mappings":";;;;;;AAeO,SAAS,kBAAkB,KAAgC;AAC1D,QAAA,EAAC,QAAQ,KAAK,KAAK,WAAU,KAE7B,UAAU,QAAQ,WAAW,IAE7B,QAAqB,CAAA,GAErBA,WAAU,OAAO,QAAQ,IAAI,WAAW,CAAE,CAAA,EAAE;AAAA,IAChD,CAAC,CAAC,OAAO,GAAG,OAAO,EAAC,OAAO,GAAG,IAAG;AAAA,KAG7B,UAAmB;AAAA,IACvB,MAAM;AAAA,IACN,SAAS,CAAA;AAAA,KAGL,cAA0C,IAC1C,oBAAsD,CAAA,GACtD,0BAAmD;AAAA,IACvD,MAAM;AAAA,IACN,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,SAAS,CAAC;AAAA,IACV,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AA,IACA;AAAA,IAAA,QACAJ;AAAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAEG,YACFA,SAAO;AAAA,IACL,oCAAoCN,cAAAA,QAAK,SAAS,KAAK,IAAI,QAAQ,CAAC;AAAA,EAEtE,GAAA,MAAMW,gBAAO,QAAA,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'\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","/* eslint-disable no-console */\n\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'\n\nimport rimraf from 'rimraf'\n\nimport {loadConfig, loadPkgWithReporting} from './core'\nimport {createLogger} from './logger'\nimport {resolveBuildContext} from './resolveBuildContext'\nimport {resolveBuildTasks} from './resolveBuildTasks'\nimport {createSpinner} from './spinner'\nimport {type BuildTask, buildTaskHandlers, 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","buildTaskHandl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tD,WAAW,kBAAkB,QAAQ,YAAY,iBAEjD,MAAM,MAAMI,WAAAA,oBAAoB;AAAA,IACpC;AAAA,IACA;AAAA,IACA;AAAA,IAAA,QACAJ;AAAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAEG,YACFA,SAAO;AAAA,IACL,oCAAoCH,cAAAA,QAAK,SAAS,KAAK,IAAI,QAAQ,CAAC;AAAA,EAEtE,GAAA,MAAMQ,gBAAO,QAAA,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,11 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var path = require("node:path"), esbuild = require("esbuild"), consoleSpy = require("./consoleSpy.cjs"), logger = require("./logger.cjs"), chalk = require("chalk"), treeify = require("treeify"),
|
|
2
|
+
var path = require("node:path"), esbuild = require("esbuild"), consoleSpy = require("./consoleSpy.cjs"), logger = require("./logger.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
|
}
|
|
6
6
|
var path__default = /* @__PURE__ */ _interopDefaultCompat(path), esbuild__default = /* @__PURE__ */ _interopDefaultCompat(esbuild), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), treeify__default = /* @__PURE__ */ _interopDefaultCompat(treeify), prettyBytes__default = /* @__PURE__ */ _interopDefaultCompat(prettyBytes);
|
|
7
7
|
function getFilesize(file) {
|
|
8
|
-
const stats =
|
|
8
|
+
const stats = node_fs.statSync(file);
|
|
9
9
|
return prettyBytes__default.default(stats.size);
|
|
10
10
|
}
|
|
11
11
|
function getFileInfo(cwd, filePath) {
|
|
@@ -39,7 +39,7 @@ function printPackageTree(ctx) {
|
|
|
39
39
|
), logger2.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$1 = logger.createLogger(), config = await consoleSpy.loadConfig({ cwd }),
|
|
42
|
+
const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger$1 = logger.createLogger(), config = await consoleSpy.loadConfig({ cwd }), pkg = await consoleSpy.loadPkgWithReporting({ cwd, logger: logger$1, strict }), tsconfig = tsconfigOption || config?.tsconfig || "tsconfig.json", ctx = await consoleSpy.resolveBuildContext({ config, cwd, logger: logger$1, pkg, strict, tsconfig });
|
|
43
43
|
if (printPackageTree(ctx), strict) {
|
|
44
44
|
const missingFiles = [];
|
|
45
45
|
for (const [, exp] of Object.entries(ctx.exports || {}))
|
|
@@ -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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 legacyExports = config?.legacyExports ?? false\n const pkg = await loadPkgWithReporting({cwd, logger, strict, legacyExports})\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,YAAS,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;AAGhE,QAAM,OAAgC,CAAC;AAEnC,MAAI,SACN,KAAK,OAAUA,eAAM,QAAA,OAAO,IAAI,IAAI,IAGlC,IAAI,QACN,KAAK,MAAS,OAAO;A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BAAiB,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'\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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,U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AI,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,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"), logger = require("./logger.cjs"), chalk = require("chalk"), zod = require("zod"), fs = require("node:fs/promises"), browserslist = require("browserslist"), config = require("@sanity/browserslist-config"),
|
|
2
|
+
var path = require("node:path"), node = require("esbuild-register/dist/node"), pkgUp = require("pkg-up"), findConfig = require("find-config"), logger = require("./logger.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
|
}
|
|
@@ -49,13 +49,11 @@ function assertOrder(a, b, arr) {
|
|
|
49
49
|
return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
|
|
50
50
|
}
|
|
51
51
|
async function loadPkgWithReporting(options) {
|
|
52
|
-
const { cwd, logger: logger2, strict
|
|
52
|
+
const { cwd, logger: logger2, strict } = options;
|
|
53
53
|
try {
|
|
54
54
|
const pkg = await loadPkg({ cwd });
|
|
55
55
|
let shouldError = !1;
|
|
56
|
-
if (strict && (
|
|
57
|
-
'the `type` field in `./package.json` shouldn\'t be "commonjs" when `legacyExports` is set to true)'
|
|
58
|
-
)), !legacyExports && !pkg.type && (shouldError = !0, logger2.error(
|
|
56
|
+
if (strict && (pkg.type || (shouldError = !0, logger2.error(
|
|
59
57
|
'the `type` field in `./package.json` must be either "module" or "commonjs")'
|
|
60
58
|
))), pkg.exports) {
|
|
61
59
|
const _exports = Object.entries(pkg.exports);
|
|
@@ -108,7 +106,7 @@ async function loadPkgWithReporting(options) {
|
|
|
108
106
|
function formatPath(segments) {
|
|
109
107
|
return segments.map((s, idx) => idx === 0 ? s : typeof s == "number" ? `[${s}]` : s.startsWith(".") ? `["${s}"]` : `.${s}`).join("");
|
|
110
108
|
}
|
|
111
|
-
const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js",
|
|
109
|
+
const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
|
|
112
110
|
function getTargetPaths(_type, expOrBundle) {
|
|
113
111
|
const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
|
|
114
112
|
return expOrBundle?.import && set.add(expOrBundle.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)), expOrBundle?.require && set.add(expOrBundle.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)), isPkgExport$1(expOrBundle) && (expOrBundle.browser?.source || (expOrBundle.browser?.import && set.add(
|
|
@@ -122,12 +120,7 @@ function getTargetPaths(_type, expOrBundle) {
|
|
|
122
120
|
expOrBundle.node.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
|
|
123
121
|
), expOrBundle.node?.require && set.add(
|
|
124
122
|
expOrBundle.node.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)
|
|
125
|
-
)),
|
|
126
|
-
expOrBundle["react-compiler"].default.replace(
|
|
127
|
-
fileEnding,
|
|
128
|
-
type === "module" ? dtsEnding : mtsEnding
|
|
129
|
-
)
|
|
130
|
-
)), Array.from(set);
|
|
123
|
+
))), Array.from(set);
|
|
131
124
|
}
|
|
132
125
|
function isPkgExport$1(exp) {
|
|
133
126
|
return exp?.browser || exp?.node || exp?.default;
|
|
@@ -142,9 +135,7 @@ const pkgExtMap = {
|
|
|
142
135
|
module: {
|
|
143
136
|
commonjs: cjsEnding,
|
|
144
137
|
esm: defaultEnding
|
|
145
|
-
}
|
|
146
|
-
// package.config.legacyExports: true
|
|
147
|
-
legacy: legacyEnding
|
|
138
|
+
}
|
|
148
139
|
};
|
|
149
140
|
function validateExports(_exports, options) {
|
|
150
141
|
const { pkg } = options, type = pkg.type || "commonjs", ext = pkgExtMap[type], errors = [];
|
|
@@ -157,7 +148,7 @@ function validateExports(_exports, options) {
|
|
|
157
148
|
return errors;
|
|
158
149
|
}
|
|
159
150
|
function parseExports(options) {
|
|
160
|
-
const { cwd, pkg, strict, strictOptions: strictOptions2,
|
|
151
|
+
const { cwd, pkg, strict, strictOptions: strictOptions2, logger: logger$1 } = options, type = pkg.type || "commonjs", errors = [], report = (kind, message) => {
|
|
161
152
|
kind === "warn" ? logger$1.warn(message) : errors.push(message);
|
|
162
153
|
};
|
|
163
154
|
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(
|
|
@@ -172,27 +163,13 @@ function parseExports(options) {
|
|
|
172
163
|
const extMap = pkgExtMap[type], importExport = pkg.main.replace(fileEnding, extMap.esm), requireExport = pkg.main.replace(fileEnding, extMap.commonjs), defaultExport = pkg.main.replace(fileEnding, defaultEnding), maybeBrowserCondition = [];
|
|
173
164
|
if (pkg.browser) {
|
|
174
165
|
const browserConditions = [];
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
)
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
);
|
|
183
|
-
else if (legacyExports) {
|
|
184
|
-
const browserImport = pkg.main.replace(fileEnding, `.browser${extMap.esm}`);
|
|
185
|
-
browserConditions.push(` "import": ${JSON.stringify(browserImport)}`);
|
|
186
|
-
}
|
|
187
|
-
if (pkg.browser?.[pkg.main])
|
|
188
|
-
browserConditions.push(
|
|
189
|
-
` "require": ${JSON.stringify(pkg.browser[pkg.main].replace(fileEnding, extMap.commonjs))}`
|
|
190
|
-
);
|
|
191
|
-
else if (legacyExports) {
|
|
192
|
-
const browserRequire = pkg.main.replace(fileEnding, `.browser${extMap.commonjs}`);
|
|
193
|
-
browserConditions.push(` "require": ${JSON.stringify(browserRequire)}`);
|
|
194
|
-
}
|
|
195
|
-
browserConditions.length && maybeBrowserCondition.push(
|
|
166
|
+
pkg.module && pkg.browser?.[pkg.module] ? browserConditions.push(
|
|
167
|
+
` "import": ${JSON.stringify(pkg.browser[pkg.module].replace(fileEnding, extMap.esm))}`
|
|
168
|
+
) : pkg.browser?.[pkg.main] && browserConditions.push(
|
|
169
|
+
` "import": ${JSON.stringify(pkg.browser?.[pkg.main].replace(fileEnding, extMap.esm))}`
|
|
170
|
+
), pkg.browser?.[pkg.main] && browserConditions.push(
|
|
171
|
+
` "require": ${JSON.stringify(pkg.browser[pkg.main].replace(fileEnding, extMap.commonjs))}`
|
|
172
|
+
), browserConditions.length && maybeBrowserCondition.push(
|
|
196
173
|
' "browser": {',
|
|
197
174
|
` "source": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,
|
|
198
175
|
...browserConditions,
|
|
@@ -207,9 +184,8 @@ function parseExports(options) {
|
|
|
207
184
|
` "source": ${JSON.stringify(pkg.source)},`,
|
|
208
185
|
// If browser conditions are detected then add them to the suggestion
|
|
209
186
|
...maybeBrowserCondition.length > 0 ? maybeBrowserCondition : [],
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
(legacyExports || type === "module") && ` "require": ${JSON.stringify(requireExport)},`,
|
|
187
|
+
type === "commonjs" && ` "import": ${JSON.stringify(importExport)},`,
|
|
188
|
+
type === "module" && ` "require": ${JSON.stringify(requireExport)},`,
|
|
213
189
|
` "default": ${JSON.stringify(defaultExport)}`,
|
|
214
190
|
" },",
|
|
215
191
|
' "./package.json": "./package.json"',
|
|
@@ -246,7 +222,7 @@ function parseExports(options) {
|
|
|
246
222
|
if (exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json"))
|
|
247
223
|
exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push('package.json: `exports["./package.json"]` must be "./package.json".');
|
|
248
224
|
else if (exportPath.endsWith(".css"))
|
|
249
|
-
typeof exportEntry == "string" && !
|
|
225
|
+
typeof exportEntry == "string" && !node_fs.existsSync(path.resolve(cwd, exportEntry)) ? errors.push(
|
|
250
226
|
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`
|
|
251
227
|
) : typeof exportEntry != "string" && errors.push(
|
|
252
228
|
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
|
|
@@ -260,28 +236,13 @@ function parseExports(options) {
|
|
|
260
236
|
};
|
|
261
237
|
if (!exp.default) {
|
|
262
238
|
const fallback = type === "module" ? exp.import : exp.require;
|
|
263
|
-
fallback && (exp.default = fallback)
|
|
264
|
-
`package.json - \`exports["${exp._path}"].default\` should be set to "${fallback}" when "legacyExports" is true`
|
|
265
|
-
) : errors.push(
|
|
266
|
-
`package.json - \`exports["${exp._path}"].default\` should be specified when "legacyExports" is true`
|
|
267
|
-
));
|
|
239
|
+
fallback && (exp.default = fallback);
|
|
268
240
|
}
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
/(\.esm)?\.[mc]?js$/,
|
|
275
|
-
legacyEnding
|
|
276
|
-
);
|
|
277
|
-
indexLegacyExport !== pkg.module && errors.push(
|
|
278
|
-
`package.json: "module" should be "${indexLegacyExport}" when "legacyExports" is true`
|
|
279
|
-
);
|
|
280
|
-
} else
|
|
281
|
-
exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
|
|
282
|
-
'package.json: mismatch between "module" and "exports.import" These must be equal.'
|
|
283
|
-
);
|
|
284
|
-
_exports.push(exp);
|
|
241
|
+
!exp.require && type === "commonjs" && exp.default && (exp.require = exp.default), !exp.import && type === "module" && exp.default && (exp.import = exp.default), exportPath === "." && (exportEntry.require && pkg.main && exportEntry.require !== pkg.main && errors.push(
|
|
242
|
+
'package.json: mismatch between "main" and "exports.require". These must be equal.'
|
|
243
|
+
), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
|
|
244
|
+
'package.json: mismatch between "module" and "exports.import" These must be equal.'
|
|
245
|
+
)), _exports.push(exp);
|
|
285
246
|
} else logger.isRecord(exportEntry) || errors.push("package.json: exports must be an object");
|
|
286
247
|
if (errors.push(...validateExports(_exports, { pkg })), errors.length)
|
|
287
248
|
throw new Error(`
|
|
@@ -412,7 +373,6 @@ async function resolveBuildContext(options) {
|
|
|
412
373
|
cwd,
|
|
413
374
|
pkg,
|
|
414
375
|
strict,
|
|
415
|
-
legacyExports: config2?.legacyExports ?? !1,
|
|
416
376
|
strictOptions: strictOptions2,
|
|
417
377
|
logger: logger2
|
|
418
378
|
}).reduce((acc, x) => {
|
|
@@ -433,8 +393,6 @@ async function resolveBuildContext(options) {
|
|
|
433
393
|
exportEntry.browser?.require,
|
|
434
394
|
exportEntry.node?.source && exportEntry.node.import,
|
|
435
395
|
exportEntry.node?.source && exportEntry.node.require
|
|
436
|
-
// @TODO implement this
|
|
437
|
-
// exportEntry['react-compiler']?.source && exportEntry['react-compiler']?.default,
|
|
438
396
|
].filter(Boolean)).map((p) => path__default.default.resolve(cwd, p)), commonDistPath = findCommonDirPath(outputPaths);
|
|
439
397
|
if (commonDistPath === cwd)
|
|
440
398
|
throw new Error(
|
|
@@ -492,9 +450,7 @@ function createConsoleSpy(options) {
|
|
|
492
450
|
}
|
|
493
451
|
exports.DEFAULT_BROWSERSLIST_QUERY = DEFAULT_BROWSERSLIST_QUERY;
|
|
494
452
|
exports.createConsoleSpy = createConsoleSpy;
|
|
495
|
-
exports.fileEnding = fileEnding;
|
|
496
453
|
exports.getTargetPaths = getTargetPaths;
|
|
497
|
-
exports.legacyEnding = legacyEnding;
|
|
498
454
|
exports.loadConfig = loadConfig;
|
|
499
455
|
exports.loadPkg = loadPkg;
|
|
500
456
|
exports.loadPkgWithReporting = loadPkgWithReporting;
|