@sanity/pkg-utils 7.2.10-canary.1 → 7.2.10-canary.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks-cjs/index.cjs +10 -106
- package/dist/_chunks-cjs/index.cjs.map +1 -1
- package/dist/_chunks-cjs/resolveRolldownConfig.cjs +79 -0
- package/dist/_chunks-cjs/resolveRolldownConfig.cjs.map +1 -0
- package/dist/_chunks-es/index.js +2311 -0
- package/dist/_chunks-es/index.js.map +1 -0
- package/dist/_chunks-es/resolveRolldownConfig.js +78 -0
- package/dist/_chunks-es/resolveRolldownConfig.js.map +1 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.d.cts +1 -1
- package/dist/index.d.cts +487 -408
- package/dist/index.d.ts +487 -408
- package/dist/index.js +1 -2390
- package/dist/index.js.map +1 -1
- package/package.json +7 -8
- package/src/cli/buildAction.ts +0 -21
- package/src/cli/checkAction.ts +0 -14
- package/src/cli/handleError.ts +0 -11
- package/src/cli/index.ts +0 -65
- package/src/cli/initAction.ts +0 -13
- package/src/cli/watchAction.ts +0 -14
- package/src/global.ts +0 -5
- package/src/node/__snapshots__/strict.test.ts.snap +0 -154
- package/src/node/build.ts +0 -100
- package/src/node/check.ts +0 -188
- package/src/node/consoleSpy.ts +0 -39
- package/src/node/core/config/defineConfig.ts +0 -6
- package/src/node/core/config/findConfigFile.ts +0 -31
- package/src/node/core/config/index.ts +0 -4
- package/src/node/core/config/loadConfig.ts +0 -37
- package/src/node/core/config/resolveConfigProperty.ts +0 -15
- package/src/node/core/config/types.ts +0 -315
- package/src/node/core/contexts/buildContext.ts +0 -32
- package/src/node/core/contexts/index.ts +0 -1
- package/src/node/core/defaults.ts +0 -4
- package/src/node/core/findCommonPath.ts +0 -35
- package/src/node/core/isRecord.ts +0 -4
- package/src/node/core/pkg/helpers.ts +0 -36
- package/src/node/core/pkg/index.ts +0 -5
- package/src/node/core/pkg/loadPkg.ts +0 -21
- package/src/node/core/pkg/loadPkgWithReporting.ts +0 -154
- package/src/node/core/pkg/parseExports.ts +0 -233
- package/src/node/core/pkg/pkgExt.ts +0 -22
- package/src/node/core/pkg/types.ts +0 -60
- package/src/node/core/pkg/validateExports.ts +0 -30
- package/src/node/core/pkg/validatePkg.ts +0 -82
- package/src/node/core/template/createFromTemplate.ts +0 -84
- package/src/node/core/template/define.ts +0 -6
- package/src/node/core/template/index.ts +0 -3
- package/src/node/core/template/types.ts +0 -45
- package/src/node/core/ts/index.ts +0 -1
- package/src/node/core/ts/loadTSConfig.ts +0 -19
- package/src/node/fileExists.ts +0 -12
- package/src/node/getFilesize.ts +0 -8
- package/src/node/globFiles.ts +0 -6
- package/src/node/index.ts +0 -48
- package/src/node/init.ts +0 -54
- package/src/node/isEmptyDirectory.ts +0 -5
- package/src/node/logger.ts +0 -32
- package/src/node/printExtractMessages.ts +0 -59
- package/src/node/printPackageTree.ts +0 -95
- package/src/node/resolveBrowserTarget.ts +0 -17
- package/src/node/resolveBuildContext.ts +0 -202
- package/src/node/resolveBuildTasks.ts +0 -199
- package/src/node/resolveNodeTarget.ts +0 -9
- package/src/node/resolveWatchTasks.ts +0 -132
- package/src/node/spinner.ts +0 -17
- package/src/node/strict.test-d.ts +0 -6
- package/src/node/strict.ts +0 -84
- package/src/node/tasks/dts/DtsError.ts +0 -11
- package/src/node/tasks/dts/buildTypes.ts +0 -42
- package/src/node/tasks/dts/createApiExtractorConfig.ts +0 -67
- package/src/node/tasks/dts/createTSDocConfig.ts +0 -53
- package/src/node/tasks/dts/doExtract.ts +0 -80
- package/src/node/tasks/dts/dtsTask.ts +0 -50
- package/src/node/tasks/dts/dtsWatchTask.ts +0 -165
- package/src/node/tasks/dts/extractModuleBlocks.ts +0 -45
- package/src/node/tasks/dts/extractTypes.ts +0 -128
- package/src/node/tasks/dts/getExtractMessagesConfig.ts +0 -109
- package/src/node/tasks/dts/getTargetPaths.ts +0 -72
- package/src/node/tasks/dts/printDiagnostic.ts +0 -42
- package/src/node/tasks/dts/types.ts +0 -30
- package/src/node/tasks/index.ts +0 -19
- package/src/node/tasks/rolldown/resolveRolldownConfig.ts +0 -208
- package/src/node/tasks/rolldown/rolldownDtsTask.ts +0 -155
- package/src/node/tasks/rollup/resolveRollupConfig.ts +0 -264
- package/src/node/tasks/rollup/rollupTask.ts +0 -154
- package/src/node/tasks/rollup/rollupWatchTask.ts +0 -77
- package/src/node/tasks/types.ts +0 -69
- package/src/node/templates/default/index.ts +0 -1
- package/src/node/templates/default/template.ts +0 -547
- package/src/node/templates/index.ts +0 -1
- package/src/node/watch.ts +0 -66
- package/src/node/watchConfigFiles.ts +0 -53
- package/src/node/watchFiles.ts +0 -31
package/dist/index.js
CHANGED
|
@@ -1,2393 +1,4 @@
|
|
|
1
|
-
import
|
|
2
|
-
import * as rimraf from "rimraf";
|
|
3
|
-
import { rimraf as rimraf$1 } from "rimraf";
|
|
4
|
-
import { register } from "esbuild-register/dist/node";
|
|
5
|
-
import pkgUp from "pkg-up";
|
|
6
|
-
import findConfig from "find-config";
|
|
7
|
-
import { statSync, existsSync } from "node:fs";
|
|
8
|
-
import chalk from "chalk";
|
|
9
|
-
import { z, ZodError } from "zod";
|
|
10
|
-
import fs, { readFile, writeFile, readdir, lstat } from "node:fs/promises";
|
|
11
|
-
import browserslist from "browserslist";
|
|
12
|
-
import config$1 from "@sanity/browserslist-config";
|
|
13
|
-
import ts from "typescript";
|
|
14
|
-
import { errorMap } from "zod-validation-error";
|
|
15
|
-
import { Observable, from, switchMap } from "rxjs";
|
|
16
|
-
import { ExtractorConfig, Extractor } from "@microsoft/api-extractor";
|
|
17
|
-
import { mkdirp } from "mkdirp";
|
|
18
|
-
import * as prettier from "prettier";
|
|
19
|
-
import { format } from "prettier";
|
|
20
|
-
import { TSDocConfigFile } from "@microsoft/tsdoc-config";
|
|
21
|
-
import { parse } from "jsonc-parser";
|
|
22
|
-
import { parse as parse$1, print } from "recast";
|
|
23
|
-
import typeScriptParser from "recast/parsers/typescript.js";
|
|
24
|
-
import { rolldown } from "rolldown";
|
|
25
|
-
import { optimizeLodashImports } from "@optimize-lodash/rollup-plugin";
|
|
26
|
-
import { getBabelOutputPlugin, babel } from "@rollup/plugin-babel";
|
|
27
|
-
import terser from "@rollup/plugin-terser";
|
|
28
|
-
import { dts } from "rolldown-plugin-dts";
|
|
29
|
-
import esbuild from "rollup-plugin-esbuild";
|
|
30
|
-
import { rollup, watch as watch$1 } from "rollup";
|
|
31
|
-
import alias from "@rollup/plugin-alias";
|
|
32
|
-
import commonjs from "@rollup/plugin-commonjs";
|
|
33
|
-
import json from "@rollup/plugin-json";
|
|
34
|
-
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
|
35
|
-
import replace from "@rollup/plugin-replace";
|
|
36
|
-
import esbuild$1 from "esbuild";
|
|
37
|
-
import treeify from "treeify";
|
|
38
|
-
import prettyBytes from "pretty-bytes";
|
|
39
|
-
import prompts from "prompts";
|
|
40
|
-
import { execSync } from "node:child_process";
|
|
41
|
-
import getLatestVersion from "get-latest-version";
|
|
42
|
-
import gitUrlParse from "git-url-parse";
|
|
43
|
-
import { outdent } from "outdent";
|
|
44
|
-
import { scan, startWith, distinctUntilChanged } from "rxjs/operators";
|
|
45
|
-
import globby from "globby";
|
|
46
|
-
import * as chokidar from "chokidar";
|
|
47
|
-
function fileExists(filePath) {
|
|
48
|
-
try {
|
|
49
|
-
return statSync(filePath), !0;
|
|
50
|
-
} catch {
|
|
51
|
-
return !1;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
const CONFIG_FILE_NAMES = [
|
|
55
|
-
"package.config.ts",
|
|
56
|
-
"package.config.js",
|
|
57
|
-
"package.config.cjs",
|
|
58
|
-
"package.config.mjs"
|
|
59
|
-
];
|
|
60
|
-
function findConfigFile(cwd) {
|
|
61
|
-
const pkgJsonPath = findConfig("package.json", { cwd });
|
|
62
|
-
if (!pkgJsonPath) return;
|
|
63
|
-
const pkgPath = path.dirname(pkgJsonPath);
|
|
64
|
-
for (const fileName of CONFIG_FILE_NAMES) {
|
|
65
|
-
const configPath = path.resolve(pkgPath, fileName);
|
|
66
|
-
if (fileExists(configPath))
|
|
67
|
-
return configPath;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
async function loadConfig(options) {
|
|
71
|
-
const { cwd } = options, pkgPath = await pkgUp({ cwd });
|
|
72
|
-
if (!pkgPath) return;
|
|
73
|
-
const root = path.dirname(pkgPath), configFile = await findConfigFile(root);
|
|
74
|
-
if (!configFile || !configFile.startsWith(cwd))
|
|
75
|
-
return;
|
|
76
|
-
const esbuildOptions = { extensions: [".js", ".mjs", ".ts"] }, { unregister } = globalThis.__DEV__ ? { unregister: () => {
|
|
77
|
-
} } : register(esbuildOptions), mod = require(configFile);
|
|
78
|
-
return unregister(), mod?.default || mod || void 0;
|
|
79
|
-
}
|
|
80
|
-
function assertLast(a, arr) {
|
|
81
|
-
const aIdx = arr.indexOf(a);
|
|
82
|
-
return aIdx === -1 ? !0 : aIdx === arr.length - 1;
|
|
83
|
-
}
|
|
84
|
-
function assertOrder(a, b, arr) {
|
|
85
|
-
const aIdx = arr.indexOf(a), bIdx = arr.indexOf(b);
|
|
86
|
-
return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
|
|
87
|
-
}
|
|
88
|
-
const pkgSchema = z.object({
|
|
89
|
-
type: z.optional(z.enum(["commonjs", "module"])),
|
|
90
|
-
name: z.string(),
|
|
91
|
-
version: z.string(),
|
|
92
|
-
license: z.string(),
|
|
93
|
-
bin: z.optional(z.record(z.string())),
|
|
94
|
-
dependencies: z.optional(z.record(z.string())),
|
|
95
|
-
devDependencies: z.optional(z.record(z.string())),
|
|
96
|
-
peerDependencies: z.optional(z.record(z.string())),
|
|
97
|
-
source: z.optional(z.string()),
|
|
98
|
-
main: z.optional(z.string()),
|
|
99
|
-
browser: z.optional(z.record(z.string())),
|
|
100
|
-
module: z.optional(z.string()),
|
|
101
|
-
types: z.optional(z.string()),
|
|
102
|
-
exports: z.optional(
|
|
103
|
-
z.record(
|
|
104
|
-
z.union([
|
|
105
|
-
z.custom((val) => /^\.\/.*\.json$/.test(val)),
|
|
106
|
-
z.custom((val) => /^\.\/.*\.css$/.test(val)),
|
|
107
|
-
z.object({
|
|
108
|
-
types: z.optional(z.string()),
|
|
109
|
-
source: z.optional(z.string()),
|
|
110
|
-
browser: z.optional(
|
|
111
|
-
z.object({
|
|
112
|
-
source: z.string(),
|
|
113
|
-
import: z.optional(z.string()),
|
|
114
|
-
require: z.optional(z.string())
|
|
115
|
-
})
|
|
116
|
-
),
|
|
117
|
-
node: z.optional(
|
|
118
|
-
z.object({
|
|
119
|
-
source: z.optional(z.string()),
|
|
120
|
-
import: z.optional(z.string()),
|
|
121
|
-
require: z.optional(z.string())
|
|
122
|
-
})
|
|
123
|
-
),
|
|
124
|
-
import: z.optional(z.string()),
|
|
125
|
-
require: z.optional(z.string()),
|
|
126
|
-
default: z.string()
|
|
127
|
-
}),
|
|
128
|
-
z.object({
|
|
129
|
-
types: z.optional(z.string()),
|
|
130
|
-
svelte: z.string(),
|
|
131
|
-
default: z.optional(z.string())
|
|
132
|
-
})
|
|
133
|
-
])
|
|
134
|
-
)
|
|
135
|
-
),
|
|
136
|
-
browserslist: z.optional(z.union([z.string(), z.array(z.string())])),
|
|
137
|
-
sideEffects: z.optional(z.union([z.boolean(), z.array(z.string())])),
|
|
138
|
-
// @TODO type this properly
|
|
139
|
-
typesVersions: z.optional(z.any())
|
|
140
|
-
}), typoMap = /* @__PURE__ */ new Map();
|
|
141
|
-
for (const key of pkgSchema.keyof()._def.values)
|
|
142
|
-
typoMap.set(key.toUpperCase(), key);
|
|
143
|
-
function validatePkg(input) {
|
|
144
|
-
const pkg = pkgSchema.parse(input), invalidKey = Object.keys(input).find((key) => {
|
|
145
|
-
const needle = key.toUpperCase();
|
|
146
|
-
return typoMap.has(needle) ? typoMap.get(needle) !== key : !1;
|
|
147
|
-
});
|
|
148
|
-
if (invalidKey)
|
|
149
|
-
throw new TypeError(
|
|
150
|
-
`
|
|
151
|
-
- package.json: "${invalidKey}" is not a valid key. Did you mean "${typoMap.get(invalidKey.toUpperCase())}"?`
|
|
152
|
-
);
|
|
153
|
-
return pkg;
|
|
154
|
-
}
|
|
155
|
-
async function loadPkg(options) {
|
|
156
|
-
const { cwd } = options, pkgPath = await pkgUp({ cwd });
|
|
157
|
-
if (!pkgPath) throw new Error("no package.json found");
|
|
158
|
-
const buf = await fs.readFile(pkgPath), raw = JSON.parse(buf.toString());
|
|
159
|
-
return validatePkg(raw), raw;
|
|
160
|
-
}
|
|
161
|
-
async function loadPkgWithReporting(options) {
|
|
162
|
-
const { cwd, logger, strict } = options;
|
|
163
|
-
try {
|
|
164
|
-
const pkg = await loadPkg({ cwd });
|
|
165
|
-
let shouldError = !1;
|
|
166
|
-
if (strict && (pkg.type || (shouldError = !0, logger.error(
|
|
167
|
-
'the `type` field in `./package.json` must be either "module" or "commonjs")'
|
|
168
|
-
))), pkg.exports) {
|
|
169
|
-
const _exports = Object.entries(pkg.exports);
|
|
170
|
-
for (const [expPath, exp] of _exports) {
|
|
171
|
-
if (typeof exp == "string" || "svelte" in exp)
|
|
172
|
-
continue;
|
|
173
|
-
const keys = Object.keys(exp);
|
|
174
|
-
exp.types && (shouldError = !0, logger.error(
|
|
175
|
-
`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`
|
|
176
|
-
)), exp.module && (shouldError = !0, logger.error(
|
|
177
|
-
`exports["${expPath}"]: the \`module\` condition shouldn't be used as it's not well supported in all bundlers.`
|
|
178
|
-
)), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0, logger.error(
|
|
179
|
-
`exports["${expPath}"]: the \`node\` property should come before the \`import\` property`
|
|
180
|
-
)), exp.node.module && (shouldError = !0, logger.error(
|
|
181
|
-
`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"`
|
|
182
|
-
)), !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(
|
|
183
|
-
`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"`
|
|
184
|
-
)), exp.require && exp.node.require && exp.require === exp.node.require ? (shouldError = !0, logger.error(
|
|
185
|
-
`exports["${expPath}"]: the \`node.require\` property isn't necessary as it's identical to \`require\``
|
|
186
|
-
)) : exp.require && exp.node.require && !assertOrder("node", "require", keys) && (shouldError = !0, logger.error(
|
|
187
|
-
`exports["${expPath}"]: the \`node\` property should come before the \`require\` property`
|
|
188
|
-
))) : assertOrder("import", "require", keys) || logger.warn(
|
|
189
|
-
`exports["${expPath}"]: the \`import\` property should come before the \`require\` property`
|
|
190
|
-
), assertLast("default", keys) || (shouldError = !0, logger.error(
|
|
191
|
-
`exports["${expPath}"]: the \`default\` property should be the last property`
|
|
192
|
-
));
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
return shouldError && process.exit(1), pkg;
|
|
196
|
-
} catch (err) {
|
|
197
|
-
if (err instanceof ZodError)
|
|
198
|
-
for (const issue of err.issues) {
|
|
199
|
-
if (issue.code === "invalid_type") {
|
|
200
|
-
logger.error(
|
|
201
|
-
[
|
|
202
|
-
`\`${formatPath(issue.path)}\` `,
|
|
203
|
-
`in \`./package.json\` must be of type ${chalk.magenta(issue.expected)} `,
|
|
204
|
-
`(received ${chalk.magenta(issue.received)})`
|
|
205
|
-
].join("")
|
|
206
|
-
);
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
logger.error(issue);
|
|
210
|
-
}
|
|
211
|
-
else
|
|
212
|
-
logger.error(err);
|
|
213
|
-
process.exit(1);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
function formatPath(segments) {
|
|
217
|
-
return segments.map((s, idx) => idx === 0 ? s : typeof s == "number" ? `[${s}]` : s.startsWith(".") ? `["${s}"]` : `.${s}`).join("");
|
|
218
|
-
}
|
|
219
|
-
function createLogger() {
|
|
220
|
-
return {
|
|
221
|
-
log: (...args) => {
|
|
222
|
-
console.log(...args);
|
|
223
|
-
},
|
|
224
|
-
info: (...args) => {
|
|
225
|
-
console.log(chalk.blue("[info]"), ...args);
|
|
226
|
-
},
|
|
227
|
-
warn: (...args) => {
|
|
228
|
-
console.log(chalk.yellow("[warning]"), ...args);
|
|
229
|
-
},
|
|
230
|
-
error: (...args) => {
|
|
231
|
-
console.log(chalk.red("[error]"), ...args);
|
|
232
|
-
},
|
|
233
|
-
success: (...args) => {
|
|
234
|
-
console.log(chalk.green("[success]"), ...args);
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
}
|
|
238
|
-
function browserslistToEsbuild(browserslistConfig, options = {}) {
|
|
239
|
-
if (!browserslistConfig) {
|
|
240
|
-
const path2 = process.cwd();
|
|
241
|
-
browserslistConfig = browserslist.loadConfig({ path: path2, ...options });
|
|
242
|
-
}
|
|
243
|
-
const SUPPORTED_ESBUILD_TARGETS = [
|
|
244
|
-
"es",
|
|
245
|
-
"chrome",
|
|
246
|
-
"edge",
|
|
247
|
-
"firefox",
|
|
248
|
-
"ios",
|
|
249
|
-
"node",
|
|
250
|
-
"safari",
|
|
251
|
-
"opera",
|
|
252
|
-
"ie"
|
|
253
|
-
], UNSUPPORTED = ["android 4"], replaces = {
|
|
254
|
-
ios_saf: "ios",
|
|
255
|
-
android: "chrome"
|
|
256
|
-
}, separator = " ";
|
|
257
|
-
return browserslist(browserslistConfig, options).filter((b) => !UNSUPPORTED.some((u) => b.startsWith(u))).map((b) => b === "safari TP" ? browserslist("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) => {
|
|
258
|
-
const existingIndex = acc.findIndex((br) => br[0] === b[0]);
|
|
259
|
-
return existingIndex !== -1 ? acc[existingIndex][1] = b[1] : acc.push(b), acc;
|
|
260
|
-
}, []).map((b) => b.join(""));
|
|
261
|
-
}
|
|
262
|
-
function resolveConfigProperty(prop, initialValue) {
|
|
263
|
-
return prop ? typeof prop == "function" ? prop(initialValue) : prop : initialValue;
|
|
264
|
-
}
|
|
265
|
-
const DEFAULT_BROWSERSLIST_QUERY = config$1;
|
|
266
|
-
function pathContains(containerPath, itemPath) {
|
|
267
|
-
return !path.relative(containerPath, itemPath).startsWith("..");
|
|
268
|
-
}
|
|
269
|
-
function findCommonDirPath(filePaths) {
|
|
270
|
-
let ret;
|
|
271
|
-
for (const filePath of filePaths) {
|
|
272
|
-
let dirPath = path.dirname(filePath);
|
|
273
|
-
if (!ret) {
|
|
274
|
-
ret = dirPath;
|
|
275
|
-
continue;
|
|
276
|
-
}
|
|
277
|
-
for (; dirPath !== ret && (dirPath = path.dirname(dirPath), dirPath !== ret); ) {
|
|
278
|
-
if (pathContains(dirPath, ret)) {
|
|
279
|
-
ret = dirPath;
|
|
280
|
-
break;
|
|
281
|
-
}
|
|
282
|
-
if (dirPath === ".") return;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
return ret;
|
|
286
|
-
}
|
|
287
|
-
const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
|
|
288
|
-
function getTargetPaths(_type, expOrBundle) {
|
|
289
|
-
const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
|
|
290
|
-
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(
|
|
291
|
-
expOrBundle.browser.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
|
|
292
|
-
), expOrBundle.browser?.require && set.add(
|
|
293
|
-
expOrBundle.browser.require.replace(
|
|
294
|
-
fileEnding,
|
|
295
|
-
type === "commonjs" ? dtsEnding : ctsEnding
|
|
296
|
-
)
|
|
297
|
-
)), expOrBundle.node?.source || (expOrBundle.node?.import && set.add(
|
|
298
|
-
expOrBundle.node.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
|
|
299
|
-
), expOrBundle.node?.require && set.add(
|
|
300
|
-
expOrBundle.node.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)
|
|
301
|
-
))), Array.from(set);
|
|
302
|
-
}
|
|
303
|
-
function isPkgExport$1(exp) {
|
|
304
|
-
return exp?.browser || exp?.node || exp?.default;
|
|
305
|
-
}
|
|
306
|
-
function isRecord(value) {
|
|
307
|
-
return !!value && !Array.isArray(value) && typeof value == "object";
|
|
308
|
-
}
|
|
309
|
-
const pkgExtMap = {
|
|
310
|
-
// pkg.type: "commonjs"
|
|
311
|
-
commonjs: {
|
|
312
|
-
commonjs: defaultEnding,
|
|
313
|
-
esm: mjsEnding
|
|
314
|
-
},
|
|
315
|
-
// pkg.type: "module"
|
|
316
|
-
module: {
|
|
317
|
-
commonjs: cjsEnding,
|
|
318
|
-
esm: defaultEnding
|
|
319
|
-
}
|
|
320
|
-
};
|
|
321
|
-
function validateExports(_exports, options) {
|
|
322
|
-
const { pkg } = options, type = pkg.type || "commonjs", ext = pkgExtMap[type], errors = [];
|
|
323
|
-
for (const exp of _exports)
|
|
324
|
-
exp.require && !exp.require.endsWith(ext.commonjs) && errors.push(
|
|
325
|
-
`package.json with \`type: "${type}"\` - \`exports["${exp._path}"].require\` must end with "${ext.commonjs}"`
|
|
326
|
-
), exp.import && !exp.import.endsWith(ext.esm) && errors.push(
|
|
327
|
-
`package.json with \`type: "${type}"\` - \`exports["${exp._path}"].import\` must end with "${ext.esm}"`
|
|
328
|
-
);
|
|
329
|
-
return errors;
|
|
330
|
-
}
|
|
331
|
-
function parseExports(options) {
|
|
332
|
-
const { cwd, pkg, strict, strictOptions: strictOptions2, logger } = options, type = pkg.type || "commonjs", errors = [], report = (kind, message) => {
|
|
333
|
-
kind === "warn" ? logger.warn(message) : errors.push(message);
|
|
334
|
-
};
|
|
335
|
-
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(
|
|
336
|
-
strictOptions2.alwaysPackageJsonFiles,
|
|
337
|
-
"package.json: `files` should be used over `.npmignore`"
|
|
338
|
-
), pkg.source) {
|
|
339
|
-
if (strict && pkg.exports?.["."] && typeof pkg.exports["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source === pkg.source)
|
|
340
|
-
errors.push(
|
|
341
|
-
'package.json: the "source" property can be removed, as it is equal to exports["."].source.'
|
|
342
|
-
);
|
|
343
|
-
else if (!pkg.exports && pkg.main) {
|
|
344
|
-
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 = [];
|
|
345
|
-
if (pkg.browser) {
|
|
346
|
-
const browserConditions = [];
|
|
347
|
-
pkg.module && pkg.browser?.[pkg.module] ? browserConditions.push(
|
|
348
|
-
` "import": ${JSON.stringify(pkg.browser[pkg.module].replace(fileEnding, extMap.esm))}`
|
|
349
|
-
) : pkg.browser?.[pkg.main] && browserConditions.push(
|
|
350
|
-
` "import": ${JSON.stringify(pkg.browser?.[pkg.main].replace(fileEnding, extMap.esm))}`
|
|
351
|
-
), pkg.browser?.[pkg.main] && browserConditions.push(
|
|
352
|
-
` "require": ${JSON.stringify(pkg.browser[pkg.main].replace(fileEnding, extMap.commonjs))}`
|
|
353
|
-
), browserConditions.length && maybeBrowserCondition.push(
|
|
354
|
-
' "browser": {',
|
|
355
|
-
` "source": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,
|
|
356
|
-
...browserConditions,
|
|
357
|
-
" }"
|
|
358
|
-
);
|
|
359
|
-
}
|
|
360
|
-
errors.push(
|
|
361
|
-
...[
|
|
362
|
-
"package.json: `exports` are missing, it should be:",
|
|
363
|
-
'"exports": {',
|
|
364
|
-
' ".": {',
|
|
365
|
-
` "source": ${JSON.stringify(pkg.source)},`,
|
|
366
|
-
// If browser conditions are detected then add them to the suggestion
|
|
367
|
-
...maybeBrowserCondition.length > 0 ? maybeBrowserCondition : [],
|
|
368
|
-
type === "commonjs" && ` "import": ${JSON.stringify(importExport)},`,
|
|
369
|
-
type === "module" && ` "require": ${JSON.stringify(requireExport)},`,
|
|
370
|
-
` "default": ${JSON.stringify(defaultExport)}`,
|
|
371
|
-
" },",
|
|
372
|
-
' "./package.json": "./package.json"',
|
|
373
|
-
"}"
|
|
374
|
-
].filter(Boolean)
|
|
375
|
-
);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
if (errors.length)
|
|
379
|
-
throw new Error(`
|
|
380
|
-
- ` + errors.join(`
|
|
381
|
-
- `));
|
|
382
|
-
if (!pkg.exports)
|
|
383
|
-
throw new Error(
|
|
384
|
-
`
|
|
385
|
-
- ` + [
|
|
386
|
-
"package.json: `exports` are missing, please set a minimal configuration, for example:",
|
|
387
|
-
'"exports": {',
|
|
388
|
-
' ".": {',
|
|
389
|
-
' "source": "./src/index.js",',
|
|
390
|
-
' "default": "./dist/index.js"',
|
|
391
|
-
" },",
|
|
392
|
-
' "./package.json": "./package.json"',
|
|
393
|
-
"}"
|
|
394
|
-
].join(`
|
|
395
|
-
- `)
|
|
396
|
-
);
|
|
397
|
-
const _exports = [];
|
|
398
|
-
strict && strictOptions2.noPackageJsonTypings !== "off" && "typings" in pkg && report(strictOptions2.noPackageJsonTypings, "package.json: `typings` should be `types`"), strict && strictOptions2.alwaysPackageJsonTypes !== "off" && !pkg.types && typeof pkg.exports?.["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source?.endsWith(".ts") && report(
|
|
399
|
-
strictOptions2.alwaysPackageJsonTypes,
|
|
400
|
-
"package.json: `types` must be declared for the npm listing to show as a TypeScript module."
|
|
401
|
-
), strict && !pkg.exports["./package.json"] && errors.push('package.json: `exports["./package.json"] must be declared.');
|
|
402
|
-
for (const [exportPath, exportEntry] of Object.entries(pkg.exports))
|
|
403
|
-
if (exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json"))
|
|
404
|
-
exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push('package.json: `exports["./package.json"]` must be "./package.json".');
|
|
405
|
-
else if (exportPath.endsWith(".css"))
|
|
406
|
-
typeof exportEntry == "string" && !existsSync(resolve(cwd, exportEntry)) ? errors.push(
|
|
407
|
-
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`
|
|
408
|
-
) : typeof exportEntry != "string" && errors.push(
|
|
409
|
-
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
|
|
410
|
-
);
|
|
411
|
-
else if (!(isRecord(exportEntry) && "svelte" in exportEntry))
|
|
412
|
-
if (isPkgExport(exportEntry)) {
|
|
413
|
-
const exp = {
|
|
414
|
-
_exported: !0,
|
|
415
|
-
_path: exportPath,
|
|
416
|
-
...exportEntry
|
|
417
|
-
};
|
|
418
|
-
if (!exp.default) {
|
|
419
|
-
const fallback = type === "module" ? exp.import : exp.require;
|
|
420
|
-
fallback && (exp.default = fallback);
|
|
421
|
-
}
|
|
422
|
-
!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(
|
|
423
|
-
'package.json: mismatch between "main" and "exports.require". These must be equal.'
|
|
424
|
-
), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
|
|
425
|
-
'package.json: mismatch between "module" and "exports.import" These must be equal.'
|
|
426
|
-
)), _exports.push(exp);
|
|
427
|
-
} else isRecord(exportEntry) || errors.push("package.json: exports must be an object");
|
|
428
|
-
if (errors.push(...validateExports(_exports, { pkg })), errors.length)
|
|
429
|
-
throw new Error(`
|
|
430
|
-
- ` + errors.join(`
|
|
431
|
-
- `));
|
|
432
|
-
return _exports;
|
|
433
|
-
}
|
|
434
|
-
function isPkgExport(value) {
|
|
435
|
-
return isRecord(value) && "source" in value && typeof value.source == "string";
|
|
436
|
-
}
|
|
437
|
-
async function loadTSConfig(options) {
|
|
438
|
-
const { cwd, tsconfigPath } = options, configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
|
|
439
|
-
if (!configPath)
|
|
440
|
-
return;
|
|
441
|
-
const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
442
|
-
return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
|
|
443
|
-
}
|
|
444
|
-
function resolveBrowserTarget(versions) {
|
|
445
|
-
const target = versions.filter(
|
|
446
|
-
(version) => version.startsWith("chrome") || version.startsWith("edge") || version.startsWith("firefox") || version.startsWith("ios") || version.startsWith("safari") || version.startsWith("opera")
|
|
447
|
-
);
|
|
448
|
-
if (target.length !== 0)
|
|
449
|
-
return target;
|
|
450
|
-
}
|
|
451
|
-
function resolveNodeTarget(versions) {
|
|
452
|
-
const target = versions.filter((version) => version.startsWith("node"));
|
|
453
|
-
if (target.length !== 0)
|
|
454
|
-
return target;
|
|
455
|
-
}
|
|
456
|
-
const toggle = z.union([z.literal("error"), z.literal("warn"), z.literal("off")]), strictOptions = z.object({
|
|
457
|
-
noPackageJsonTypings: toggle.default("error"),
|
|
458
|
-
noImplicitSideEffects: toggle.default("warn"),
|
|
459
|
-
noImplicitBrowsersList: toggle.default("warn"),
|
|
460
|
-
alwaysPackageJsonTypes: toggle.default("error"),
|
|
461
|
-
alwaysPackageJsonMain: toggle.default("error"),
|
|
462
|
-
alwaysPackageJsonFiles: toggle.default("error")
|
|
463
|
-
}).strict(), validationSchema = z.object({
|
|
464
|
-
strictOptions: strictOptions.default({})
|
|
465
|
-
});
|
|
466
|
-
function parseStrictOptions(input) {
|
|
467
|
-
return validationSchema.parse({ strictOptions: input }, { errorMap }).strictOptions;
|
|
468
|
-
}
|
|
469
|
-
async function resolveBuildContext(options) {
|
|
470
|
-
const {
|
|
471
|
-
config: config2,
|
|
472
|
-
cwd,
|
|
473
|
-
emitDeclarationOnly = !1,
|
|
474
|
-
logger,
|
|
475
|
-
pkg,
|
|
476
|
-
strict,
|
|
477
|
-
tsconfig: tsconfigPath
|
|
478
|
-
} = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config2?.strictOptions ?? {});
|
|
479
|
-
let browserslist2 = pkg.browserslist;
|
|
480
|
-
if (!browserslist2) {
|
|
481
|
-
if (strict && strictOptions2.noImplicitBrowsersList !== "off") {
|
|
482
|
-
if (strictOptions2.noImplicitBrowsersList === "error")
|
|
483
|
-
throw new Error(
|
|
484
|
-
'\n- package.json: "browserslist" is missing, set it to `"browserslist": "extends @sanity/browserslist-config"`'
|
|
485
|
-
);
|
|
486
|
-
logger.warn(
|
|
487
|
-
'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `"browserslist": "extends @sanity/browserslist-config"` to silence this warning.'
|
|
488
|
-
);
|
|
489
|
-
}
|
|
490
|
-
browserslist2 = DEFAULT_BROWSERSLIST_QUERY;
|
|
491
|
-
}
|
|
492
|
-
const targetVersions = browserslistToEsbuild(browserslist2);
|
|
493
|
-
if (strict && strictOptions2.noImplicitSideEffects !== "off" && typeof pkg.sideEffects > "u") {
|
|
494
|
-
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`";
|
|
495
|
-
if (strictOptions2.noImplicitSideEffects === "error")
|
|
496
|
-
throw new Error(msg);
|
|
497
|
-
logger.warn(msg);
|
|
498
|
-
}
|
|
499
|
-
const nodeTarget = resolveNodeTarget(targetVersions), webTarget = resolveBrowserTarget(targetVersions);
|
|
500
|
-
if (!nodeTarget)
|
|
501
|
-
throw new Error("no matching `node` target");
|
|
502
|
-
if (!webTarget)
|
|
503
|
-
throw new Error("no matching `web` target");
|
|
504
|
-
const target = {
|
|
505
|
-
"*": webTarget.concat(nodeTarget),
|
|
506
|
-
browser: webTarget,
|
|
507
|
-
node: nodeTarget
|
|
508
|
-
}, parsedExports = parseExports({
|
|
509
|
-
cwd,
|
|
510
|
-
pkg,
|
|
511
|
-
strict,
|
|
512
|
-
strictOptions: strictOptions2,
|
|
513
|
-
logger
|
|
514
|
-
}).reduce(
|
|
515
|
-
(acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
|
|
516
|
-
{}
|
|
517
|
-
), exports = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
|
|
518
|
-
...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
|
|
519
|
-
...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
|
|
520
|
-
], 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(
|
|
521
|
-
// Do not bundle anything that is marked as external
|
|
522
|
-
(_) => !externalWithTypes.has(_)
|
|
523
|
-
), bundledPackages = config2 && Array.isArray(config2.extract?.bundledPackages) ? [...bundledDependencies, ...config2.extract.bundledPackages] : resolveConfigProperty(config2?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports).flatMap((exportEntry) => [
|
|
524
|
-
exportEntry.import,
|
|
525
|
-
exportEntry.require,
|
|
526
|
-
exportEntry.browser?.import,
|
|
527
|
-
exportEntry.browser?.require,
|
|
528
|
-
exportEntry.node?.source && exportEntry.node.import,
|
|
529
|
-
exportEntry.node?.source && exportEntry.node.require
|
|
530
|
-
].filter(Boolean)).map((p) => path.resolve(cwd, p)), commonDistPath = findCommonDirPath(outputPaths);
|
|
531
|
-
if (commonDistPath === cwd)
|
|
532
|
-
throw new Error(
|
|
533
|
-
"all output files must share a common parent directory which is not the root package directory"
|
|
534
|
-
);
|
|
535
|
-
if (commonDistPath && !pathContains(cwd, commonDistPath))
|
|
536
|
-
throw new Error("all output files must be located within the package");
|
|
537
|
-
const configDistPath = config2?.dist ? path.resolve(cwd, config2.dist) : void 0;
|
|
538
|
-
if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
|
|
539
|
-
throw logger.log(`did you mean to configure \`dist: './${path.relative(cwd, commonDistPath)}'\`?`), new Error("all output files must be located with the configured `dist` path");
|
|
540
|
-
const distPath = configDistPath || commonDistPath;
|
|
541
|
-
if (!distPath)
|
|
542
|
-
throw new Error("could not detect `dist` path");
|
|
543
|
-
return {
|
|
544
|
-
config: config2,
|
|
545
|
-
cwd,
|
|
546
|
-
distPath,
|
|
547
|
-
emitDeclarationOnly,
|
|
548
|
-
exports,
|
|
549
|
-
external,
|
|
550
|
-
bundledPackages,
|
|
551
|
-
files: [],
|
|
552
|
-
logger,
|
|
553
|
-
pkg,
|
|
554
|
-
runtime: config2?.runtime ?? "*",
|
|
555
|
-
strict,
|
|
556
|
-
target,
|
|
557
|
-
ts: {
|
|
558
|
-
config: tsconfig,
|
|
559
|
-
configPath: tsconfigPath
|
|
560
|
-
},
|
|
561
|
-
dts: config2?.dts === "rolldown" ? "rolldown" : "api-extractor"
|
|
562
|
-
};
|
|
563
|
-
}
|
|
564
|
-
function transformPackageName(packageName) {
|
|
565
|
-
if (packageName.startsWith("@types/"))
|
|
566
|
-
return packageName;
|
|
567
|
-
if (packageName.startsWith("@")) {
|
|
568
|
-
const [scope, name] = packageName.split("/");
|
|
569
|
-
return `@types/${scope.slice(1)}__${name}`;
|
|
570
|
-
} else
|
|
571
|
-
return `@types/${packageName}`;
|
|
572
|
-
}
|
|
573
|
-
function resolveBuildTasks(ctx) {
|
|
574
|
-
const { config: config2, pkg, target } = ctx, bundles = config2?.bundles || [], tasks = [], exports = Object.entries(ctx.exports || {}).map(
|
|
575
|
-
([_path, exp]) => ({ _path, ...exp })
|
|
576
|
-
), dtsTask2 = {
|
|
577
|
-
type: "build:dts",
|
|
578
|
-
entries: []
|
|
579
|
-
}, rolldownDtsTask2 = {}, rollupTasks = {};
|
|
580
|
-
function addRollupTaskEntry(format2, runtime, entry) {
|
|
581
|
-
const buildId = `${format2}:${runtime}`;
|
|
582
|
-
ctx.dts === "rolldown" && (rolldownDtsTask2[buildId] ? rolldownDtsTask2[buildId].entries.push(entry) : rolldownDtsTask2[buildId] = {
|
|
583
|
-
type: "rolldown:dts",
|
|
584
|
-
buildId,
|
|
585
|
-
entries: [entry],
|
|
586
|
-
runtime,
|
|
587
|
-
format: format2,
|
|
588
|
-
target: target[runtime]
|
|
589
|
-
}), ctx.emitDeclarationOnly || (rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
|
|
590
|
-
type: "build:js",
|
|
591
|
-
buildId,
|
|
592
|
-
entries: [entry],
|
|
593
|
-
runtime,
|
|
594
|
-
format: format2,
|
|
595
|
-
target: target[runtime]
|
|
596
|
-
});
|
|
597
|
-
}
|
|
598
|
-
if (ctx.dts === "api-extractor") {
|
|
599
|
-
for (const exp of exports) {
|
|
600
|
-
const importId = path.join(pkg.name, exp._path);
|
|
601
|
-
exp.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
602
|
-
importId,
|
|
603
|
-
exportPath: exp._path,
|
|
604
|
-
sourcePath: exp.source,
|
|
605
|
-
targetPaths: getTargetPaths(pkg.type, exp)
|
|
606
|
-
}), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
607
|
-
importId,
|
|
608
|
-
exportPath: exp._path,
|
|
609
|
-
sourcePath: exp.browser.source,
|
|
610
|
-
targetPaths: getTargetPaths(pkg.type, exp.browser)
|
|
611
|
-
}), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
612
|
-
importId,
|
|
613
|
-
exportPath: exp._path,
|
|
614
|
-
sourcePath: exp.node.source,
|
|
615
|
-
targetPaths: getTargetPaths(pkg.type, exp.node)
|
|
616
|
-
});
|
|
617
|
-
}
|
|
618
|
-
for (const bundle of bundles)
|
|
619
|
-
if (bundle.source?.endsWith(".ts")) {
|
|
620
|
-
const exportPath = (bundle.import || bundle.require).replace(/\.[mc]?js$/, ""), importId = path.join(pkg.name, exportPath);
|
|
621
|
-
dtsTask2.entries.push({
|
|
622
|
-
importId,
|
|
623
|
-
exportPath,
|
|
624
|
-
sourcePath: bundle.source,
|
|
625
|
-
targetPaths: getTargetPaths(pkg.type, bundle)
|
|
626
|
-
});
|
|
627
|
-
}
|
|
628
|
-
dtsTask2.entries.length && tasks.push(dtsTask2);
|
|
629
|
-
}
|
|
630
|
-
for (const exp of exports) {
|
|
631
|
-
const output = exp.require;
|
|
632
|
-
output && addRollupTaskEntry("commonjs", ctx.runtime, {
|
|
633
|
-
path: exp._path,
|
|
634
|
-
source: exp.source,
|
|
635
|
-
output
|
|
636
|
-
});
|
|
637
|
-
}
|
|
638
|
-
for (const exp of exports) {
|
|
639
|
-
const output = exp.import;
|
|
640
|
-
output && addRollupTaskEntry("esm", ctx.runtime, {
|
|
641
|
-
path: exp._path,
|
|
642
|
-
source: exp.source,
|
|
643
|
-
output
|
|
644
|
-
});
|
|
645
|
-
}
|
|
646
|
-
for (const exp of exports) {
|
|
647
|
-
const output = exp.browser?.require;
|
|
648
|
-
output && addRollupTaskEntry("commonjs", "browser", {
|
|
649
|
-
path: exp._path,
|
|
650
|
-
source: exp.browser?.source || exp.source,
|
|
651
|
-
output
|
|
652
|
-
});
|
|
653
|
-
}
|
|
654
|
-
for (const exp of exports) {
|
|
655
|
-
const output = exp.browser?.import;
|
|
656
|
-
output && addRollupTaskEntry("esm", "browser", {
|
|
657
|
-
path: exp._path,
|
|
658
|
-
source: exp.browser?.source || exp.source,
|
|
659
|
-
output
|
|
660
|
-
});
|
|
661
|
-
}
|
|
662
|
-
for (const bundle of bundles) {
|
|
663
|
-
const idx = bundles.indexOf(bundle);
|
|
664
|
-
bundle.require && addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
|
|
665
|
-
path: `__$$bundle_cjs_${idx}$$__`,
|
|
666
|
-
source: bundle.source,
|
|
667
|
-
output: bundle.require
|
|
668
|
-
}), bundle.import && addRollupTaskEntry("esm", bundle.runtime || ctx.runtime, {
|
|
669
|
-
path: `__$$bundle_esm_${idx}$$__`,
|
|
670
|
-
source: bundle.source,
|
|
671
|
-
output: bundle.import
|
|
672
|
-
});
|
|
673
|
-
}
|
|
674
|
-
return tasks.push(...Object.values(rolldownDtsTask2)), tasks.push(...Object.values(rollupTasks)), tasks;
|
|
675
|
-
}
|
|
676
|
-
function createSpinner(msg) {
|
|
677
|
-
const startTime = Date.now();
|
|
678
|
-
return console.log(msg), {
|
|
679
|
-
complete: () => {
|
|
680
|
-
console.log(`${chalk.green("[success]")} ${chalk.gray(`${Date.now() - startTime}ms`)}`);
|
|
681
|
-
},
|
|
682
|
-
error: () => {
|
|
683
|
-
console.log(`${chalk.red("[error]")} ${chalk.gray(`${Date.now() - startTime}ms`)}`);
|
|
684
|
-
}
|
|
685
|
-
};
|
|
686
|
-
}
|
|
687
|
-
function printExtractMessages(ctx, messages) {
|
|
688
|
-
const { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === "warning");
|
|
689
|
-
warnings.length && logger.log();
|
|
690
|
-
for (const msg of warnings) {
|
|
691
|
-
const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
|
|
692
|
-
msg.messageId !== "TS6307" && logger.log(
|
|
693
|
-
[
|
|
694
|
-
`${chalk.cyan(sourceFilePath || "?")}`,
|
|
695
|
-
`:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,
|
|
696
|
-
` - ${chalk.yellow("warning")} ${chalk.gray(msg.messageId)}
|
|
697
|
-
`,
|
|
698
|
-
msg.text,
|
|
699
|
-
`
|
|
700
|
-
`
|
|
701
|
-
].join("")
|
|
702
|
-
);
|
|
703
|
-
}
|
|
704
|
-
const errors = messages.filter((msg) => msg.logLevel === "error");
|
|
705
|
-
!warnings.length && errors.length && logger.log("");
|
|
706
|
-
for (const msg of errors) {
|
|
707
|
-
const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
|
|
708
|
-
logger.log(
|
|
709
|
-
[
|
|
710
|
-
`${chalk.cyan(sourceFilePath || "?")}`,
|
|
711
|
-
`:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,
|
|
712
|
-
` - ${chalk.red("error")} ${chalk.gray(msg.messageId)}
|
|
713
|
-
`,
|
|
714
|
-
msg.text,
|
|
715
|
-
`
|
|
716
|
-
`
|
|
717
|
-
].join("")
|
|
718
|
-
);
|
|
719
|
-
}
|
|
720
|
-
errors.length && process.exit(1);
|
|
721
|
-
}
|
|
722
|
-
function printDiagnostic(options) {
|
|
723
|
-
const { cwd, logger, diagnostic } = options;
|
|
724
|
-
if (diagnostic.file && diagnostic.start) {
|
|
725
|
-
const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), message = ts.flattenDiagnosticMessageText(diagnostic.messageText, `
|
|
726
|
-
`), file = path.relative(cwd, diagnostic.file.fileName), output = [
|
|
727
|
-
`${chalk.yellow(file)}:${chalk.blue(line + 1)}:${chalk.blue(character + 1)} - `,
|
|
728
|
-
`${chalk.gray(`TS${diagnostic.code}:`)} ${message}`
|
|
729
|
-
].join("");
|
|
730
|
-
diagnostic.category === ts.DiagnosticCategory.Error && logger.error(output), diagnostic.category === ts.DiagnosticCategory.Warning && logger.warn(output), diagnostic.category === ts.DiagnosticCategory.Message && logger.log(output), diagnostic.category === ts.DiagnosticCategory.Suggestion && logger.log(output);
|
|
731
|
-
} else
|
|
732
|
-
logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
|
|
733
|
-
`));
|
|
734
|
-
}
|
|
735
|
-
async function buildTypes(options) {
|
|
736
|
-
const { cwd, logger, outDir, tsconfig, strict = !1 } = options, compilerOptions = {
|
|
737
|
-
...tsconfig.options,
|
|
738
|
-
declaration: !0,
|
|
739
|
-
declarationDir: outDir,
|
|
740
|
-
emitDeclarationOnly: !0,
|
|
741
|
-
noEmit: !1,
|
|
742
|
-
noEmitOnError: strict ? !0 : tsconfig.options.noEmitOnError ?? !0,
|
|
743
|
-
outDir
|
|
744
|
-
}, program = ts.createProgram(tsconfig.fileNames, compilerOptions), emitResult = program.emit(), allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
|
|
745
|
-
for (const diagnostic of allDiagnostics)
|
|
746
|
-
printDiagnostic({ cwd, logger, diagnostic });
|
|
747
|
-
if (emitResult.emitSkipped && allDiagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error).length)
|
|
748
|
-
throw new Error("failed to compile TypeScript definitions");
|
|
749
|
-
}
|
|
750
|
-
class DtsError extends Error {
|
|
751
|
-
messages;
|
|
752
|
-
constructor(message, messages) {
|
|
753
|
-
super(message), this.messages = messages;
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
function createApiExtractorConfig(options) {
|
|
757
|
-
const {
|
|
758
|
-
bundledPackages,
|
|
759
|
-
distPath,
|
|
760
|
-
exportPath,
|
|
761
|
-
filePath,
|
|
762
|
-
messages,
|
|
763
|
-
projectFolder,
|
|
764
|
-
mainEntryPointFilePath,
|
|
765
|
-
tsconfig,
|
|
766
|
-
tsconfigPath,
|
|
767
|
-
dtsRollupEnabled
|
|
768
|
-
} = options;
|
|
769
|
-
return {
|
|
770
|
-
apiReport: {
|
|
771
|
-
enabled: !1,
|
|
772
|
-
reportFileName: "<unscopedPackageName>.api.md"
|
|
773
|
-
},
|
|
774
|
-
bundledPackages,
|
|
775
|
-
// If `paths` are used for self-referencing imports (e.g. the module is named `sanity`, and the `sanity/structure` export is also importing from `sanity/router`),
|
|
776
|
-
compiler: tsconfig.options.paths ? {
|
|
777
|
-
overrideTsconfig: {
|
|
778
|
-
extends: tsconfigPath,
|
|
779
|
-
compilerOptions: {
|
|
780
|
-
// An empty object replaces whatever is in the original tsconfig file
|
|
781
|
-
paths: {}
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
} : { tsconfigFilePath: tsconfigPath },
|
|
785
|
-
docModel: {
|
|
786
|
-
enabled: !1,
|
|
787
|
-
apiJsonFilePath: path.resolve(distPath, `${exportPath}.api.json`)
|
|
788
|
-
},
|
|
789
|
-
dtsRollup: {
|
|
790
|
-
enabled: dtsRollupEnabled,
|
|
791
|
-
untrimmedFilePath: path.resolve(distPath, filePath)
|
|
792
|
-
// betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
|
|
793
|
-
// publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
|
|
794
|
-
},
|
|
795
|
-
tsdocMetadata: {
|
|
796
|
-
enabled: !1
|
|
797
|
-
},
|
|
798
|
-
messages,
|
|
799
|
-
mainEntryPointFilePath,
|
|
800
|
-
projectFolder
|
|
801
|
-
};
|
|
802
|
-
}
|
|
803
|
-
async function createTSDocConfig(opts) {
|
|
804
|
-
const { customTags } = opts;
|
|
805
|
-
if (customTags.length === 0)
|
|
806
|
-
return;
|
|
807
|
-
const tsDocBaseBuf = await readFile(
|
|
808
|
-
require.resolve("@microsoft/api-extractor/extends/tsdoc-base.json")
|
|
809
|
-
), tsDocBaseConfig = parse(tsDocBaseBuf.toString()), tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(
|
|
810
|
-
customTags.map((t) => ({
|
|
811
|
-
tagName: `@${t.name}`,
|
|
812
|
-
syntaxKind: t.syntaxKind,
|
|
813
|
-
allowMultiple: t.allowMultiple
|
|
814
|
-
}))
|
|
815
|
-
), supportForTags = { ...tsDocBaseConfig.supportForTags };
|
|
816
|
-
for (const customTag of customTags)
|
|
817
|
-
supportForTags[`@${customTag.name}`] = !0;
|
|
818
|
-
return TSDocConfigFile.loadFromObject({
|
|
819
|
-
...tsDocBaseConfig,
|
|
820
|
-
noStandardTags: !1,
|
|
821
|
-
tagDefinitions,
|
|
822
|
-
supportForTags
|
|
823
|
-
});
|
|
824
|
-
}
|
|
825
|
-
async function extractModuleBlocksFromTypes({
|
|
826
|
-
tsOutDir,
|
|
827
|
-
extractResult
|
|
828
|
-
}) {
|
|
829
|
-
const program = extractResult.compilerState.program, moduleBlocks = [], sourceFiles = [...program.getSourceFiles()].filter((sourceFile) => sourceFile.fileName.includes(tsOutDir));
|
|
830
|
-
for (const sourceFile of sourceFiles)
|
|
831
|
-
sourceFile.text.includes("declare module") && moduleBlocks.push(...extractModuleBlocks(sourceFile.text));
|
|
832
|
-
return moduleBlocks;
|
|
833
|
-
}
|
|
834
|
-
function extractModuleBlocks(fileContent) {
|
|
835
|
-
return parse$1(fileContent, {
|
|
836
|
-
parser: typeScriptParser
|
|
837
|
-
}).program.body.filter((node) => node.type === "TSModuleDeclaration").map((node) => print(node).code);
|
|
838
|
-
}
|
|
839
|
-
const LOG_LEVELS = {
|
|
840
|
-
error: "error",
|
|
841
|
-
info: "info",
|
|
842
|
-
off: "none",
|
|
843
|
-
warn: "warning"
|
|
844
|
-
};
|
|
845
|
-
function getExtractMessagesConfig(options) {
|
|
846
|
-
const { rules, disabled = !1 } = options;
|
|
847
|
-
function ruleToLogLevel(key, defaultLevel) {
|
|
848
|
-
const r = rules?.[key];
|
|
849
|
-
return r ? LOG_LEVELS[r] : defaultLevel || "warning";
|
|
850
|
-
}
|
|
851
|
-
return {
|
|
852
|
-
compilerMessageReporting: {
|
|
853
|
-
default: {
|
|
854
|
-
logLevel: disabled ? "none" : "warning"
|
|
855
|
-
}
|
|
856
|
-
},
|
|
857
|
-
extractorMessageReporting: disabled ? {
|
|
858
|
-
default: {
|
|
859
|
-
logLevel: "none",
|
|
860
|
-
addToApiReportFile: !1
|
|
861
|
-
}
|
|
862
|
-
} : {
|
|
863
|
-
default: {
|
|
864
|
-
logLevel: "warning",
|
|
865
|
-
addToApiReportFile: !1
|
|
866
|
-
},
|
|
867
|
-
"ae-forgotten-export": {
|
|
868
|
-
/**
|
|
869
|
-
* This is hardcoded to `none` as it's no longer needed since TypeScript 5.5 https://github.com/microsoft/TypeScript/issues/42873
|
|
870
|
-
* It's hardcoded to `none` since supported by API Extractor when using `module: 'Preserve'` doesn't support it well since `@microsoft/api-extractor` v7.49.0, which upgraded from TS 5.4 to 5.7 internally
|
|
871
|
-
*/
|
|
872
|
-
logLevel: "none",
|
|
873
|
-
addToApiReportFile: !1
|
|
874
|
-
},
|
|
875
|
-
"ae-incompatible-release-tags": {
|
|
876
|
-
logLevel: ruleToLogLevel("ae-incompatible-release-tags", "error"),
|
|
877
|
-
addToApiReportFile: !1
|
|
878
|
-
},
|
|
879
|
-
"ae-internal-missing-underscore": {
|
|
880
|
-
logLevel: ruleToLogLevel("ae-internal-missing-underscore"),
|
|
881
|
-
addToApiReportFile: !1
|
|
882
|
-
},
|
|
883
|
-
"ae-missing-release-tag": {
|
|
884
|
-
logLevel: ruleToLogLevel("ae-missing-release-tag", "error"),
|
|
885
|
-
addToApiReportFile: !1
|
|
886
|
-
},
|
|
887
|
-
"ae-wrong-input-file-type": {
|
|
888
|
-
logLevel: "none",
|
|
889
|
-
addToApiReportFile: !1
|
|
890
|
-
}
|
|
891
|
-
},
|
|
892
|
-
tsdocMessageReporting: disabled ? {
|
|
893
|
-
default: {
|
|
894
|
-
logLevel: "none",
|
|
895
|
-
addToApiReportFile: !1
|
|
896
|
-
}
|
|
897
|
-
} : {
|
|
898
|
-
default: {
|
|
899
|
-
logLevel: "warning",
|
|
900
|
-
addToApiReportFile: !1
|
|
901
|
-
},
|
|
902
|
-
"tsdoc-link-tag-unescaped-text": {
|
|
903
|
-
logLevel: ruleToLogLevel(
|
|
904
|
-
"tsdoc-link-tag-unescaped-text",
|
|
905
|
-
"warning"
|
|
906
|
-
),
|
|
907
|
-
addToApiReportFile: !1
|
|
908
|
-
},
|
|
909
|
-
"tsdoc-undefined-tag": {
|
|
910
|
-
logLevel: ruleToLogLevel("tsdoc-undefined-tag", "error"),
|
|
911
|
-
addToApiReportFile: !1
|
|
912
|
-
},
|
|
913
|
-
"tsdoc-unsupported-tag": {
|
|
914
|
-
logLevel: ruleToLogLevel("tsdoc-unsupported-tag", "none"),
|
|
915
|
-
addToApiReportFile: !1
|
|
916
|
-
}
|
|
917
|
-
}
|
|
918
|
-
};
|
|
919
|
-
}
|
|
920
|
-
async function extractTypes(options) {
|
|
921
|
-
const {
|
|
922
|
-
bundledPackages,
|
|
923
|
-
customTags,
|
|
924
|
-
distPath,
|
|
925
|
-
exportPath,
|
|
926
|
-
files,
|
|
927
|
-
filePaths,
|
|
928
|
-
projectPath,
|
|
929
|
-
rules,
|
|
930
|
-
sourceTypesPath,
|
|
931
|
-
tmpPath,
|
|
932
|
-
tsconfig,
|
|
933
|
-
tsconfigPath,
|
|
934
|
-
extractorDisabled
|
|
935
|
-
} = options, tsdocConfigFile = await createTSDocConfig({
|
|
936
|
-
customTags: customTags || []
|
|
937
|
-
}), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = ExtractorConfig.prepare({
|
|
938
|
-
configObject: createApiExtractorConfig({
|
|
939
|
-
bundledPackages,
|
|
940
|
-
distPath,
|
|
941
|
-
exportPath,
|
|
942
|
-
filePath,
|
|
943
|
-
messages: getExtractMessagesConfig({ rules, disabled: extractorDisabled }),
|
|
944
|
-
projectFolder: projectPath,
|
|
945
|
-
mainEntryPointFilePath: sourceTypesPath,
|
|
946
|
-
tsconfig,
|
|
947
|
-
tsconfigPath,
|
|
948
|
-
dtsRollupEnabled: !0
|
|
949
|
-
}),
|
|
950
|
-
configObjectFullPath: void 0,
|
|
951
|
-
tsdocConfigFile,
|
|
952
|
-
packageJsonFullPath: path.resolve(projectPath, "package.json")
|
|
953
|
-
}), messages = [], extractorResult = Extractor.invoke(extractorConfig, {
|
|
954
|
-
// Equivalent to the "--local" command-line parameter
|
|
955
|
-
localBuild: !0,
|
|
956
|
-
// Equivalent to the "--verbose" command-line parameter
|
|
957
|
-
showVerboseMessages: !0,
|
|
958
|
-
// handle messages
|
|
959
|
-
messageCallback(message) {
|
|
960
|
-
messages.push(message), message.handled = !0;
|
|
961
|
-
}
|
|
962
|
-
}), typesPath = path.resolve(distPath, filePath), typesBuf = await fs.readFile(typesPath), prettierConfig = await prettier.resolveConfig(typesPath);
|
|
963
|
-
await mkdirp(path.dirname(typesPath));
|
|
964
|
-
const moduleBlocks = await extractModuleBlocksFromTypes({
|
|
965
|
-
extractResult: extractorResult,
|
|
966
|
-
tsOutDir: tmpPath
|
|
967
|
-
}), code = [typesBuf.toString(), ...moduleBlocks].join(`
|
|
968
|
-
|
|
969
|
-
`), prettyCode = await prettier.format(code, {
|
|
970
|
-
...prettierConfig,
|
|
971
|
-
filepath: typesPath
|
|
972
|
-
});
|
|
973
|
-
for (const expFilePath of filePaths) {
|
|
974
|
-
const expTypesPath = path.resolve(distPath, expFilePath);
|
|
975
|
-
await fs.writeFile(expTypesPath, prettyCode), files.push({
|
|
976
|
-
type: "types",
|
|
977
|
-
path: expTypesPath
|
|
978
|
-
});
|
|
979
|
-
}
|
|
980
|
-
return shouldCleanUpDts && await fs.unlink(typesPath), { extractorResult, messages };
|
|
981
|
-
}
|
|
982
|
-
async function doExtract(ctx, task) {
|
|
983
|
-
const { config: config2, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
|
|
984
|
-
if (!ts2.config || !ts2.configPath)
|
|
985
|
-
return { type: "dts", messages: [], results: [] };
|
|
986
|
-
const { outDir, rootDir = cwd } = ts2.config.options;
|
|
987
|
-
if (!outDir)
|
|
988
|
-
throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
|
|
989
|
-
const tmpPath = path.resolve(outDir, "__tmp__");
|
|
990
|
-
await buildTypes({ cwd, logger, outDir: tmpPath, strict, tsconfig: ts2.config });
|
|
991
|
-
const messages = [], results = [];
|
|
992
|
-
for (const entry of task.entries) {
|
|
993
|
-
const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path.resolve(
|
|
994
|
-
tmpPath,
|
|
995
|
-
path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
|
|
996
|
-
), targetPaths = entry.targetPaths.map((targetPath) => path.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path.relative(outDir, targetPath)), result = await extractTypes({
|
|
997
|
-
bundledPackages: bundledPackages || [],
|
|
998
|
-
customTags: config2?.extract?.customTags,
|
|
999
|
-
distPath: outDir,
|
|
1000
|
-
exportPath,
|
|
1001
|
-
files,
|
|
1002
|
-
filePaths,
|
|
1003
|
-
projectPath: cwd,
|
|
1004
|
-
rules: config2?.extract?.rules,
|
|
1005
|
-
sourceTypesPath,
|
|
1006
|
-
tsconfig: ts2.config,
|
|
1007
|
-
tmpPath,
|
|
1008
|
-
tsconfigPath: path.resolve(cwd, ts2.configPath || "tsconfig.json"),
|
|
1009
|
-
extractorDisabled: config2?.extract?.enabled === !1
|
|
1010
|
-
});
|
|
1011
|
-
messages.push(...result.messages);
|
|
1012
|
-
const errors = result.messages.filter((msg) => msg.logLevel === "error");
|
|
1013
|
-
if (errors.length > 0)
|
|
1014
|
-
throw await rimraf$1(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
|
|
1015
|
-
results.push({ sourcePath: path.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
|
|
1016
|
-
}
|
|
1017
|
-
return await rimraf$1(tmpPath), { type: "dts", messages, results };
|
|
1018
|
-
}
|
|
1019
|
-
const dtsTask = {
|
|
1020
|
-
name: (ctx, task) => [
|
|
1021
|
-
`Build type definitions with ${chalk.bold(ctx.dts)}...`,
|
|
1022
|
-
" entries:",
|
|
1023
|
-
...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
|
|
1024
|
-
` - ${chalk.cyan(entry.importId)}: `,
|
|
1025
|
-
`${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
|
|
1026
|
-
].join("")).join(`
|
|
1027
|
-
`))
|
|
1028
|
-
].join(`
|
|
1029
|
-
`),
|
|
1030
|
-
exec: (ctx, task) => new Observable((observer) => {
|
|
1031
|
-
doExtract(ctx, task).then((result) => {
|
|
1032
|
-
observer.next(result), observer.complete();
|
|
1033
|
-
}).catch((err) => {
|
|
1034
|
-
observer.error(err);
|
|
1035
|
-
});
|
|
1036
|
-
}),
|
|
1037
|
-
complete: (ctx, _task, result) => {
|
|
1038
|
-
printExtractMessages(ctx, result.messages);
|
|
1039
|
-
},
|
|
1040
|
-
error: (ctx, _task, err) => {
|
|
1041
|
-
const { logger } = ctx;
|
|
1042
|
-
err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
|
|
1043
|
-
}
|
|
1044
|
-
}, dtsWatchTask = {
|
|
1045
|
-
name: (_ctx, task) => [
|
|
1046
|
-
"build type definitions",
|
|
1047
|
-
...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
|
|
1048
|
-
` - ${chalk.cyan(entry.importId)}: `,
|
|
1049
|
-
`${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
|
|
1050
|
-
].join("")))
|
|
1051
|
-
].join(`
|
|
1052
|
-
`),
|
|
1053
|
-
exec: (ctx, task) => {
|
|
1054
|
-
const { config: config2, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
|
|
1055
|
-
return new Observable((observer) => {
|
|
1056
|
-
if (!tsContext.config || !tsContext.configPath) {
|
|
1057
|
-
observer.next({ type: "dts", messages: [], results: [] }), observer.complete();
|
|
1058
|
-
return;
|
|
1059
|
-
}
|
|
1060
|
-
const { outDir, rootDir = cwd } = tsContext.config.options;
|
|
1061
|
-
if (!outDir) {
|
|
1062
|
-
observer.error(new Error("tsconfig.json is missing `compilerOptions.outDir`"));
|
|
1063
|
-
return;
|
|
1064
|
-
}
|
|
1065
|
-
const tmpPath = path.resolve(outDir, "__tmp__");
|
|
1066
|
-
buildTypes({
|
|
1067
|
-
cwd,
|
|
1068
|
-
logger,
|
|
1069
|
-
outDir: tmpPath,
|
|
1070
|
-
tsconfig: tsContext.config,
|
|
1071
|
-
strict
|
|
1072
|
-
}).catch((err) => {
|
|
1073
|
-
observer.error(err);
|
|
1074
|
-
});
|
|
1075
|
-
const host = ts.createWatchCompilerHost(
|
|
1076
|
-
tsContext.configPath,
|
|
1077
|
-
{
|
|
1078
|
-
...tsContext.config.options,
|
|
1079
|
-
declaration: !0,
|
|
1080
|
-
declarationDir: tmpPath,
|
|
1081
|
-
emitDeclarationOnly: !0,
|
|
1082
|
-
noEmit: !1,
|
|
1083
|
-
noEmitOnError: strict ? !0 : tsContext.config.options.noEmitOnError ?? !0,
|
|
1084
|
-
outDir: tmpPath
|
|
1085
|
-
},
|
|
1086
|
-
ts.sys,
|
|
1087
|
-
ts.createEmitAndSemanticDiagnosticsBuilderProgram,
|
|
1088
|
-
(diagnostic) => {
|
|
1089
|
-
logger.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
|
|
1090
|
-
`));
|
|
1091
|
-
},
|
|
1092
|
-
(diagnostic) => {
|
|
1093
|
-
logger.info(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
|
|
1094
|
-
`));
|
|
1095
|
-
}
|
|
1096
|
-
), origPostProgramCreate = host.afterProgramCreate;
|
|
1097
|
-
host.afterProgramCreate = async (program) => {
|
|
1098
|
-
origPostProgramCreate?.(program);
|
|
1099
|
-
const messages = [], results = [];
|
|
1100
|
-
for (const entry of task.entries) {
|
|
1101
|
-
const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path.resolve(
|
|
1102
|
-
tmpPath,
|
|
1103
|
-
path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
|
|
1104
|
-
), targetPaths = entry.targetPaths.map((targetPath) => path.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path.relative(outDir, targetPath));
|
|
1105
|
-
try {
|
|
1106
|
-
const result = await extractTypes({
|
|
1107
|
-
bundledPackages: bundledPackages || [],
|
|
1108
|
-
customTags: config2?.extract?.customTags,
|
|
1109
|
-
cwd,
|
|
1110
|
-
distPath: outDir,
|
|
1111
|
-
exportPath,
|
|
1112
|
-
files,
|
|
1113
|
-
filePaths,
|
|
1114
|
-
projectPath: cwd,
|
|
1115
|
-
rules: config2?.extract?.rules,
|
|
1116
|
-
sourceTypesPath,
|
|
1117
|
-
tsconfig: tsContext.config,
|
|
1118
|
-
tmpPath,
|
|
1119
|
-
tsconfigPath: path.resolve(cwd, tsContext.configPath || "tsconfig.json"),
|
|
1120
|
-
extractorDisabled: config2?.extract?.enabled === !1
|
|
1121
|
-
});
|
|
1122
|
-
messages.push(...result.messages), results.push({ sourcePath: path.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
|
|
1123
|
-
} catch (err) {
|
|
1124
|
-
if (err instanceof DtsError)
|
|
1125
|
-
messages.push(...err.messages);
|
|
1126
|
-
else {
|
|
1127
|
-
observer.error(err);
|
|
1128
|
-
return;
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
observer.next({ type: "dts", messages, results });
|
|
1133
|
-
};
|
|
1134
|
-
const watchProgram = ts.createWatchProgram(host);
|
|
1135
|
-
return () => {
|
|
1136
|
-
watchProgram.close(), rimraf.sync(tmpPath);
|
|
1137
|
-
};
|
|
1138
|
-
});
|
|
1139
|
-
},
|
|
1140
|
-
complete: (ctx, task, result) => {
|
|
1141
|
-
const { logger } = ctx;
|
|
1142
|
-
printExtractMessages(ctx, result.messages), logger.success(
|
|
1143
|
-
`build type definitions
|
|
1144
|
-
${task.entries.map(
|
|
1145
|
-
(entry) => ` - ${chalk.cyan(entry.importId)}: ${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(entry.targetPaths.join(", "))}`
|
|
1146
|
-
).join(`
|
|
1147
|
-
`)}`
|
|
1148
|
-
), logger.log("");
|
|
1149
|
-
},
|
|
1150
|
-
error: (ctx, _task, err) => {
|
|
1151
|
-
const { logger } = ctx;
|
|
1152
|
-
err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
|
|
1153
|
-
}
|
|
1154
|
-
};
|
|
1155
|
-
function createConsoleSpy(options) {
|
|
1156
|
-
const { onRestored } = options || {}, original = {
|
|
1157
|
-
log: console.log,
|
|
1158
|
-
warn: console.warn,
|
|
1159
|
-
error: console.error
|
|
1160
|
-
}, messages = [];
|
|
1161
|
-
return console.log = (...args) => messages.push({ type: "log", args }), console.warn = (...args) => messages.push({ type: "warn", args }), console.error = (...args) => messages.push({ type: "error", args }), {
|
|
1162
|
-
messages,
|
|
1163
|
-
restore: () => {
|
|
1164
|
-
console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
|
|
1165
|
-
}
|
|
1166
|
-
};
|
|
1167
|
-
}
|
|
1168
|
-
function resolveRolldownConfig(ctx, buildTask) {
|
|
1169
|
-
const { format: format2, runtime, target } = buildTask, { config: config2, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format2], minify = config2?.minify ?? !1, outDir = path.relative(cwd, distPath), pathAliases = Object.fromEntries(
|
|
1170
|
-
Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
|
|
1171
|
-
), entries = buildTask.entries.map((entry) => ({
|
|
1172
|
-
...entry,
|
|
1173
|
-
name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
|
|
1174
|
-
}), {}), exportIds = _exports && Object.keys(_exports).map((exportPath) => path.join(pkg.name, exportPath)), sourcePaths = _exports && Object.values(_exports).map((e) => path.resolve(cwd, e.source)), replacements = Object.fromEntries(
|
|
1175
|
-
Object.entries(config2?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
|
|
1176
|
-
), { optimizeLodash: enableOptimizeLodash = hasDependency$1(pkg, "lodash") } = config2?.rollup || {};
|
|
1177
|
-
[
|
|
1178
|
-
esbuild({
|
|
1179
|
-
target,
|
|
1180
|
-
tsconfig: ctx.ts.configPath || "tsconfig.json",
|
|
1181
|
-
treeShaking: !0,
|
|
1182
|
-
minifySyntax: config2?.minify !== !1,
|
|
1183
|
-
supported: {
|
|
1184
|
-
"template-literal": !0
|
|
1185
|
-
}
|
|
1186
|
-
}),
|
|
1187
|
-
Array.isArray(config2?.babel?.plugins) && getBabelOutputPlugin({
|
|
1188
|
-
babelrc: !1,
|
|
1189
|
-
plugins: config2.babel.plugins
|
|
1190
|
-
}),
|
|
1191
|
-
enableOptimizeLodash && optimizeLodashImports({
|
|
1192
|
-
useLodashEs: format2 === "esm" && hasDependency$1(pkg, "lodash-es") ? !0 : void 0,
|
|
1193
|
-
...typeof config2?.rollup?.optimizeLodash == "boolean" ? {} : config2?.rollup?.optimizeLodash
|
|
1194
|
-
}),
|
|
1195
|
-
minify && terser({
|
|
1196
|
-
compress: { directives: !1, passes: 10 },
|
|
1197
|
-
ecma: 2020,
|
|
1198
|
-
output: {
|
|
1199
|
-
comments: (_node, comment) => {
|
|
1200
|
-
const text = comment.value;
|
|
1201
|
-
return comment.type === "comment2" ? /@preserve|@license|@cc_on/i.test(text) : !1;
|
|
1202
|
-
},
|
|
1203
|
-
preserve_annotations: !0
|
|
1204
|
-
}
|
|
1205
|
-
})
|
|
1206
|
-
].filter(Boolean);
|
|
1207
|
-
const hashChunkFileNames = config2?.rollup?.hashChunkFileNames ?? !1, chunkFileNames = `${hashChunkFileNames ? "_chunks" : "_chunks-[format]"}/${hashChunkFileNames ? "[name]-[hash]" : "[name]"}${outputExt}`, entryFileNames = `[name]${outputExt}`, inputOptions = {
|
|
1208
|
-
cwd,
|
|
1209
|
-
jsx: {
|
|
1210
|
-
mode: config2?.jsx === "automatic" ? "automatic" : config2?.jsx === "preserve" ? "preserve" : config2?.jsx === "transform" ? "classic" : "automatic",
|
|
1211
|
-
factory: config2?.jsxFactory,
|
|
1212
|
-
fragment: config2?.jsxFragment,
|
|
1213
|
-
importSource: config2?.jsxImportSource
|
|
1214
|
-
},
|
|
1215
|
-
define: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
|
|
1216
|
-
"process.env.PKG_FORMAT": JSON.stringify(format2),
|
|
1217
|
-
"process.env.PKG_RUNTIME": JSON.stringify(runtime),
|
|
1218
|
-
"process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
|
|
1219
|
-
...replacements
|
|
1220
|
-
},
|
|
1221
|
-
platform: buildTask.type === "rolldown:dts" || runtime === "node" ? "node" : runtime === "browser" ? "browser" : "neutral",
|
|
1222
|
-
resolve: {
|
|
1223
|
-
alias: pathAliases,
|
|
1224
|
-
tsconfigFilename: ctx.ts.configPath || "tsconfig.json"
|
|
1225
|
-
},
|
|
1226
|
-
transform: {
|
|
1227
|
-
target
|
|
1228
|
-
},
|
|
1229
|
-
experimental: {
|
|
1230
|
-
attachDebugInfo: "none"
|
|
1231
|
-
},
|
|
1232
|
-
external: (id, importer) => {
|
|
1233
|
-
if (exportIds?.includes(id))
|
|
1234
|
-
return !0;
|
|
1235
|
-
if (importer && (id.startsWith(".") || id.startsWith("/"))) {
|
|
1236
|
-
const idPath = path.resolve(path.dirname(importer), id);
|
|
1237
|
-
if (sourcePaths?.includes(idPath))
|
|
1238
|
-
return logger.warn(
|
|
1239
|
-
`detected self-referencing import \u2013 treating as external: ${path.relative(
|
|
1240
|
-
cwd,
|
|
1241
|
-
idPath
|
|
1242
|
-
)}`
|
|
1243
|
-
), !0;
|
|
1244
|
-
}
|
|
1245
|
-
const idParts = id.split("/"), name = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0];
|
|
1246
|
-
return !!(name && external.includes(name));
|
|
1247
|
-
},
|
|
1248
|
-
input: entries.reduce(
|
|
1249
|
-
(acc, entry) => Object.assign(acc, { [entry.name]: entry.source }),
|
|
1250
|
-
{}
|
|
1251
|
-
),
|
|
1252
|
-
plugins: [dts({ emitDtsOnly: !0, tsconfig: ctx.ts.configPath || "tsconfig.json" })],
|
|
1253
|
-
treeshake: !0
|
|
1254
|
-
}, outputOptions = {
|
|
1255
|
-
chunkFileNames,
|
|
1256
|
-
dir: outDir,
|
|
1257
|
-
entryFileNames,
|
|
1258
|
-
esModule: !0,
|
|
1259
|
-
format: buildTask.type === "rolldown:dts" ? "es" : format2,
|
|
1260
|
-
sourcemap: buildTask.type === "rolldown:dts" ? !1 : config2?.sourcemap ?? !0,
|
|
1261
|
-
hoistTransitiveImports: !1
|
|
1262
|
-
};
|
|
1263
|
-
return { inputOptions, outputOptions };
|
|
1264
|
-
}
|
|
1265
|
-
function hasDependency$1(pkg, packageName) {
|
|
1266
|
-
return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
|
|
1267
|
-
}
|
|
1268
|
-
const rolldownDtsTask = {
|
|
1269
|
-
name: (ctx, task) => {
|
|
1270
|
-
const bundleEntries = task.entries.filter((e) => e.path.includes("__$$bundle_")), entries = task.entries.filter((e) => !e.path.includes("__$$bundle_")), targetLines = task.target.length ? [" target:", ...task.target.map((t) => ` - ${chalk.yellow(t)}`)] : [], bundlesLines = bundleEntries.length ? [
|
|
1271
|
-
" bundles:",
|
|
1272
|
-
...bundleEntries.map(
|
|
1273
|
-
(e) => [
|
|
1274
|
-
" - ",
|
|
1275
|
-
`${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
|
|
1276
|
-
].join("")
|
|
1277
|
-
)
|
|
1278
|
-
] : [], entriesLines = entries.length ? [
|
|
1279
|
-
" entries:",
|
|
1280
|
-
...entries.map(
|
|
1281
|
-
(e) => [
|
|
1282
|
-
" - ",
|
|
1283
|
-
`${chalk.cyan(path.join(ctx.pkg.name, e.path))}: `,
|
|
1284
|
-
`${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
|
|
1285
|
-
].join("")
|
|
1286
|
-
)
|
|
1287
|
-
] : [];
|
|
1288
|
-
return [
|
|
1289
|
-
`Build type definitions with ${chalk.bold("rolldown")}...`,
|
|
1290
|
-
` format: ${chalk.yellow(task.format)}`,
|
|
1291
|
-
...targetLines,
|
|
1292
|
-
...bundlesLines,
|
|
1293
|
-
...entriesLines
|
|
1294
|
-
].join(`
|
|
1295
|
-
`);
|
|
1296
|
-
},
|
|
1297
|
-
exec: (ctx, task) => from(execPromise$1(ctx, task)),
|
|
1298
|
-
complete: () => {
|
|
1299
|
-
},
|
|
1300
|
-
error: (_ctx, _task, err) => {
|
|
1301
|
-
console.error(err);
|
|
1302
|
-
}
|
|
1303
|
-
};
|
|
1304
|
-
async function execPromise$1(ctx, task) {
|
|
1305
|
-
const { distPath, files, logger } = ctx, outDir = path.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
|
|
1306
|
-
onRestored: (messages) => {
|
|
1307
|
-
for (const msg of messages) {
|
|
1308
|
-
const text = String(msg.args[0]);
|
|
1309
|
-
msg.code !== "CIRCULAR_DEPENDENCY" && (text.startsWith("Dynamic import can only") || text.startsWith("Sourcemap is likely to be incorrect") || (msg.type === "log" && logger.info(...msg.args), msg.type === "warn" && logger.warn(...msg.args), msg.type === "error" && logger.error(...msg.args)));
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
});
|
|
1313
|
-
try {
|
|
1314
|
-
const { inputOptions, outputOptions } = resolveRolldownConfig(ctx, task), bundle = await rolldown({
|
|
1315
|
-
...inputOptions,
|
|
1316
|
-
onwarn(warning) {
|
|
1317
|
-
consoleSpy.messages.push({
|
|
1318
|
-
type: "warn",
|
|
1319
|
-
code: warning.code,
|
|
1320
|
-
args: [warning.message]
|
|
1321
|
-
});
|
|
1322
|
-
}
|
|
1323
|
-
}), { output } = await bundle.generate(outputOptions);
|
|
1324
|
-
for (const chunkOrAsset of output)
|
|
1325
|
-
chunkOrAsset.type === "asset" ? files.push({
|
|
1326
|
-
type: "asset",
|
|
1327
|
-
path: path.resolve(outDir, chunkOrAsset.fileName)
|
|
1328
|
-
}) : files.push({
|
|
1329
|
-
type: "chunk",
|
|
1330
|
-
path: path.resolve(outDir, chunkOrAsset.fileName)
|
|
1331
|
-
});
|
|
1332
|
-
await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
|
|
1333
|
-
} catch (err) {
|
|
1334
|
-
throw consoleSpy.restore(), err;
|
|
1335
|
-
}
|
|
1336
|
-
}
|
|
1337
|
-
function resolveRollupConfig(ctx, buildTask) {
|
|
1338
|
-
const { format: format2, runtime, target } = buildTask, { config: config2, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format2], minify = config2?.minify ?? !1, outDir = path.relative(cwd, distPath), pathAliases = Object.fromEntries(
|
|
1339
|
-
Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
|
|
1340
|
-
), entries = buildTask.entries.map((entry) => ({
|
|
1341
|
-
...entry,
|
|
1342
|
-
name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
|
|
1343
|
-
}), {}), exportIds = _exports && Object.keys(_exports).map((exportPath) => path.join(pkg.name, exportPath)), sourcePaths = _exports && Object.values(_exports).map((e) => path.resolve(cwd, e.source)), replacements = Object.fromEntries(
|
|
1344
|
-
Object.entries(config2?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
|
|
1345
|
-
), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config2?.rollup || {}, defaultPlugins = [
|
|
1346
|
-
replace({
|
|
1347
|
-
preventAssignment: !0,
|
|
1348
|
-
values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
|
|
1349
|
-
"process.env.PKG_FILE_PATH": (arg) => {
|
|
1350
|
-
const sourcePath = `./${path.relative(cwd, arg)}`, entry = entries.find((e) => e.source === sourcePath);
|
|
1351
|
-
return entry ? JSON.stringify(
|
|
1352
|
-
path.relative(cwd, path.resolve(outDir, entry.name + outputExt))
|
|
1353
|
-
) : (console.error(`could not find source entry: ${sourcePath}`), "null");
|
|
1354
|
-
},
|
|
1355
|
-
"process.env.PKG_FORMAT": JSON.stringify(format2),
|
|
1356
|
-
"process.env.PKG_RUNTIME": JSON.stringify(runtime),
|
|
1357
|
-
"process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
|
|
1358
|
-
...replacements
|
|
1359
|
-
}
|
|
1360
|
-
}),
|
|
1361
|
-
alias({
|
|
1362
|
-
entries: { ...pathAliases }
|
|
1363
|
-
}),
|
|
1364
|
-
nodeResolve({
|
|
1365
|
-
browser: runtime === "browser",
|
|
1366
|
-
extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
|
|
1367
|
-
preferBuiltins: !0
|
|
1368
|
-
}),
|
|
1369
|
-
commonjs(),
|
|
1370
|
-
json(),
|
|
1371
|
-
(config2?.babel?.reactCompiler || config2?.babel?.styledComponents) && babel({
|
|
1372
|
-
babelrc: !1,
|
|
1373
|
-
presets: ["@babel/preset-typescript"],
|
|
1374
|
-
babelHelpers: "bundled",
|
|
1375
|
-
extensions: [".ts", ".tsx", ".js", ".jsx"],
|
|
1376
|
-
plugins: [
|
|
1377
|
-
// The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
|
|
1378
|
-
config2?.babel?.styledComponents && [
|
|
1379
|
-
"babel-plugin-styled-components",
|
|
1380
|
-
{
|
|
1381
|
-
// Unnecessary, as the way we use styled-components in Sanity is usually by wrapping `@sanity/ui` primitives, not declaring new ones like "const Button = styled.button``"
|
|
1382
|
-
fileName: !1,
|
|
1383
|
-
// Native template literals take less space than this transpilation
|
|
1384
|
-
transpileTemplateLiterals: !1,
|
|
1385
|
-
// Massively helps dead code elimination and tree-shaking
|
|
1386
|
-
pure: !0,
|
|
1387
|
-
// disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
|
|
1388
|
-
cssProp: !1,
|
|
1389
|
-
...typeof config2.babel.styledComponents == "object" ? config2.babel.styledComponents : {}
|
|
1390
|
-
}
|
|
1391
|
-
],
|
|
1392
|
-
config2?.babel?.reactCompiler && [
|
|
1393
|
-
"babel-plugin-react-compiler",
|
|
1394
|
-
config2?.reactCompilerOptions || {}
|
|
1395
|
-
]
|
|
1396
|
-
].filter(Boolean)
|
|
1397
|
-
}),
|
|
1398
|
-
esbuild({
|
|
1399
|
-
jsx: config2?.jsx ?? "automatic",
|
|
1400
|
-
jsxFactory: config2?.jsxFactory ?? "createElement",
|
|
1401
|
-
jsxFragment: config2?.jsxFragment ?? "Fragment",
|
|
1402
|
-
jsxImportSource: config2?.jsxImportSource ?? "react",
|
|
1403
|
-
target,
|
|
1404
|
-
tsconfig: ctx.ts.configPath || "tsconfig.json",
|
|
1405
|
-
treeShaking: !0,
|
|
1406
|
-
minifySyntax: config2?.minify !== !1,
|
|
1407
|
-
supported: {
|
|
1408
|
-
"template-literal": !0
|
|
1409
|
-
}
|
|
1410
|
-
}),
|
|
1411
|
-
Array.isArray(config2?.babel?.plugins) && getBabelOutputPlugin({
|
|
1412
|
-
babelrc: !1,
|
|
1413
|
-
plugins: config2.babel.plugins
|
|
1414
|
-
}),
|
|
1415
|
-
enableOptimizeLodash && optimizeLodashImports({
|
|
1416
|
-
useLodashEs: format2 === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
|
|
1417
|
-
...typeof config2?.rollup?.optimizeLodash == "boolean" ? {} : config2?.rollup?.optimizeLodash
|
|
1418
|
-
}),
|
|
1419
|
-
minify && terser({
|
|
1420
|
-
compress: { directives: !1, passes: 10 },
|
|
1421
|
-
ecma: 2020,
|
|
1422
|
-
output: {
|
|
1423
|
-
comments: (_node, comment) => {
|
|
1424
|
-
const text = comment.value;
|
|
1425
|
-
return comment.type === "comment2" ? /@preserve|@license|@cc_on/i.test(text) : !1;
|
|
1426
|
-
},
|
|
1427
|
-
preserve_annotations: !0
|
|
1428
|
-
}
|
|
1429
|
-
})
|
|
1430
|
-
].filter(Boolean), userPlugins = config2?.rollup?.plugins, plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty(config2?.rollup?.plugins, defaultPlugins), hashChunkFileNames = config2?.rollup?.hashChunkFileNames ?? !1, chunkFileNames = `${hashChunkFileNames ? "_chunks" : "_chunks-[format]"}/${hashChunkFileNames ? "[name]-[hash]" : "[name]"}${outputExt}`, entryFileNames = `[name]${outputExt}`;
|
|
1431
|
-
return {
|
|
1432
|
-
inputOptions: {
|
|
1433
|
-
context: cwd,
|
|
1434
|
-
external: (id, importer) => {
|
|
1435
|
-
if (exportIds?.includes(id))
|
|
1436
|
-
return !0;
|
|
1437
|
-
if (importer && (id.startsWith(".") || id.startsWith("/"))) {
|
|
1438
|
-
const idPath = path.resolve(path.dirname(importer), id);
|
|
1439
|
-
if (sourcePaths?.includes(idPath))
|
|
1440
|
-
return logger.warn(
|
|
1441
|
-
`detected self-referencing import \u2013 treating as external: ${path.relative(
|
|
1442
|
-
cwd,
|
|
1443
|
-
idPath
|
|
1444
|
-
)}`
|
|
1445
|
-
), !0;
|
|
1446
|
-
}
|
|
1447
|
-
const idParts = id.split("/"), name = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0];
|
|
1448
|
-
return !!(name && external.includes(name));
|
|
1449
|
-
},
|
|
1450
|
-
input: entries.reduce(
|
|
1451
|
-
(acc, entry) => Object.assign(acc, { [entry.name]: entry.source }),
|
|
1452
|
-
{}
|
|
1453
|
-
),
|
|
1454
|
-
watch: {
|
|
1455
|
-
chokidar: {
|
|
1456
|
-
usePolling: !0
|
|
1457
|
-
}
|
|
1458
|
-
},
|
|
1459
|
-
plugins,
|
|
1460
|
-
treeshake: {
|
|
1461
|
-
preset: "recommended",
|
|
1462
|
-
propertyReadSideEffects: !1,
|
|
1463
|
-
moduleSideEffects: "no-external",
|
|
1464
|
-
...config2?.rollup?.treeshake
|
|
1465
|
-
},
|
|
1466
|
-
experimentalLogSideEffects: config2?.rollup?.experimentalLogSideEffects
|
|
1467
|
-
},
|
|
1468
|
-
outputOptions: {
|
|
1469
|
-
chunkFileNames,
|
|
1470
|
-
compact: minify,
|
|
1471
|
-
dir: outDir,
|
|
1472
|
-
entryFileNames,
|
|
1473
|
-
esModule: !0,
|
|
1474
|
-
format: format2,
|
|
1475
|
-
interop: "compat",
|
|
1476
|
-
sourcemap: config2?.sourcemap ?? !0,
|
|
1477
|
-
hoistTransitiveImports: !1,
|
|
1478
|
-
minifyInternalExports: minify,
|
|
1479
|
-
...config2?.rollup?.output
|
|
1480
|
-
}
|
|
1481
|
-
};
|
|
1482
|
-
}
|
|
1483
|
-
function hasDependency(pkg, packageName) {
|
|
1484
|
-
return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
|
|
1485
|
-
}
|
|
1486
|
-
const rollupTask = {
|
|
1487
|
-
name: (ctx, task) => {
|
|
1488
|
-
const bundleEntries = task.entries.filter((e) => e.path.includes("__$$bundle_")), entries = task.entries.filter((e) => !e.path.includes("__$$bundle_")), targetLines = task.target.length ? [" target:", ...task.target.map((t) => ` - ${chalk.yellow(t)}`)] : [], bundlesLines = bundleEntries.length ? [
|
|
1489
|
-
" bundles:",
|
|
1490
|
-
...bundleEntries.map(
|
|
1491
|
-
(e) => [
|
|
1492
|
-
" - ",
|
|
1493
|
-
`${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
|
|
1494
|
-
].join("")
|
|
1495
|
-
)
|
|
1496
|
-
] : [], entriesLines = entries.length ? [
|
|
1497
|
-
" entries:",
|
|
1498
|
-
...entries.map(
|
|
1499
|
-
(e) => [
|
|
1500
|
-
" - ",
|
|
1501
|
-
`${chalk.cyan(path.join(ctx.pkg.name, e.path))}: `,
|
|
1502
|
-
`${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
|
|
1503
|
-
].join("")
|
|
1504
|
-
)
|
|
1505
|
-
] : [];
|
|
1506
|
-
return [
|
|
1507
|
-
"Build javascript files...",
|
|
1508
|
-
` format: ${chalk.yellow(task.format)}`,
|
|
1509
|
-
...targetLines,
|
|
1510
|
-
...bundlesLines,
|
|
1511
|
-
...entriesLines
|
|
1512
|
-
].join(`
|
|
1513
|
-
`);
|
|
1514
|
-
},
|
|
1515
|
-
exec: (ctx, task) => new Observable((observer) => {
|
|
1516
|
-
execPromise(ctx, task).then((result) => {
|
|
1517
|
-
observer.next(result), observer.complete();
|
|
1518
|
-
}).catch((err) => observer.error(err));
|
|
1519
|
-
}),
|
|
1520
|
-
complete: () => {
|
|
1521
|
-
},
|
|
1522
|
-
error: (_ctx, _task, err) => {
|
|
1523
|
-
console.error(err);
|
|
1524
|
-
}
|
|
1525
|
-
};
|
|
1526
|
-
async function execPromise(ctx, task) {
|
|
1527
|
-
const { distPath, files, logger } = ctx, outDir = path.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
|
|
1528
|
-
onRestored: (messages) => {
|
|
1529
|
-
for (const msg of messages) {
|
|
1530
|
-
const text = String(msg.args[0]);
|
|
1531
|
-
msg.code !== "CIRCULAR_DEPENDENCY" && (text.startsWith("Dynamic import can only") || text.startsWith("Sourcemap is likely to be incorrect") || (msg.type === "log" && logger.info(...msg.args), msg.type === "warn" && logger.warn(...msg.args), msg.type === "error" && logger.error(...msg.args)));
|
|
1532
|
-
}
|
|
1533
|
-
}
|
|
1534
|
-
});
|
|
1535
|
-
try {
|
|
1536
|
-
const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task), bundle = await rollup({
|
|
1537
|
-
...inputOptions,
|
|
1538
|
-
onwarn(warning) {
|
|
1539
|
-
consoleSpy.messages.push({
|
|
1540
|
-
type: "warn",
|
|
1541
|
-
code: warning.code,
|
|
1542
|
-
args: [warning.message]
|
|
1543
|
-
});
|
|
1544
|
-
}
|
|
1545
|
-
}), { output } = await bundle.generate(outputOptions);
|
|
1546
|
-
for (const chunkOrAsset of output)
|
|
1547
|
-
chunkOrAsset.type === "asset" ? files.push({
|
|
1548
|
-
type: "asset",
|
|
1549
|
-
path: path.resolve(outDir, chunkOrAsset.fileName)
|
|
1550
|
-
}) : files.push({
|
|
1551
|
-
type: "chunk",
|
|
1552
|
-
path: path.resolve(outDir, chunkOrAsset.fileName)
|
|
1553
|
-
});
|
|
1554
|
-
await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
|
|
1555
|
-
} catch (err) {
|
|
1556
|
-
throw consoleSpy.restore(), err;
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
const rollupWatchTask = {
|
|
1560
|
-
name: (ctx, task) => `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
|
|
1561
|
-
${task.entries.map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
|
|
1562
|
-
`)}`,
|
|
1563
|
-
exec: (ctx, task) => {
|
|
1564
|
-
const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task);
|
|
1565
|
-
return new Observable((observer) => {
|
|
1566
|
-
const watchOptions = {
|
|
1567
|
-
...inputOptions,
|
|
1568
|
-
output: outputOptions
|
|
1569
|
-
}, watcher = watch$1(watchOptions);
|
|
1570
|
-
return watcher.on("event", (event) => {
|
|
1571
|
-
observer.next(event);
|
|
1572
|
-
}), () => {
|
|
1573
|
-
watcher.close();
|
|
1574
|
-
};
|
|
1575
|
-
});
|
|
1576
|
-
},
|
|
1577
|
-
complete: (ctx, task, event) => {
|
|
1578
|
-
const { logger } = ctx;
|
|
1579
|
-
if (event.code === "BUNDLE_END") {
|
|
1580
|
-
logger.success(
|
|
1581
|
-
`build javascript files (target ${task.target.join(" + ")}, format ${task.format})
|
|
1582
|
-
${task.entries.map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
|
|
1583
|
-
`)}`
|
|
1584
|
-
), logger.log("");
|
|
1585
|
-
return;
|
|
1586
|
-
}
|
|
1587
|
-
if (event.code !== "BUNDLE_START" && event.code !== "END" && event.code === "ERROR") {
|
|
1588
|
-
logger.error(event.code, event);
|
|
1589
|
-
return;
|
|
1590
|
-
}
|
|
1591
|
-
},
|
|
1592
|
-
error: (ctx, _task, err) => {
|
|
1593
|
-
const { logger } = ctx;
|
|
1594
|
-
err instanceof Error && logger.log(err);
|
|
1595
|
-
}
|
|
1596
|
-
}, buildTaskHandlers = {
|
|
1597
|
-
"build:dts": dtsTask,
|
|
1598
|
-
"build:js": rollupTask,
|
|
1599
|
-
"rolldown:dts": rolldownDtsTask
|
|
1600
|
-
}, watchTaskHandlers = {
|
|
1601
|
-
"watch:dts": dtsWatchTask,
|
|
1602
|
-
"watch:js": rollupWatchTask
|
|
1603
|
-
};
|
|
1604
|
-
async function build(options) {
|
|
1605
|
-
const {
|
|
1606
|
-
cwd,
|
|
1607
|
-
emitDeclarationOnly,
|
|
1608
|
-
strict = !1,
|
|
1609
|
-
tsconfig: tsconfigOption,
|
|
1610
|
-
clean = !1
|
|
1611
|
-
} = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({
|
|
1612
|
-
config: config2,
|
|
1613
|
-
cwd,
|
|
1614
|
-
emitDeclarationOnly,
|
|
1615
|
-
logger,
|
|
1616
|
-
pkg,
|
|
1617
|
-
strict,
|
|
1618
|
-
tsconfig
|
|
1619
|
-
});
|
|
1620
|
-
clean && (logger.log(
|
|
1621
|
-
`Deleting the \`dist\` folder: './${path.relative(cwd, ctx.distPath)}' before building...`
|
|
1622
|
-
), await rimraf$1(ctx.distPath));
|
|
1623
|
-
const buildTasks = resolveBuildTasks(ctx);
|
|
1624
|
-
for (const task of buildTasks) {
|
|
1625
|
-
const handler = buildTaskHandlers[task.type], taskName = handler.name(ctx, task), spinner = createSpinner(taskName);
|
|
1626
|
-
try {
|
|
1627
|
-
const result = await handler.exec(ctx, task).toPromise();
|
|
1628
|
-
spinner.complete(), ctx.logger.log(), handler.complete(ctx, task, result);
|
|
1629
|
-
} catch (err) {
|
|
1630
|
-
if (spinner.error(), err instanceof Error) {
|
|
1631
|
-
const RE_CWD = new RegExp(`${cwd}`, "g");
|
|
1632
|
-
ctx.logger.error(err.message.replace(RE_CWD, ".")), ctx.logger.log();
|
|
1633
|
-
}
|
|
1634
|
-
handler.error(ctx, task, err), process.exit(1);
|
|
1635
|
-
}
|
|
1636
|
-
}
|
|
1637
|
-
}
|
|
1638
|
-
function getFilesize(file) {
|
|
1639
|
-
const stats = statSync(file);
|
|
1640
|
-
return prettyBytes(stats.size);
|
|
1641
|
-
}
|
|
1642
|
-
function getFileInfo(cwd, filePath) {
|
|
1643
|
-
const p = path.resolve(cwd, filePath), exists = fileExists(p), size = exists ? getFilesize(p) : void 0;
|
|
1644
|
-
return { exists, size };
|
|
1645
|
-
}
|
|
1646
|
-
function printPackageTree(ctx) {
|
|
1647
|
-
const { cwd, exports, logger, pkg } = ctx;
|
|
1648
|
-
if (!exports) return;
|
|
1649
|
-
logger.log(`${chalk.blue(pkg.name)}@${chalk.green(pkg.version)}`);
|
|
1650
|
-
const tree = {};
|
|
1651
|
-
pkg.type && (tree.type = chalk.yellow(pkg.type)), pkg.bin && (tree.bin = Object.fromEntries(
|
|
1652
|
-
Object.entries(pkg.bin).map(([name, file]) => [chalk.cyan(name), fileInfo(file)])
|
|
1653
|
-
));
|
|
1654
|
-
function fileInfo(file) {
|
|
1655
|
-
const info = getFileInfo(cwd, file);
|
|
1656
|
-
return info.size ? `${chalk.yellow(file)} ${chalk.gray(info.size)}` : `${chalk.gray(file)} ${chalk.red("does not exist")}`;
|
|
1657
|
-
}
|
|
1658
|
-
tree.exports = Object.fromEntries(
|
|
1659
|
-
Object.entries(exports).filter(([, entry]) => entry._exported).map(([exportPath, entry]) => {
|
|
1660
|
-
const exp = {
|
|
1661
|
-
source: fileInfo(entry.source),
|
|
1662
|
-
browser: void 0,
|
|
1663
|
-
require: void 0,
|
|
1664
|
-
node: void 0,
|
|
1665
|
-
import: void 0,
|
|
1666
|
-
default: fileInfo(entry.default)
|
|
1667
|
-
};
|
|
1668
|
-
return entry.browser ? (exp.browser = { source: fileInfo(entry.browser.source) }, entry.browser.import && (exp.browser.import = fileInfo(entry.browser.import)), entry.browser.require && (exp.browser.require = fileInfo(entry.browser.require))) : delete exp.browser, entry.require ? exp.require = fileInfo(entry.require) : delete exp.require, entry.node ? (exp.node = {}, entry.node.source && (exp.node.source = fileInfo(entry.node.source)), entry.node.import && (exp.node.import = fileInfo(entry.node.import)), entry.node.require && (exp.node.require = fileInfo(entry.node.require))) : delete exp.node, entry.import ? exp.import = fileInfo(entry.import) : delete exp.import, [chalk.cyan(path.join(pkg.name, exportPath)), exp];
|
|
1669
|
-
})
|
|
1670
|
-
), logger.log(treeify.asTree(tree, !0, !0));
|
|
1671
|
-
}
|
|
1672
|
-
async function check(options) {
|
|
1673
|
-
const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({ config: config2, cwd, logger, pkg, strict, tsconfig });
|
|
1674
|
-
if (printPackageTree(ctx), strict) {
|
|
1675
|
-
const missingFiles = [];
|
|
1676
|
-
for (const [, exp] of Object.entries(ctx.exports || {}))
|
|
1677
|
-
exp.source && !fileExists(path.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !fileExists(path.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !fileExists(path.resolve(cwd, exp.import)) && missingFiles.push(exp.import);
|
|
1678
|
-
ctx.pkg.types && !fileExists(path.resolve(cwd, ctx.pkg.types)) && missingFiles.push(ctx.pkg.types), missingFiles.length && (logger.error(`missing files: ${missingFiles.join(", ")}`), process.exit(1));
|
|
1679
|
-
const exportPaths = {
|
|
1680
|
-
require: [],
|
|
1681
|
-
import: []
|
|
1682
|
-
};
|
|
1683
|
-
for (const exp of Object.values(ctx.exports || {}))
|
|
1684
|
-
exp._exported && (exp.require && exportPaths.require.push(exp.require), exp.import && exportPaths.import.push(exp.import));
|
|
1685
|
-
const external = [
|
|
1686
|
-
...Object.keys(pkg.dependencies || {}),
|
|
1687
|
-
...Object.keys(pkg.devDependencies || {})
|
|
1688
|
-
], consoleSpy = createConsoleSpy();
|
|
1689
|
-
exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger }), exportPaths.require.length && checkExports(exportPaths.require, { cwd, external, format: "cjs", logger }), consoleSpy.restore();
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
async function checkExports(exportPaths, options) {
|
|
1693
|
-
const { cwd, external, format: format2, logger } = options, code = exportPaths.map((id) => format2 ? `import('${id}');` : `require('${id}');`).join(`
|
|
1694
|
-
`);
|
|
1695
|
-
try {
|
|
1696
|
-
const esbuildResult = await esbuild$1.build({
|
|
1697
|
-
bundle: !0,
|
|
1698
|
-
external,
|
|
1699
|
-
format: format2,
|
|
1700
|
-
logLevel: "silent",
|
|
1701
|
-
// otherwise output maps to stdout as we're using stdin
|
|
1702
|
-
outfile: "/dev/null",
|
|
1703
|
-
platform: "node",
|
|
1704
|
-
stdin: {
|
|
1705
|
-
contents: code,
|
|
1706
|
-
loader: "js",
|
|
1707
|
-
resolveDir: cwd
|
|
1708
|
-
}
|
|
1709
|
-
});
|
|
1710
|
-
if (esbuildResult.errors.length > 0) {
|
|
1711
|
-
for (const msg of esbuildResult.errors)
|
|
1712
|
-
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
1713
|
-
process.exit(1);
|
|
1714
|
-
}
|
|
1715
|
-
const esbuildWarnings = esbuildResult.warnings.filter((msg) => {
|
|
1716
|
-
(msg.detail || msg.text).includes("does not affect esbuild's own target setting");
|
|
1717
|
-
});
|
|
1718
|
-
for (const msg of esbuildWarnings)
|
|
1719
|
-
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
1720
|
-
} catch (err) {
|
|
1721
|
-
if (isEsbuildFailure(err)) {
|
|
1722
|
-
const { errors } = err;
|
|
1723
|
-
for (const msg of errors)
|
|
1724
|
-
printEsbuildMessage(logger.error, msg), logger.log();
|
|
1725
|
-
} else err instanceof Error ? (logger.error(err.stack || err.message), logger.log()) : (logger.error(`${err}`), logger.log());
|
|
1726
|
-
process.exit(1);
|
|
1727
|
-
}
|
|
1728
|
-
}
|
|
1729
|
-
function printEsbuildMessage(log, msg) {
|
|
1730
|
-
msg.location ? log(
|
|
1731
|
-
[
|
|
1732
|
-
`${msg.detail || msg.text}
|
|
1733
|
-
`,
|
|
1734
|
-
`${msg.location.line} | ${msg.location.lineText}
|
|
1735
|
-
`,
|
|
1736
|
-
`in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`
|
|
1737
|
-
].join("")
|
|
1738
|
-
) : log(msg.detail || msg.text);
|
|
1739
|
-
}
|
|
1740
|
-
function isEsbuildFailure(err) {
|
|
1741
|
-
return err instanceof Error && "errors" in err && Array.isArray(err.errors) && err.errors.every(isEsbuildMessage) && "warnings" in err && Array.isArray(err.warnings) && err.warnings.every(isEsbuildMessage);
|
|
1742
|
-
}
|
|
1743
|
-
function isEsbuildMessage(msg) {
|
|
1744
|
-
return typeof msg == "object" && msg !== null && "text" in msg && typeof msg.text == "string" && "location" in msg && (msg.location === null || typeof msg.location == "object");
|
|
1745
|
-
}
|
|
1746
|
-
function defineConfig(configOptions) {
|
|
1747
|
-
return configOptions;
|
|
1748
|
-
}
|
|
1749
|
-
function defineTemplateOption(option) {
|
|
1750
|
-
return option;
|
|
1751
|
-
}
|
|
1752
|
-
const promptsTypes = {
|
|
1753
|
-
string: "text"
|
|
1754
|
-
};
|
|
1755
|
-
async function createFromTemplate(options) {
|
|
1756
|
-
const { cwd, logger, packagePath, template: templateOrResolver } = options, template = typeof templateOrResolver == "function" ? await templateOrResolver({ cwd, logger, packagePath }) : templateOrResolver;
|
|
1757
|
-
logger.log("create new package at", relative(cwd, packagePath));
|
|
1758
|
-
const templateOptions = {};
|
|
1759
|
-
for (const templateOption of template.options) {
|
|
1760
|
-
const templateValidate = templateOption.validate, res = await prompts(
|
|
1761
|
-
{
|
|
1762
|
-
type: promptsTypes[templateOption.type],
|
|
1763
|
-
name: templateOption.name,
|
|
1764
|
-
message: templateOption.description,
|
|
1765
|
-
validate: templateValidate ? (prev) => templateValidate(prev) : void 0,
|
|
1766
|
-
initial: typeof templateOption.initial == "function" ? templateOption.initial(templateOptions) : templateOption.initial
|
|
1767
|
-
},
|
|
1768
|
-
{ onCancel: () => process.exit(0) }
|
|
1769
|
-
);
|
|
1770
|
-
templateOptions[templateOption.name] = templateOption.parse ? templateOption.parse(res[templateOption.name]) : res[templateOption.name];
|
|
1771
|
-
}
|
|
1772
|
-
const features = {};
|
|
1773
|
-
for (const templateFeature of template.features) {
|
|
1774
|
-
const res = templateFeature.optional ? await prompts(
|
|
1775
|
-
{
|
|
1776
|
-
type: "confirm",
|
|
1777
|
-
name: "confirm",
|
|
1778
|
-
message: `use ${templateFeature.name}?`,
|
|
1779
|
-
initial: templateFeature.initial
|
|
1780
|
-
},
|
|
1781
|
-
{ onCancel: () => process.exit(0) }
|
|
1782
|
-
) : void 0;
|
|
1783
|
-
features[templateFeature.name] = res?.confirm || !templateFeature.optional;
|
|
1784
|
-
}
|
|
1785
|
-
const files = await template.getFiles(templateOptions, features);
|
|
1786
|
-
files.sort((a, b) => a.name.localeCompare(b.name));
|
|
1787
|
-
for (const file of files) {
|
|
1788
|
-
const filePath = resolve(packagePath, file.name);
|
|
1789
|
-
await mkdirp(dirname(filePath)), await writeFile(filePath, file.contents.trim() + `
|
|
1790
|
-
`), logger.success(`wrote ${relative(cwd, filePath)}`);
|
|
1791
|
-
}
|
|
1792
|
-
}
|
|
1793
|
-
async function isEmptyDirectory(dirPath) {
|
|
1794
|
-
return (await readdir(dirPath)).length === 0;
|
|
1795
|
-
}
|
|
1796
|
-
const overridableDefaults = {
|
|
1797
|
-
endOfLine: "lf",
|
|
1798
|
-
tabWidth: 2,
|
|
1799
|
-
useTabs: !1
|
|
1800
|
-
}, config = {
|
|
1801
|
-
...overridableDefaults,
|
|
1802
|
-
printWidth: 100,
|
|
1803
|
-
semi: !1,
|
|
1804
|
-
singleQuote: !0,
|
|
1805
|
-
quoteProps: "consistent",
|
|
1806
|
-
bracketSpacing: !1,
|
|
1807
|
-
plugins: ["prettier-plugin-packagejson"],
|
|
1808
|
-
overrides: [
|
|
1809
|
-
{
|
|
1810
|
-
files: ["*.json5"],
|
|
1811
|
-
options: {
|
|
1812
|
-
quoteProps: "preserve",
|
|
1813
|
-
singleQuote: !1
|
|
1814
|
-
}
|
|
1815
|
-
},
|
|
1816
|
-
{
|
|
1817
|
-
files: ["*.yml"],
|
|
1818
|
-
options: {
|
|
1819
|
-
singleQuote: !1
|
|
1820
|
-
}
|
|
1821
|
-
}
|
|
1822
|
-
]
|
|
1823
|
-
}, RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i, defaultTemplate = async ({ cwd, logger, packagePath }) => {
|
|
1824
|
-
const gitConfig = getGitUserConfig(cwd);
|
|
1825
|
-
return {
|
|
1826
|
-
options: [
|
|
1827
|
-
{
|
|
1828
|
-
name: "repo",
|
|
1829
|
-
type: "string",
|
|
1830
|
-
description: "git url",
|
|
1831
|
-
validate: (v) => {
|
|
1832
|
-
if (!v) return !0;
|
|
1833
|
-
try {
|
|
1834
|
-
return gitUrlParse(v), !0;
|
|
1835
|
-
} catch {
|
|
1836
|
-
return "invalid git url";
|
|
1837
|
-
}
|
|
1838
|
-
},
|
|
1839
|
-
parse: (v) => {
|
|
1840
|
-
if (!v) return null;
|
|
1841
|
-
const result = gitUrlParse(v);
|
|
1842
|
-
return { source: result.source, owner: result.owner, name: result.name };
|
|
1843
|
-
}
|
|
1844
|
-
},
|
|
1845
|
-
{
|
|
1846
|
-
name: "pkgName",
|
|
1847
|
-
type: "string",
|
|
1848
|
-
description: "package name",
|
|
1849
|
-
initial: (options) => options.repo?.name || void 0,
|
|
1850
|
-
validate: (v) => v ? RE_NAME.exec(v) ? !0 : "invalid package name" : "package name is required",
|
|
1851
|
-
parse: (v) => {
|
|
1852
|
-
if (!v)
|
|
1853
|
-
throw new Error("package name is required");
|
|
1854
|
-
if (!RE_NAME.exec(v))
|
|
1855
|
-
throw new Error("invalid package name");
|
|
1856
|
-
const [scope, name] = v.split("/");
|
|
1857
|
-
return { scope, name, fullName: v };
|
|
1858
|
-
}
|
|
1859
|
-
},
|
|
1860
|
-
{
|
|
1861
|
-
name: "description",
|
|
1862
|
-
type: "string",
|
|
1863
|
-
description: "package description"
|
|
1864
|
-
},
|
|
1865
|
-
{
|
|
1866
|
-
name: "authorName",
|
|
1867
|
-
type: "string",
|
|
1868
|
-
description: "package author name",
|
|
1869
|
-
initial: gitConfig.user
|
|
1870
|
-
},
|
|
1871
|
-
{
|
|
1872
|
-
name: "authorEmail",
|
|
1873
|
-
type: "string",
|
|
1874
|
-
description: "package author email",
|
|
1875
|
-
initial: gitConfig.email
|
|
1876
|
-
},
|
|
1877
|
-
{
|
|
1878
|
-
name: "license",
|
|
1879
|
-
type: "string",
|
|
1880
|
-
description: "package license",
|
|
1881
|
-
initial: "MIT",
|
|
1882
|
-
validate: (v) => v ? !0 : "license is required"
|
|
1883
|
-
}
|
|
1884
|
-
],
|
|
1885
|
-
features: [
|
|
1886
|
-
{
|
|
1887
|
-
name: "eslint",
|
|
1888
|
-
optional: !0,
|
|
1889
|
-
initial: !0
|
|
1890
|
-
},
|
|
1891
|
-
{
|
|
1892
|
-
name: "prettier",
|
|
1893
|
-
optional: !0,
|
|
1894
|
-
initial: !0
|
|
1895
|
-
},
|
|
1896
|
-
{
|
|
1897
|
-
name: "typescript",
|
|
1898
|
-
optional: !0,
|
|
1899
|
-
initial: !0
|
|
1900
|
-
}
|
|
1901
|
-
],
|
|
1902
|
-
async getFiles(options, features) {
|
|
1903
|
-
const { pkgName, repo } = options, { fullName: name } = pkgName, author = [options.authorName, options.authorEmail && `<${options.authorEmail}>`].filter(Boolean).join(" ") ?? void 0, pkgJson = {
|
|
1904
|
-
name,
|
|
1905
|
-
version: "0.0.0",
|
|
1906
|
-
description: options.description ?? void 0,
|
|
1907
|
-
keywords: [],
|
|
1908
|
-
homepage: void 0,
|
|
1909
|
-
bugs: void 0,
|
|
1910
|
-
repository: void 0,
|
|
1911
|
-
license: options.license,
|
|
1912
|
-
author,
|
|
1913
|
-
sideEffects: !1,
|
|
1914
|
-
type: "module",
|
|
1915
|
-
exports: {
|
|
1916
|
-
".": {
|
|
1917
|
-
source: features.typescript ? "./src/index.ts" : "./src/index.js",
|
|
1918
|
-
require: "./dist/index.cjs",
|
|
1919
|
-
default: "./dist/index.js"
|
|
1920
|
-
},
|
|
1921
|
-
"./package.json": "./package.json"
|
|
1922
|
-
},
|
|
1923
|
-
main: "./dist/index.cjs",
|
|
1924
|
-
module: "./dist/index.js",
|
|
1925
|
-
types: void 0,
|
|
1926
|
-
files: ["dist", "src"],
|
|
1927
|
-
scripts: {
|
|
1928
|
-
build: "pkg build --strict --clean --check",
|
|
1929
|
-
format: features.prettier ? "prettier --write --cache --ignore-unknown ." : void 0
|
|
1930
|
-
},
|
|
1931
|
-
"lint-staged": features.prettier ? {
|
|
1932
|
-
"*": ["prettier --write --cache --ignore-unknown"]
|
|
1933
|
-
} : void 0,
|
|
1934
|
-
browserslist: "extends @sanity/browserslist-config",
|
|
1935
|
-
prettier: features.prettier ? "@sanity/prettier-config" : void 0,
|
|
1936
|
-
dependencies: {},
|
|
1937
|
-
devDependencies: {
|
|
1938
|
-
"@sanity/pkg-utils": "^6",
|
|
1939
|
-
"@sanity/prettier-config": features.prettier ? "^1" : void 0,
|
|
1940
|
-
"@typescript-eslint/eslint-plugin": void 0,
|
|
1941
|
-
"@typescript-eslint/parser": void 0,
|
|
1942
|
-
eslint: void 0,
|
|
1943
|
-
"eslint-config-prettier": void 0,
|
|
1944
|
-
"eslint-plugin-import": void 0,
|
|
1945
|
-
"eslint-plugin-prettier": void 0,
|
|
1946
|
-
"eslint-plugin-simple-import-sort": void 0,
|
|
1947
|
-
"lint-staged": "^15",
|
|
1948
|
-
prettier: features.prettier ? "^3" : void 0,
|
|
1949
|
-
typescript: void 0
|
|
1950
|
-
},
|
|
1951
|
-
engines: {
|
|
1952
|
-
node: ">=18.0.0"
|
|
1953
|
-
}
|
|
1954
|
-
}, files = [];
|
|
1955
|
-
if (files.push({
|
|
1956
|
-
name: ".editorconfig",
|
|
1957
|
-
contents: outdent`
|
|
1958
|
-
root = true
|
|
1959
|
-
|
|
1960
|
-
[*]
|
|
1961
|
-
charset = utf-8
|
|
1962
|
-
indent_style = space
|
|
1963
|
-
indent_size = 2
|
|
1964
|
-
end_of_line = lf
|
|
1965
|
-
insert_final_newline = true
|
|
1966
|
-
trim_trailing_whitespace = true
|
|
1967
|
-
`
|
|
1968
|
-
}), files.push({
|
|
1969
|
-
name: ".gitignore",
|
|
1970
|
-
contents: outdent`
|
|
1971
|
-
*.local
|
|
1972
|
-
*.log
|
|
1973
|
-
*.tgz
|
|
1974
|
-
|
|
1975
|
-
.DS_Store
|
|
1976
|
-
dist
|
|
1977
|
-
etc
|
|
1978
|
-
node_modules
|
|
1979
|
-
`
|
|
1980
|
-
}), features.prettier && files.push({
|
|
1981
|
-
name: ".prettierignore",
|
|
1982
|
-
contents: outdent`
|
|
1983
|
-
dist
|
|
1984
|
-
pnpm-lock.yaml
|
|
1985
|
-
`
|
|
1986
|
-
}), repo && (pkgJson.repository = {
|
|
1987
|
-
type: "git",
|
|
1988
|
-
url: `git+ssh://git@${repo.source}/${repo.owner}/${repo.name}.git`
|
|
1989
|
-
}, pkgJson.bugs = {
|
|
1990
|
-
url: `https://${repo.source}/${repo.owner}/${repo.name}/issues`
|
|
1991
|
-
}, pkgJson.homepage = `https://${repo.source}/${repo.owner}/${repo.name}#readme`), features.typescript) {
|
|
1992
|
-
pkgJson.types = "./dist/index.d.ts", pkgJson.scripts = {
|
|
1993
|
-
...pkgJson.scripts,
|
|
1994
|
-
"ts:check": "tsc --noEmit"
|
|
1995
|
-
};
|
|
1996
|
-
const devDependencies = pkgJson.devDependencies;
|
|
1997
|
-
isRecord(devDependencies) && (devDependencies.typescript = "^5.4");
|
|
1998
|
-
}
|
|
1999
|
-
if (features.eslint) {
|
|
2000
|
-
const eslintConfig = {
|
|
2001
|
-
root: !0,
|
|
2002
|
-
env: {
|
|
2003
|
-
browser: !0,
|
|
2004
|
-
es6: !0,
|
|
2005
|
-
node: !0
|
|
2006
|
-
},
|
|
2007
|
-
extends: [
|
|
2008
|
-
"eslint:recommended",
|
|
2009
|
-
features.prettier ? "plugin:prettier/recommended" : void 0
|
|
2010
|
-
].filter(Boolean),
|
|
2011
|
-
parserOptions: {
|
|
2012
|
-
ecmaVersion: 2020,
|
|
2013
|
-
sourceType: "module"
|
|
2014
|
-
},
|
|
2015
|
-
plugins: [
|
|
2016
|
-
"import",
|
|
2017
|
-
"simple-import-sort",
|
|
2018
|
-
features.prettier ? "prettier" : void 0
|
|
2019
|
-
].filter(Boolean),
|
|
2020
|
-
rules: {
|
|
2021
|
-
"no-console": "error",
|
|
2022
|
-
"no-shadow": "error",
|
|
2023
|
-
"no-warning-comments": ["warn", { location: "start", terms: ["todo", "fixme"] }],
|
|
2024
|
-
"quote-props": ["warn", "consistent-as-needed"],
|
|
2025
|
-
"simple-import-sort/exports": "warn",
|
|
2026
|
-
"simple-import-sort/imports": "warn",
|
|
2027
|
-
strict: ["warn", "global"]
|
|
2028
|
-
}
|
|
2029
|
-
};
|
|
2030
|
-
if (files.push({
|
|
2031
|
-
name: ".eslintignore",
|
|
2032
|
-
contents: outdent`
|
|
2033
|
-
dist
|
|
2034
|
-
`
|
|
2035
|
-
}), pkgJson.scripts = {
|
|
2036
|
-
...pkgJson.scripts,
|
|
2037
|
-
lint: features.typescript ? "eslint . --ext .cjs,.js,.ts,.tsx" : "eslint . --ext .cjs,.js"
|
|
2038
|
-
}, pkgJson.devDependencies = {
|
|
2039
|
-
...pkgJson.devDependencies,
|
|
2040
|
-
eslint: "^8",
|
|
2041
|
-
"eslint-config-prettier": features.prettier ? "^9" : void 0,
|
|
2042
|
-
"eslint-plugin-import": "^2",
|
|
2043
|
-
"eslint-plugin-prettier": features.prettier ? "^5" : void 0,
|
|
2044
|
-
"eslint-plugin-simple-import-sort": "^12"
|
|
2045
|
-
}, features.typescript) {
|
|
2046
|
-
pkgJson.devDependencies = {
|
|
2047
|
-
...pkgJson.devDependencies,
|
|
2048
|
-
"@typescript-eslint/eslint-plugin": "^7",
|
|
2049
|
-
"@typescript-eslint/parser": "^7"
|
|
2050
|
-
};
|
|
2051
|
-
const eslintConfigOverride = {
|
|
2052
|
-
files: ["**/*.ts", "**/*.tsx"],
|
|
2053
|
-
parser: "@typescript-eslint/parser",
|
|
2054
|
-
parserOptions: {
|
|
2055
|
-
project: ["./tsconfig.json"]
|
|
2056
|
-
},
|
|
2057
|
-
extends: [
|
|
2058
|
-
"eslint:recommended",
|
|
2059
|
-
features.prettier ? "plugin:prettier/recommended" : void 0,
|
|
2060
|
-
"plugin:@typescript-eslint/eslint-recommended",
|
|
2061
|
-
"plugin:@typescript-eslint/recommended"
|
|
2062
|
-
].filter(Boolean),
|
|
2063
|
-
plugins: [
|
|
2064
|
-
"import",
|
|
2065
|
-
"@typescript-eslint",
|
|
2066
|
-
"simple-import-sort",
|
|
2067
|
-
features.prettier ? "prettier" : void 0
|
|
2068
|
-
].filter(Boolean),
|
|
2069
|
-
rules: {
|
|
2070
|
-
"@typescript-eslint/explicit-module-boundary-types": "error",
|
|
2071
|
-
"@typescript-eslint/interface-name-prefix": "off",
|
|
2072
|
-
"@typescript-eslint/member-delimiter-style": "off",
|
|
2073
|
-
"@typescript-eslint/no-empty-interface": "off"
|
|
2074
|
-
}
|
|
2075
|
-
};
|
|
2076
|
-
eslintConfig.overrides = [eslintConfigOverride];
|
|
2077
|
-
}
|
|
2078
|
-
files.push({
|
|
2079
|
-
name: ".eslintrc.cjs",
|
|
2080
|
-
contents: await prettierFormat(
|
|
2081
|
-
resolve(packagePath, ".eslintrc.cjs"),
|
|
2082
|
-
outdent`
|
|
2083
|
-
'use strict'
|
|
2084
|
-
|
|
2085
|
-
/** @type import('eslint').Linter.Config */
|
|
2086
|
-
module.exports = ${JSON.stringify(eslintConfig, null, 2)}
|
|
2087
|
-
`,
|
|
2088
|
-
config
|
|
2089
|
-
)
|
|
2090
|
-
});
|
|
2091
|
-
}
|
|
2092
|
-
features.typescript && (files.push({
|
|
2093
|
-
name: "tsconfig.settings.json",
|
|
2094
|
-
contents: await prettierFormat(
|
|
2095
|
-
resolve(packagePath, "tsconfig.settings.json"),
|
|
2096
|
-
outdent`
|
|
2097
|
-
{
|
|
2098
|
-
"extends": "@sanity/pkg-utils/tsconfig/strictest.json",
|
|
2099
|
-
"compilerOptions": {
|
|
2100
|
-
"rootDir": ".",
|
|
2101
|
-
"outDir": "./dist"
|
|
2102
|
-
}
|
|
2103
|
-
}
|
|
2104
|
-
`,
|
|
2105
|
-
config
|
|
2106
|
-
)
|
|
2107
|
-
}), files.push({
|
|
2108
|
-
name: "tsconfig.dist.json",
|
|
2109
|
-
contents: await prettierFormat(
|
|
2110
|
-
resolve(packagePath, "tsconfig.dist.json"),
|
|
2111
|
-
outdent`
|
|
2112
|
-
{
|
|
2113
|
-
"extends": "./tsconfig.settings",
|
|
2114
|
-
"include": ["./src"],
|
|
2115
|
-
"exclude": ["./src/**/*.test.ts"]
|
|
2116
|
-
}
|
|
2117
|
-
`,
|
|
2118
|
-
config
|
|
2119
|
-
)
|
|
2120
|
-
}), files.push({
|
|
2121
|
-
name: "tsconfig.json",
|
|
2122
|
-
contents: await prettierFormat(
|
|
2123
|
-
resolve(packagePath, "tsconfig.json"),
|
|
2124
|
-
outdent`
|
|
2125
|
-
{
|
|
2126
|
-
"extends": "./tsconfig.settings",
|
|
2127
|
-
"include": ["./**/*.cjs", "./**/*.ts", "./**/*.tsx"],
|
|
2128
|
-
"exclude": ["./node_modules"]
|
|
2129
|
-
}
|
|
2130
|
-
`,
|
|
2131
|
-
config
|
|
2132
|
-
)
|
|
2133
|
-
})), features.typescript ? (files.push({
|
|
2134
|
-
name: "package.config.ts",
|
|
2135
|
-
contents: await prettierFormat(
|
|
2136
|
-
resolve(packagePath, "package.config.ts"),
|
|
2137
|
-
outdent`
|
|
2138
|
-
import {defineConfig} from '@sanity/pkg-utils'
|
|
2139
|
-
|
|
2140
|
-
// https://github.com/sanity-io/pkg-utils#configuration
|
|
2141
|
-
export default defineConfig({
|
|
2142
|
-
// the path to the tsconfig file for distributed builds
|
|
2143
|
-
tsconfig: 'tsconfig.dist.json',
|
|
2144
|
-
})
|
|
2145
|
-
`,
|
|
2146
|
-
config
|
|
2147
|
-
)
|
|
2148
|
-
}), files.push({
|
|
2149
|
-
name: "src/index.ts",
|
|
2150
|
-
contents: await prettierFormat(
|
|
2151
|
-
resolve(packagePath, "src/index.ts"),
|
|
2152
|
-
outdent`
|
|
2153
|
-
/** @public */
|
|
2154
|
-
export function main(): void {
|
|
2155
|
-
//
|
|
2156
|
-
}
|
|
2157
|
-
`,
|
|
2158
|
-
config
|
|
2159
|
-
)
|
|
2160
|
-
})) : (files.push({
|
|
2161
|
-
name: "package.config.js",
|
|
2162
|
-
contents: await prettierFormat(
|
|
2163
|
-
resolve(packagePath, "package.config.js"),
|
|
2164
|
-
outdent`
|
|
2165
|
-
import {defineConfig} from '@sanity/pkg-utils'
|
|
2166
|
-
|
|
2167
|
-
export default defineConfig({
|
|
2168
|
-
extract: {
|
|
2169
|
-
rules: {
|
|
2170
|
-
// do not require internal members to be prefixed with \`_\`
|
|
2171
|
-
'ae-internal-missing-underscore': 'off',
|
|
2172
|
-
},
|
|
2173
|
-
},
|
|
2174
|
-
})
|
|
2175
|
-
`,
|
|
2176
|
-
config
|
|
2177
|
-
)
|
|
2178
|
-
}), files.push({
|
|
2179
|
-
name: "src/index.js",
|
|
2180
|
-
contents: await prettierFormat(
|
|
2181
|
-
resolve(packagePath, "src/index.js"),
|
|
2182
|
-
outdent`
|
|
2183
|
-
/** @public */
|
|
2184
|
-
export function main() {
|
|
2185
|
-
//
|
|
2186
|
-
}
|
|
2187
|
-
`,
|
|
2188
|
-
config
|
|
2189
|
-
)
|
|
2190
|
-
}));
|
|
2191
|
-
try {
|
|
2192
|
-
pkgJson.dependencies = await resolveLatestDeps(pkgJson.dependencies ?? {});
|
|
2193
|
-
} catch (error) {
|
|
2194
|
-
logger.warn(error instanceof Error ? error.message : error);
|
|
2195
|
-
}
|
|
2196
|
-
try {
|
|
2197
|
-
pkgJson.devDependencies = await resolveLatestDeps(pkgJson.devDependencies ?? {});
|
|
2198
|
-
} catch (error) {
|
|
2199
|
-
logger.warn(error instanceof Error ? error.message : error);
|
|
2200
|
-
}
|
|
2201
|
-
return files.push({
|
|
2202
|
-
name: "package.json",
|
|
2203
|
-
contents: await prettierFormat(
|
|
2204
|
-
resolve(packagePath, "package.json"),
|
|
2205
|
-
JSON.stringify(pkgJson, null, 2),
|
|
2206
|
-
config
|
|
2207
|
-
)
|
|
2208
|
-
}), files;
|
|
2209
|
-
}
|
|
2210
|
-
};
|
|
2211
|
-
};
|
|
2212
|
-
function prettierFormat(filepath, input, prettierOptions) {
|
|
2213
|
-
return format(input, { ...prettierOptions, plugins: [], filepath });
|
|
2214
|
-
}
|
|
2215
|
-
async function resolveLatestDeps(deps) {
|
|
2216
|
-
const depsEntries = Object.entries(deps), latestDeps = {};
|
|
2217
|
-
for (const entry of depsEntries) {
|
|
2218
|
-
const [name, version] = entry;
|
|
2219
|
-
if (version) {
|
|
2220
|
-
const latestVersion = await getLatestVersion(name, version);
|
|
2221
|
-
latestDeps[name] = latestVersion ? `^${latestVersion}` : version;
|
|
2222
|
-
}
|
|
2223
|
-
}
|
|
2224
|
-
return latestDeps;
|
|
2225
|
-
}
|
|
2226
|
-
function getGitUserConfig(cwd) {
|
|
2227
|
-
let user, email;
|
|
2228
|
-
try {
|
|
2229
|
-
user = execSync("git config user.name", { encoding: "utf8", cwd }).trim() || void 0, email = execSync("git config user.email", { encoding: "utf8", cwd }).trim() || void 0;
|
|
2230
|
-
} catch {
|
|
2231
|
-
}
|
|
2232
|
-
return { user, email };
|
|
2233
|
-
}
|
|
2234
|
-
async function init(options) {
|
|
2235
|
-
if (!options.cwd)
|
|
2236
|
-
throw new Error("Missing required option: cwd");
|
|
2237
|
-
if (!options.path)
|
|
2238
|
-
throw new Error("Missing required option: path");
|
|
2239
|
-
const logger = createLogger(), packagePath = resolve(options.cwd, options.path);
|
|
2240
|
-
await ensurePackagePath(packagePath), await createFromTemplate({
|
|
2241
|
-
cwd: options.cwd,
|
|
2242
|
-
logger,
|
|
2243
|
-
template: defaultTemplate,
|
|
2244
|
-
packagePath
|
|
2245
|
-
});
|
|
2246
|
-
}
|
|
2247
|
-
async function ensurePackagePath(packagePath) {
|
|
2248
|
-
if (!fileExists(packagePath)) {
|
|
2249
|
-
await mkdirp(packagePath);
|
|
2250
|
-
return;
|
|
2251
|
-
}
|
|
2252
|
-
if (!(await lstat(packagePath)).isDirectory())
|
|
2253
|
-
throw new Error("the package path is a file, not a directory");
|
|
2254
|
-
if (!await isEmptyDirectory(packagePath))
|
|
2255
|
-
throw new Error("the package directory is not empty");
|
|
2256
|
-
}
|
|
2257
|
-
function resolveWatchTasks(ctx) {
|
|
2258
|
-
const { pkg, target } = ctx, tasks = [], exports = Object.entries(ctx.exports || {}).map(
|
|
2259
|
-
([_path, exp]) => ({ _path, ...exp })
|
|
2260
|
-
), dtsTask2 = {
|
|
2261
|
-
type: "watch:dts",
|
|
2262
|
-
entries: []
|
|
2263
|
-
}, rollupTasks = {};
|
|
2264
|
-
function addRollupTaskEntry(format2, runtime, entry) {
|
|
2265
|
-
const buildId = `${format2}:${runtime}`;
|
|
2266
|
-
rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
|
|
2267
|
-
type: "watch:js",
|
|
2268
|
-
buildId,
|
|
2269
|
-
entries: [entry],
|
|
2270
|
-
runtime,
|
|
2271
|
-
format: format2,
|
|
2272
|
-
target: target[runtime]
|
|
2273
|
-
};
|
|
2274
|
-
}
|
|
2275
|
-
for (const exp of exports) {
|
|
2276
|
-
const importId = path.join(pkg.name, exp._path);
|
|
2277
|
-
exp.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2278
|
-
importId,
|
|
2279
|
-
exportPath: exp._path,
|
|
2280
|
-
sourcePath: exp.source,
|
|
2281
|
-
targetPaths: getTargetPaths(pkg.type, exp)
|
|
2282
|
-
}), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2283
|
-
importId,
|
|
2284
|
-
exportPath: exp._path,
|
|
2285
|
-
sourcePath: exp.browser.source,
|
|
2286
|
-
targetPaths: getTargetPaths(pkg.type, exp.browser)
|
|
2287
|
-
}), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2288
|
-
importId,
|
|
2289
|
-
exportPath: exp._path,
|
|
2290
|
-
sourcePath: exp.node.source,
|
|
2291
|
-
targetPaths: getTargetPaths(pkg.type, exp.node)
|
|
2292
|
-
});
|
|
2293
|
-
}
|
|
2294
|
-
for (const exp of exports) {
|
|
2295
|
-
const output = exp.require;
|
|
2296
|
-
output && addRollupTaskEntry("commonjs", ctx.runtime, {
|
|
2297
|
-
path: exp._path,
|
|
2298
|
-
source: exp.source,
|
|
2299
|
-
output
|
|
2300
|
-
});
|
|
2301
|
-
}
|
|
2302
|
-
for (const exp of exports) {
|
|
2303
|
-
const output = exp.browser?.require;
|
|
2304
|
-
output && addRollupTaskEntry("commonjs", "browser", {
|
|
2305
|
-
path: exp._path,
|
|
2306
|
-
source: exp.browser?.source || exp.source,
|
|
2307
|
-
output
|
|
2308
|
-
});
|
|
2309
|
-
}
|
|
2310
|
-
for (const exp of exports) {
|
|
2311
|
-
const output = exp.import;
|
|
2312
|
-
output && addRollupTaskEntry("esm", ctx.runtime, {
|
|
2313
|
-
path: exp._path,
|
|
2314
|
-
source: exp.source,
|
|
2315
|
-
output
|
|
2316
|
-
});
|
|
2317
|
-
}
|
|
2318
|
-
for (const exp of exports) {
|
|
2319
|
-
const output = exp.browser?.import;
|
|
2320
|
-
output && addRollupTaskEntry("esm", "browser", {
|
|
2321
|
-
path: exp._path,
|
|
2322
|
-
source: exp.browser?.source || exp.source,
|
|
2323
|
-
output
|
|
2324
|
-
});
|
|
2325
|
-
}
|
|
2326
|
-
return dtsTask2.entries.length && tasks.push(dtsTask2), tasks.push(...Object.values(rollupTasks)), tasks;
|
|
2327
|
-
}
|
|
2328
|
-
function globFiles(patterns) {
|
|
2329
|
-
return globby(patterns.map((pattern) => pattern.split(path.sep).join(path.posix.sep)));
|
|
2330
|
-
}
|
|
2331
|
-
function watchFiles(patterns) {
|
|
2332
|
-
return new Observable((observer) => {
|
|
2333
|
-
const watcher = chokidar.watch(patterns, {
|
|
2334
|
-
ignoreInitial: !0
|
|
2335
|
-
});
|
|
2336
|
-
function handleFileEvent(type, file) {
|
|
2337
|
-
type === "error" || file instanceof Error ? observer.error(file) : observer.next({ type, file });
|
|
2338
|
-
}
|
|
2339
|
-
return watcher.on("all", handleFileEvent), () => {
|
|
2340
|
-
watcher.off("all", handleFileEvent), watcher.close();
|
|
2341
|
-
};
|
|
2342
|
-
});
|
|
2343
|
-
}
|
|
2344
|
-
async function watchConfigFiles(options) {
|
|
2345
|
-
const { cwd, logger } = options, initialFiles = await globFiles([
|
|
2346
|
-
path.resolve(cwd, "package.json"),
|
|
2347
|
-
path.resolve(cwd, "package.config.cjs"),
|
|
2348
|
-
path.resolve(cwd, "package.config.js"),
|
|
2349
|
-
path.resolve(cwd, "package.config.ts")
|
|
2350
|
-
]);
|
|
2351
|
-
return watchFiles([
|
|
2352
|
-
path.resolve(cwd, "package.json"),
|
|
2353
|
-
path.resolve(cwd, "package.config.cjs"),
|
|
2354
|
-
path.resolve(cwd, "package.config.js"),
|
|
2355
|
-
path.resolve(cwd, "package.config.ts")
|
|
2356
|
-
]).pipe(
|
|
2357
|
-
scan((files, fileEvent) => fileEvent.type === "add" ? files.concat(fileEvent.file) : fileEvent.type === "unlink" ? files.filter((f) => f !== fileEvent.file) : fileEvent.type === "change" ? (logger.log(
|
|
2358
|
-
"--------------------------------------------------------------------------------"
|
|
2359
|
-
), logger.info(path.relative(cwd, fileEvent.file), "changed"), logger.log(""), files.slice(0)) : files, initialFiles),
|
|
2360
|
-
startWith(initialFiles),
|
|
2361
|
-
distinctUntilChanged()
|
|
2362
|
-
);
|
|
2363
|
-
}
|
|
2364
|
-
async function watch(options) {
|
|
2365
|
-
const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger();
|
|
2366
|
-
(await watchConfigFiles({ cwd, logger })).pipe(
|
|
2367
|
-
switchMap(async (configFiles) => {
|
|
2368
|
-
if (!configFiles.map((f) => path.relative(cwd, f)).find((f) => f === "package.json"))
|
|
2369
|
-
throw new Error("missing package.json");
|
|
2370
|
-
const config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json";
|
|
2371
|
-
return resolveBuildContext({ config: config2, cwd, logger, pkg, strict, tsconfig });
|
|
2372
|
-
})
|
|
2373
|
-
).subscribe(async (ctx) => {
|
|
2374
|
-
const watchTasks = resolveWatchTasks(ctx);
|
|
2375
|
-
for (const task of watchTasks) {
|
|
2376
|
-
const handler = watchTaskHandlers[task.type];
|
|
2377
|
-
handler.exec(ctx, task).subscribe({
|
|
2378
|
-
error: (err) => {
|
|
2379
|
-
ctx.logger.error(err), ctx.logger.log(), process.exit(1);
|
|
2380
|
-
},
|
|
2381
|
-
next: (result) => {
|
|
2382
|
-
handler.complete(ctx, task, result);
|
|
2383
|
-
},
|
|
2384
|
-
complete: () => {
|
|
2385
|
-
ctx.logger.success(handler.name(ctx, task)), ctx.logger.log();
|
|
2386
|
-
}
|
|
2387
|
-
});
|
|
2388
|
-
}
|
|
2389
|
-
});
|
|
2390
|
-
}
|
|
1
|
+
import { DEFAULT_BROWSERSLIST_QUERY, build, check, createLogger, defineConfig, defineTemplateOption, getExtractMessagesConfig, init, loadConfig, loadPkg, loadPkgWithReporting, parseExports, parseStrictOptions, strictOptions, toggle, watch } from "./_chunks-es/index.js";
|
|
2391
2
|
export {
|
|
2392
3
|
DEFAULT_BROWSERSLIST_QUERY,
|
|
2393
4
|
build,
|