@sanity/pkg-utils 7.3.0 → 7.4.0-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/pkg-utils.js +2 -0
- package/dist/_chunks-cjs/index.cjs +1499 -43
- package/dist/_chunks-cjs/index.cjs.map +1 -1
- package/dist/_chunks-cjs/resolveRolldownConfig.cjs +2 -2
- package/dist/_chunks-cjs/resolveRolldownConfig.cjs.map +1 -1
- package/dist/{_chunks-cjs/build.cjs → _chunks-es/build.js} +28 -26
- package/dist/_chunks-es/build.js.map +1 -0
- package/dist/{_chunks-cjs/buildAction.cjs → _chunks-es/buildAction.js} +8 -6
- package/dist/_chunks-es/buildAction.js.map +1 -0
- package/dist/{_chunks-cjs/check.cjs → _chunks-es/check.js} +30 -26
- package/dist/_chunks-es/check.js.map +1 -0
- package/dist/_chunks-es/checkAction.js +17 -0
- package/dist/_chunks-es/checkAction.js.map +1 -0
- package/dist/{_chunks-cjs/consoleSpy.cjs → _chunks-es/consoleSpy.js} +107 -96
- package/dist/_chunks-es/consoleSpy.js.map +1 -0
- package/dist/_chunks-es/handleError.js +8 -0
- package/dist/_chunks-es/handleError.js.map +1 -0
- package/dist/_chunks-es/index.js +42 -1516
- package/dist/_chunks-es/index.js.map +1 -1
- package/dist/{_chunks-cjs/init.cjs → _chunks-es/init.js} +53 -47
- package/dist/_chunks-es/init.js.map +1 -0
- package/dist/_chunks-es/initAction.js +16 -0
- package/dist/_chunks-es/initAction.js.map +1 -0
- package/dist/_chunks-es/isRecord.js +37 -0
- package/dist/_chunks-es/isRecord.js.map +1 -0
- package/dist/_chunks-es/resolveRolldownConfig.js +1 -1
- package/dist/_chunks-es/watch.js +146 -0
- package/dist/_chunks-es/watch.js.map +1 -0
- package/dist/_chunks-es/watchAction.js +17 -0
- package/dist/_chunks-es/watchAction.js.map +1 -0
- package/dist/{cli.cjs → cli.js} +9 -19
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +16 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/bin/pkg-utils.cjs +0 -2
- package/dist/_chunks-cjs/build.cjs.map +0 -1
- package/dist/_chunks-cjs/buildAction.cjs.map +0 -1
- package/dist/_chunks-cjs/check.cjs.map +0 -1
- package/dist/_chunks-cjs/checkAction.cjs +0 -15
- package/dist/_chunks-cjs/checkAction.cjs.map +0 -1
- package/dist/_chunks-cjs/consoleSpy.cjs.map +0 -1
- package/dist/_chunks-cjs/handleError.cjs +0 -11
- package/dist/_chunks-cjs/handleError.cjs.map +0 -1
- package/dist/_chunks-cjs/init.cjs.map +0 -1
- package/dist/_chunks-cjs/initAction.cjs +0 -14
- package/dist/_chunks-cjs/initAction.cjs.map +0 -1
- package/dist/_chunks-cjs/isRecord.cjs +0 -39
- package/dist/_chunks-cjs/isRecord.cjs.map +0 -1
- package/dist/_chunks-cjs/watch.cjs +0 -157
- package/dist/_chunks-cjs/watch.cjs.map +0 -1
- package/dist/_chunks-cjs/watchAction.cjs +0 -15
- package/dist/_chunks-cjs/watchAction.cjs.map +0 -1
- package/dist/cli.cjs.map +0 -1
- /package/dist/{cli.d.cts → cli.d.ts} +0 -0
package/dist/_chunks-es/index.js
CHANGED
|
@@ -1,27 +1,19 @@
|
|
|
1
|
-
import
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { Observable, from } from "rxjs";
|
|
3
|
+
import path from "node:path";
|
|
2
4
|
import * as rimraf from "rimraf";
|
|
3
5
|
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
6
|
import ts from "typescript";
|
|
14
|
-
import {
|
|
15
|
-
import { Observable, from, switchMap } from "rxjs";
|
|
7
|
+
import fs, { readFile } from "node:fs/promises";
|
|
16
8
|
import { ExtractorConfig, Extractor } from "@microsoft/api-extractor";
|
|
17
9
|
import { mkdirp } from "mkdirp";
|
|
18
10
|
import * as prettier from "prettier";
|
|
19
|
-
import { format } from "prettier";
|
|
20
11
|
import { TSDocConfigFile } from "@microsoft/tsdoc-config";
|
|
21
12
|
import { parse } from "jsonc-parser";
|
|
22
13
|
import { parse as parse$1, print } from "recast";
|
|
23
14
|
import typeScriptParser from "recast/parsers/typescript.js";
|
|
24
|
-
import {
|
|
15
|
+
import { createConsoleSpy, resolveConfigProperty, pkgExtMap } from "./consoleSpy.js";
|
|
16
|
+
import { rollup, watch } from "rollup";
|
|
25
17
|
import { optimizeLodashImports } from "@optimize-lodash/rollup-plugin";
|
|
26
18
|
import alias from "@rollup/plugin-alias";
|
|
27
19
|
import { babel, getBabelOutputPlugin } from "@rollup/plugin-babel";
|
|
@@ -31,657 +23,6 @@ import { nodeResolve } from "@rollup/plugin-node-resolve";
|
|
|
31
23
|
import replace from "@rollup/plugin-replace";
|
|
32
24
|
import terser from "@rollup/plugin-terser";
|
|
33
25
|
import esbuild from "rollup-plugin-esbuild";
|
|
34
|
-
import esbuild$1 from "esbuild";
|
|
35
|
-
import treeify from "treeify";
|
|
36
|
-
import prettyBytes from "pretty-bytes";
|
|
37
|
-
import prompts from "prompts";
|
|
38
|
-
import { execSync } from "node:child_process";
|
|
39
|
-
import getLatestVersion from "get-latest-version";
|
|
40
|
-
import gitUrlParse from "git-url-parse";
|
|
41
|
-
import { outdent } from "outdent";
|
|
42
|
-
import { scan, startWith, distinctUntilChanged } from "rxjs/operators";
|
|
43
|
-
import globby from "globby";
|
|
44
|
-
import * as chokidar from "chokidar";
|
|
45
|
-
function fileExists(filePath) {
|
|
46
|
-
try {
|
|
47
|
-
return statSync(filePath), !0;
|
|
48
|
-
} catch {
|
|
49
|
-
return !1;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
const CONFIG_FILE_NAMES = [
|
|
53
|
-
"package.config.ts",
|
|
54
|
-
"package.config.js",
|
|
55
|
-
"package.config.cjs",
|
|
56
|
-
"package.config.mjs"
|
|
57
|
-
];
|
|
58
|
-
function findConfigFile(cwd) {
|
|
59
|
-
const pkgJsonPath = findConfig("package.json", { cwd });
|
|
60
|
-
if (!pkgJsonPath) return;
|
|
61
|
-
const pkgPath = path.dirname(pkgJsonPath);
|
|
62
|
-
for (const fileName of CONFIG_FILE_NAMES) {
|
|
63
|
-
const configPath = path.resolve(pkgPath, fileName);
|
|
64
|
-
if (fileExists(configPath))
|
|
65
|
-
return configPath;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
async function loadConfig(options) {
|
|
69
|
-
const { cwd } = options, pkgPath = await pkgUp({ cwd });
|
|
70
|
-
if (!pkgPath) return;
|
|
71
|
-
const root = path.dirname(pkgPath), configFile = await findConfigFile(root);
|
|
72
|
-
if (!configFile || !configFile.startsWith(cwd))
|
|
73
|
-
return;
|
|
74
|
-
const esbuildOptions = { extensions: [".js", ".mjs", ".ts"] }, { unregister } = globalThis.__DEV__ ? { unregister: () => {
|
|
75
|
-
} } : register(esbuildOptions), mod = require(configFile);
|
|
76
|
-
return unregister(), mod?.default || mod || void 0;
|
|
77
|
-
}
|
|
78
|
-
function assertLast(a, arr) {
|
|
79
|
-
const aIdx = arr.indexOf(a);
|
|
80
|
-
return aIdx === -1 ? !0 : aIdx === arr.length - 1;
|
|
81
|
-
}
|
|
82
|
-
function assertOrder(a, b, arr) {
|
|
83
|
-
const aIdx = arr.indexOf(a), bIdx = arr.indexOf(b);
|
|
84
|
-
return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
|
|
85
|
-
}
|
|
86
|
-
const pkgSchema = z.object({
|
|
87
|
-
type: z.optional(z.enum(["commonjs", "module"])),
|
|
88
|
-
name: z.string(),
|
|
89
|
-
version: z.string(),
|
|
90
|
-
license: z.string(),
|
|
91
|
-
bin: z.optional(z.record(z.string())),
|
|
92
|
-
dependencies: z.optional(z.record(z.string())),
|
|
93
|
-
devDependencies: z.optional(z.record(z.string())),
|
|
94
|
-
peerDependencies: z.optional(z.record(z.string())),
|
|
95
|
-
source: z.optional(z.string()),
|
|
96
|
-
main: z.optional(z.string()),
|
|
97
|
-
browser: z.optional(z.record(z.string())),
|
|
98
|
-
module: z.optional(z.string()),
|
|
99
|
-
types: z.optional(z.string()),
|
|
100
|
-
exports: z.optional(
|
|
101
|
-
z.record(
|
|
102
|
-
z.union([
|
|
103
|
-
z.custom((val) => /^\.\/.*\.json$/.test(val)),
|
|
104
|
-
z.custom((val) => /^\.\/.*\.css$/.test(val)),
|
|
105
|
-
z.object({
|
|
106
|
-
types: z.optional(z.string()),
|
|
107
|
-
source: z.optional(z.string()),
|
|
108
|
-
browser: z.optional(
|
|
109
|
-
z.object({
|
|
110
|
-
source: z.string(),
|
|
111
|
-
import: z.optional(z.string()),
|
|
112
|
-
require: z.optional(z.string())
|
|
113
|
-
})
|
|
114
|
-
),
|
|
115
|
-
node: z.optional(
|
|
116
|
-
z.object({
|
|
117
|
-
source: z.optional(z.string()),
|
|
118
|
-
import: z.optional(z.string()),
|
|
119
|
-
require: z.optional(z.string())
|
|
120
|
-
})
|
|
121
|
-
),
|
|
122
|
-
import: z.optional(z.string()),
|
|
123
|
-
require: z.optional(z.string()),
|
|
124
|
-
default: z.string()
|
|
125
|
-
}),
|
|
126
|
-
z.object({
|
|
127
|
-
types: z.optional(z.string()),
|
|
128
|
-
svelte: z.string(),
|
|
129
|
-
default: z.optional(z.string())
|
|
130
|
-
})
|
|
131
|
-
])
|
|
132
|
-
)
|
|
133
|
-
),
|
|
134
|
-
browserslist: z.optional(z.union([z.string(), z.array(z.string())])),
|
|
135
|
-
sideEffects: z.optional(z.union([z.boolean(), z.array(z.string())])),
|
|
136
|
-
// @TODO type this properly
|
|
137
|
-
typesVersions: z.optional(z.any())
|
|
138
|
-
}), typoMap = /* @__PURE__ */ new Map();
|
|
139
|
-
for (const key of pkgSchema.keyof()._def.values)
|
|
140
|
-
typoMap.set(key.toUpperCase(), key);
|
|
141
|
-
function validatePkg(input) {
|
|
142
|
-
const pkg = pkgSchema.parse(input), invalidKey = Object.keys(input).find((key) => {
|
|
143
|
-
const needle = key.toUpperCase();
|
|
144
|
-
return typoMap.has(needle) ? typoMap.get(needle) !== key : !1;
|
|
145
|
-
});
|
|
146
|
-
if (invalidKey)
|
|
147
|
-
throw new TypeError(
|
|
148
|
-
`
|
|
149
|
-
- package.json: "${invalidKey}" is not a valid key. Did you mean "${typoMap.get(invalidKey.toUpperCase())}"?`
|
|
150
|
-
);
|
|
151
|
-
return pkg;
|
|
152
|
-
}
|
|
153
|
-
async function loadPkg(options) {
|
|
154
|
-
const { cwd } = options, pkgPath = await pkgUp({ cwd });
|
|
155
|
-
if (!pkgPath) throw new Error("no package.json found");
|
|
156
|
-
const buf = await fs.readFile(pkgPath), raw = JSON.parse(buf.toString());
|
|
157
|
-
return validatePkg(raw), raw;
|
|
158
|
-
}
|
|
159
|
-
async function loadPkgWithReporting(options) {
|
|
160
|
-
const { cwd, logger, strict } = options;
|
|
161
|
-
try {
|
|
162
|
-
const pkg = await loadPkg({ cwd });
|
|
163
|
-
let shouldError = !1;
|
|
164
|
-
if (strict && (pkg.type || (shouldError = !0, logger.error(
|
|
165
|
-
'the `type` field in `./package.json` must be either "module" or "commonjs")'
|
|
166
|
-
))), pkg.exports) {
|
|
167
|
-
const _exports = Object.entries(pkg.exports);
|
|
168
|
-
for (const [expPath, exp] of _exports) {
|
|
169
|
-
if (typeof exp == "string" || "svelte" in exp)
|
|
170
|
-
continue;
|
|
171
|
-
const keys = Object.keys(exp);
|
|
172
|
-
exp.types && (shouldError = !0, logger.error(
|
|
173
|
-
`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`
|
|
174
|
-
)), exp.module && (shouldError = !0, logger.error(
|
|
175
|
-
`exports["${expPath}"]: the \`module\` condition shouldn't be used as it's not well supported in all bundlers.`
|
|
176
|
-
)), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0, logger.error(
|
|
177
|
-
`exports["${expPath}"]: the \`node\` property should come before the \`import\` property`
|
|
178
|
-
)), exp.node.module && (shouldError = !0, logger.error(
|
|
179
|
-
`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"`
|
|
180
|
-
)), !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(
|
|
181
|
-
`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"`
|
|
182
|
-
)), exp.require && exp.node.require && exp.require === exp.node.require ? (shouldError = !0, logger.error(
|
|
183
|
-
`exports["${expPath}"]: the \`node.require\` property isn't necessary as it's identical to \`require\``
|
|
184
|
-
)) : exp.require && exp.node.require && !assertOrder("node", "require", keys) && (shouldError = !0, logger.error(
|
|
185
|
-
`exports["${expPath}"]: the \`node\` property should come before the \`require\` property`
|
|
186
|
-
))) : assertOrder("import", "require", keys) || logger.warn(
|
|
187
|
-
`exports["${expPath}"]: the \`import\` property should come before the \`require\` property`
|
|
188
|
-
), assertLast("default", keys) || (shouldError = !0, logger.error(
|
|
189
|
-
`exports["${expPath}"]: the \`default\` property should be the last property`
|
|
190
|
-
));
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
return shouldError && process.exit(1), pkg;
|
|
194
|
-
} catch (err) {
|
|
195
|
-
if (err instanceof ZodError)
|
|
196
|
-
for (const issue of err.issues) {
|
|
197
|
-
if (issue.code === "invalid_type") {
|
|
198
|
-
logger.error(
|
|
199
|
-
[
|
|
200
|
-
`\`${formatPath(issue.path)}\` `,
|
|
201
|
-
`in \`./package.json\` must be of type ${chalk.magenta(issue.expected)} `,
|
|
202
|
-
`(received ${chalk.magenta(issue.received)})`
|
|
203
|
-
].join("")
|
|
204
|
-
);
|
|
205
|
-
continue;
|
|
206
|
-
}
|
|
207
|
-
logger.error(issue);
|
|
208
|
-
}
|
|
209
|
-
else
|
|
210
|
-
logger.error(err);
|
|
211
|
-
process.exit(1);
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
function formatPath(segments) {
|
|
215
|
-
return segments.map((s, idx) => idx === 0 ? s : typeof s == "number" ? `[${s}]` : s.startsWith(".") ? `["${s}"]` : `.${s}`).join("");
|
|
216
|
-
}
|
|
217
|
-
function createLogger() {
|
|
218
|
-
return {
|
|
219
|
-
log: (...args) => {
|
|
220
|
-
console.log(...args);
|
|
221
|
-
},
|
|
222
|
-
info: (...args) => {
|
|
223
|
-
console.log(chalk.blue("[info]"), ...args);
|
|
224
|
-
},
|
|
225
|
-
warn: (...args) => {
|
|
226
|
-
console.log(chalk.yellow("[warning]"), ...args);
|
|
227
|
-
},
|
|
228
|
-
error: (...args) => {
|
|
229
|
-
console.log(chalk.red("[error]"), ...args);
|
|
230
|
-
},
|
|
231
|
-
success: (...args) => {
|
|
232
|
-
console.log(chalk.green("[success]"), ...args);
|
|
233
|
-
}
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
function browserslistToEsbuild(browserslistConfig, options = {}) {
|
|
237
|
-
if (!browserslistConfig) {
|
|
238
|
-
const path2 = process.cwd();
|
|
239
|
-
browserslistConfig = browserslist.loadConfig({ path: path2, ...options });
|
|
240
|
-
}
|
|
241
|
-
const SUPPORTED_ESBUILD_TARGETS = [
|
|
242
|
-
"es",
|
|
243
|
-
"chrome",
|
|
244
|
-
"edge",
|
|
245
|
-
"firefox",
|
|
246
|
-
"ios",
|
|
247
|
-
"node",
|
|
248
|
-
"safari",
|
|
249
|
-
"opera",
|
|
250
|
-
"ie"
|
|
251
|
-
], UNSUPPORTED = ["android 4"], replaces = {
|
|
252
|
-
ios_saf: "ios",
|
|
253
|
-
android: "chrome"
|
|
254
|
-
}, separator = " ";
|
|
255
|
-
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) => {
|
|
256
|
-
const existingIndex = acc.findIndex((br) => br[0] === b[0]);
|
|
257
|
-
return existingIndex !== -1 ? acc[existingIndex][1] = b[1] : acc.push(b), acc;
|
|
258
|
-
}, []).map((b) => b.join(""));
|
|
259
|
-
}
|
|
260
|
-
function resolveConfigProperty(prop, initialValue) {
|
|
261
|
-
return prop ? typeof prop == "function" ? prop(initialValue) : prop : initialValue;
|
|
262
|
-
}
|
|
263
|
-
const DEFAULT_BROWSERSLIST_QUERY = config$1;
|
|
264
|
-
function pathContains(containerPath, itemPath) {
|
|
265
|
-
return !path.relative(containerPath, itemPath).startsWith("..");
|
|
266
|
-
}
|
|
267
|
-
function findCommonDirPath(filePaths) {
|
|
268
|
-
let ret;
|
|
269
|
-
for (const filePath of filePaths) {
|
|
270
|
-
let dirPath = path.dirname(filePath);
|
|
271
|
-
if (!ret) {
|
|
272
|
-
ret = dirPath;
|
|
273
|
-
continue;
|
|
274
|
-
}
|
|
275
|
-
for (; dirPath !== ret && (dirPath = path.dirname(dirPath), dirPath !== ret); ) {
|
|
276
|
-
if (pathContains(dirPath, ret)) {
|
|
277
|
-
ret = dirPath;
|
|
278
|
-
break;
|
|
279
|
-
}
|
|
280
|
-
if (dirPath === ".") return;
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
return ret;
|
|
284
|
-
}
|
|
285
|
-
const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
|
|
286
|
-
function getTargetPaths(_type, expOrBundle) {
|
|
287
|
-
const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
|
|
288
|
-
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(
|
|
289
|
-
expOrBundle.browser.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
|
|
290
|
-
), expOrBundle.browser?.require && set.add(
|
|
291
|
-
expOrBundle.browser.require.replace(
|
|
292
|
-
fileEnding,
|
|
293
|
-
type === "commonjs" ? dtsEnding : ctsEnding
|
|
294
|
-
)
|
|
295
|
-
)), expOrBundle.node?.source || (expOrBundle.node?.import && set.add(
|
|
296
|
-
expOrBundle.node.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
|
|
297
|
-
), expOrBundle.node?.require && set.add(
|
|
298
|
-
expOrBundle.node.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)
|
|
299
|
-
))), Array.from(set);
|
|
300
|
-
}
|
|
301
|
-
function isPkgExport$1(exp) {
|
|
302
|
-
return exp?.browser || exp?.node || exp?.default;
|
|
303
|
-
}
|
|
304
|
-
function isRecord(value) {
|
|
305
|
-
return !!value && !Array.isArray(value) && typeof value == "object";
|
|
306
|
-
}
|
|
307
|
-
const pkgExtMap = {
|
|
308
|
-
// pkg.type: "commonjs"
|
|
309
|
-
commonjs: {
|
|
310
|
-
commonjs: defaultEnding,
|
|
311
|
-
esm: mjsEnding
|
|
312
|
-
},
|
|
313
|
-
// pkg.type: "module"
|
|
314
|
-
module: {
|
|
315
|
-
commonjs: cjsEnding,
|
|
316
|
-
esm: defaultEnding
|
|
317
|
-
}
|
|
318
|
-
};
|
|
319
|
-
function validateExports(_exports, options) {
|
|
320
|
-
const { pkg } = options, type = pkg.type || "commonjs", ext = pkgExtMap[type], errors = [];
|
|
321
|
-
for (const exp of _exports)
|
|
322
|
-
exp.require && !exp.require.endsWith(ext.commonjs) && errors.push(
|
|
323
|
-
`package.json with \`type: "${type}"\` - \`exports["${exp._path}"].require\` must end with "${ext.commonjs}"`
|
|
324
|
-
), exp.import && !exp.import.endsWith(ext.esm) && errors.push(
|
|
325
|
-
`package.json with \`type: "${type}"\` - \`exports["${exp._path}"].import\` must end with "${ext.esm}"`
|
|
326
|
-
);
|
|
327
|
-
return errors;
|
|
328
|
-
}
|
|
329
|
-
function parseExports(options) {
|
|
330
|
-
const { cwd, pkg, strict, strictOptions: strictOptions2, logger } = options, type = pkg.type || "commonjs", errors = [], report = (kind, message) => {
|
|
331
|
-
kind === "warn" ? logger.warn(message) : errors.push(message);
|
|
332
|
-
};
|
|
333
|
-
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(
|
|
334
|
-
strictOptions2.alwaysPackageJsonFiles,
|
|
335
|
-
"package.json: `files` should be used over `.npmignore`"
|
|
336
|
-
), pkg.source) {
|
|
337
|
-
if (strict && pkg.exports?.["."] && typeof pkg.exports["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source === pkg.source)
|
|
338
|
-
errors.push(
|
|
339
|
-
'package.json: the "source" property can be removed, as it is equal to exports["."].source.'
|
|
340
|
-
);
|
|
341
|
-
else if (!pkg.exports && pkg.main) {
|
|
342
|
-
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 = [];
|
|
343
|
-
if (pkg.browser) {
|
|
344
|
-
const browserConditions = [];
|
|
345
|
-
pkg.module && pkg.browser?.[pkg.module] ? browserConditions.push(
|
|
346
|
-
` "import": ${JSON.stringify(pkg.browser[pkg.module].replace(fileEnding, extMap.esm))}`
|
|
347
|
-
) : pkg.browser?.[pkg.main] && browserConditions.push(
|
|
348
|
-
` "import": ${JSON.stringify(pkg.browser?.[pkg.main].replace(fileEnding, extMap.esm))}`
|
|
349
|
-
), pkg.browser?.[pkg.main] && browserConditions.push(
|
|
350
|
-
` "require": ${JSON.stringify(pkg.browser[pkg.main].replace(fileEnding, extMap.commonjs))}`
|
|
351
|
-
), browserConditions.length && maybeBrowserCondition.push(
|
|
352
|
-
' "browser": {',
|
|
353
|
-
` "source": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,
|
|
354
|
-
...browserConditions,
|
|
355
|
-
" }"
|
|
356
|
-
);
|
|
357
|
-
}
|
|
358
|
-
errors.push(
|
|
359
|
-
...[
|
|
360
|
-
"package.json: `exports` are missing, it should be:",
|
|
361
|
-
'"exports": {',
|
|
362
|
-
' ".": {',
|
|
363
|
-
` "source": ${JSON.stringify(pkg.source)},`,
|
|
364
|
-
// If browser conditions are detected then add them to the suggestion
|
|
365
|
-
...maybeBrowserCondition.length > 0 ? maybeBrowserCondition : [],
|
|
366
|
-
type === "commonjs" && ` "import": ${JSON.stringify(importExport)},`,
|
|
367
|
-
type === "module" && ` "require": ${JSON.stringify(requireExport)},`,
|
|
368
|
-
` "default": ${JSON.stringify(defaultExport)}`,
|
|
369
|
-
" },",
|
|
370
|
-
' "./package.json": "./package.json"',
|
|
371
|
-
"}"
|
|
372
|
-
].filter(Boolean)
|
|
373
|
-
);
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
if (errors.length)
|
|
377
|
-
throw new Error(`
|
|
378
|
-
- ` + errors.join(`
|
|
379
|
-
- `));
|
|
380
|
-
if (!pkg.exports)
|
|
381
|
-
throw new Error(
|
|
382
|
-
`
|
|
383
|
-
- ` + [
|
|
384
|
-
"package.json: `exports` are missing, please set a minimal configuration, for example:",
|
|
385
|
-
'"exports": {',
|
|
386
|
-
' ".": {',
|
|
387
|
-
' "source": "./src/index.js",',
|
|
388
|
-
' "default": "./dist/index.js"',
|
|
389
|
-
" },",
|
|
390
|
-
' "./package.json": "./package.json"',
|
|
391
|
-
"}"
|
|
392
|
-
].join(`
|
|
393
|
-
- `)
|
|
394
|
-
);
|
|
395
|
-
const _exports = [];
|
|
396
|
-
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(
|
|
397
|
-
strictOptions2.alwaysPackageJsonTypes,
|
|
398
|
-
"package.json: `types` must be declared for the npm listing to show as a TypeScript module."
|
|
399
|
-
), strict && !pkg.exports["./package.json"] && errors.push('package.json: `exports["./package.json"] must be declared.');
|
|
400
|
-
for (const [exportPath, exportEntry] of Object.entries(pkg.exports))
|
|
401
|
-
if (exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json"))
|
|
402
|
-
exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push('package.json: `exports["./package.json"]` must be "./package.json".');
|
|
403
|
-
else if (exportPath.endsWith(".css"))
|
|
404
|
-
typeof exportEntry == "string" && !existsSync(resolve(cwd, exportEntry)) ? errors.push(
|
|
405
|
-
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`
|
|
406
|
-
) : typeof exportEntry != "string" && errors.push(
|
|
407
|
-
`package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
|
|
408
|
-
);
|
|
409
|
-
else if (!(isRecord(exportEntry) && "svelte" in exportEntry))
|
|
410
|
-
if (isPkgExport(exportEntry)) {
|
|
411
|
-
const exp = {
|
|
412
|
-
_exported: !0,
|
|
413
|
-
_path: exportPath,
|
|
414
|
-
...exportEntry
|
|
415
|
-
};
|
|
416
|
-
if (!exp.default) {
|
|
417
|
-
const fallback = type === "module" ? exp.import : exp.require;
|
|
418
|
-
fallback && (exp.default = fallback);
|
|
419
|
-
}
|
|
420
|
-
!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(
|
|
421
|
-
'package.json: mismatch between "main" and "exports.require". These must be equal.'
|
|
422
|
-
), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
|
|
423
|
-
'package.json: mismatch between "module" and "exports.import" These must be equal.'
|
|
424
|
-
)), _exports.push(exp);
|
|
425
|
-
} else isRecord(exportEntry) || errors.push("package.json: exports must be an object");
|
|
426
|
-
if (errors.push(...validateExports(_exports, { pkg })), errors.length)
|
|
427
|
-
throw new Error(`
|
|
428
|
-
- ` + errors.join(`
|
|
429
|
-
- `));
|
|
430
|
-
return _exports;
|
|
431
|
-
}
|
|
432
|
-
function isPkgExport(value) {
|
|
433
|
-
return isRecord(value) && "source" in value && typeof value.source == "string";
|
|
434
|
-
}
|
|
435
|
-
async function loadTSConfig(options) {
|
|
436
|
-
const { cwd, tsconfigPath } = options, configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
|
|
437
|
-
if (!configPath)
|
|
438
|
-
return;
|
|
439
|
-
const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
440
|
-
return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
|
|
441
|
-
}
|
|
442
|
-
function resolveBrowserTarget(versions) {
|
|
443
|
-
const target = versions.filter(
|
|
444
|
-
(version) => version.startsWith("chrome") || version.startsWith("edge") || version.startsWith("firefox") || version.startsWith("ios") || version.startsWith("safari") || version.startsWith("opera")
|
|
445
|
-
);
|
|
446
|
-
if (target.length !== 0)
|
|
447
|
-
return target;
|
|
448
|
-
}
|
|
449
|
-
function resolveNodeTarget(versions) {
|
|
450
|
-
const target = versions.filter((version) => version.startsWith("node"));
|
|
451
|
-
if (target.length !== 0)
|
|
452
|
-
return target;
|
|
453
|
-
}
|
|
454
|
-
const toggle = z.union([z.literal("error"), z.literal("warn"), z.literal("off")]), strictOptions = z.object({
|
|
455
|
-
noPackageJsonTypings: toggle.default("error"),
|
|
456
|
-
noImplicitSideEffects: toggle.default("warn"),
|
|
457
|
-
noImplicitBrowsersList: toggle.default("warn"),
|
|
458
|
-
alwaysPackageJsonTypes: toggle.default("error"),
|
|
459
|
-
alwaysPackageJsonMain: toggle.default("error"),
|
|
460
|
-
alwaysPackageJsonFiles: toggle.default("error")
|
|
461
|
-
}).strict(), validationSchema = z.object({
|
|
462
|
-
strictOptions: strictOptions.default({})
|
|
463
|
-
});
|
|
464
|
-
function parseStrictOptions(input) {
|
|
465
|
-
return validationSchema.parse({ strictOptions: input }, { errorMap }).strictOptions;
|
|
466
|
-
}
|
|
467
|
-
async function resolveBuildContext(options) {
|
|
468
|
-
const {
|
|
469
|
-
config: config2,
|
|
470
|
-
cwd,
|
|
471
|
-
emitDeclarationOnly = !1,
|
|
472
|
-
logger,
|
|
473
|
-
pkg,
|
|
474
|
-
strict,
|
|
475
|
-
tsconfig: tsconfigPath
|
|
476
|
-
} = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config2?.strictOptions ?? {});
|
|
477
|
-
let browserslist2 = pkg.browserslist;
|
|
478
|
-
if (!browserslist2) {
|
|
479
|
-
if (strict && strictOptions2.noImplicitBrowsersList !== "off") {
|
|
480
|
-
if (strictOptions2.noImplicitBrowsersList === "error")
|
|
481
|
-
throw new Error(
|
|
482
|
-
'\n- package.json: "browserslist" is missing, set it to `"browserslist": "extends @sanity/browserslist-config"`'
|
|
483
|
-
);
|
|
484
|
-
logger.warn(
|
|
485
|
-
'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `"browserslist": "extends @sanity/browserslist-config"` to silence this warning.'
|
|
486
|
-
);
|
|
487
|
-
}
|
|
488
|
-
browserslist2 = DEFAULT_BROWSERSLIST_QUERY;
|
|
489
|
-
}
|
|
490
|
-
const targetVersions = browserslistToEsbuild(browserslist2);
|
|
491
|
-
if (strict && strictOptions2.noImplicitSideEffects !== "off" && typeof pkg.sideEffects > "u") {
|
|
492
|
-
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`";
|
|
493
|
-
if (strictOptions2.noImplicitSideEffects === "error")
|
|
494
|
-
throw new Error(msg);
|
|
495
|
-
logger.warn(msg);
|
|
496
|
-
}
|
|
497
|
-
const nodeTarget = resolveNodeTarget(targetVersions), webTarget = resolveBrowserTarget(targetVersions);
|
|
498
|
-
if (!nodeTarget)
|
|
499
|
-
throw new Error("no matching `node` target");
|
|
500
|
-
if (!webTarget)
|
|
501
|
-
throw new Error("no matching `web` target");
|
|
502
|
-
const target = {
|
|
503
|
-
"*": webTarget.concat(nodeTarget),
|
|
504
|
-
browser: webTarget,
|
|
505
|
-
node: nodeTarget
|
|
506
|
-
}, parsedExports = parseExports({
|
|
507
|
-
cwd,
|
|
508
|
-
pkg,
|
|
509
|
-
strict,
|
|
510
|
-
strictOptions: strictOptions2,
|
|
511
|
-
logger
|
|
512
|
-
}).reduce(
|
|
513
|
-
(acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
|
|
514
|
-
{}
|
|
515
|
-
), exports = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
|
|
516
|
-
...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
|
|
517
|
-
...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
|
|
518
|
-
], 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(
|
|
519
|
-
// Do not bundle anything that is marked as external
|
|
520
|
-
(_) => !externalWithTypes.has(_)
|
|
521
|
-
), bundledPackages = config2 && Array.isArray(config2.extract?.bundledPackages) ? [...bundledDependencies, ...config2.extract.bundledPackages] : resolveConfigProperty(config2?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports).flatMap((exportEntry) => [
|
|
522
|
-
exportEntry.import,
|
|
523
|
-
exportEntry.require,
|
|
524
|
-
exportEntry.browser?.import,
|
|
525
|
-
exportEntry.browser?.require,
|
|
526
|
-
exportEntry.node?.source && exportEntry.node.import,
|
|
527
|
-
exportEntry.node?.source && exportEntry.node.require
|
|
528
|
-
].filter(Boolean)).map((p) => path.resolve(cwd, p)), commonDistPath = findCommonDirPath(outputPaths);
|
|
529
|
-
if (commonDistPath === cwd)
|
|
530
|
-
throw new Error(
|
|
531
|
-
"all output files must share a common parent directory which is not the root package directory"
|
|
532
|
-
);
|
|
533
|
-
if (commonDistPath && !pathContains(cwd, commonDistPath))
|
|
534
|
-
throw new Error("all output files must be located within the package");
|
|
535
|
-
const configDistPath = config2?.dist ? path.resolve(cwd, config2.dist) : void 0;
|
|
536
|
-
if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
|
|
537
|
-
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");
|
|
538
|
-
const distPath = configDistPath || commonDistPath;
|
|
539
|
-
if (!distPath)
|
|
540
|
-
throw new Error("could not detect `dist` path");
|
|
541
|
-
return {
|
|
542
|
-
config: config2,
|
|
543
|
-
cwd,
|
|
544
|
-
distPath,
|
|
545
|
-
emitDeclarationOnly,
|
|
546
|
-
exports,
|
|
547
|
-
external,
|
|
548
|
-
bundledPackages,
|
|
549
|
-
files: [],
|
|
550
|
-
logger,
|
|
551
|
-
pkg,
|
|
552
|
-
runtime: config2?.runtime ?? "*",
|
|
553
|
-
strict,
|
|
554
|
-
target,
|
|
555
|
-
ts: {
|
|
556
|
-
config: tsconfig,
|
|
557
|
-
configPath: tsconfigPath
|
|
558
|
-
},
|
|
559
|
-
dts: config2?.dts === "rolldown" ? "rolldown" : "api-extractor"
|
|
560
|
-
};
|
|
561
|
-
}
|
|
562
|
-
function transformPackageName(packageName) {
|
|
563
|
-
if (packageName.startsWith("@types/"))
|
|
564
|
-
return packageName;
|
|
565
|
-
if (packageName.startsWith("@")) {
|
|
566
|
-
const [scope, name] = packageName.split("/");
|
|
567
|
-
return `@types/${scope.slice(1)}__${name}`;
|
|
568
|
-
} else
|
|
569
|
-
return `@types/${packageName}`;
|
|
570
|
-
}
|
|
571
|
-
function resolveBuildTasks(ctx) {
|
|
572
|
-
const { config: config2, pkg, target } = ctx, bundles = config2?.bundles || [], tasks = [], exports = Object.entries(ctx.exports || {}).map(
|
|
573
|
-
([_path, exp]) => ({ _path, ...exp })
|
|
574
|
-
), dtsTask2 = {
|
|
575
|
-
type: "build:dts",
|
|
576
|
-
entries: []
|
|
577
|
-
}, rolldownDtsTask2 = {}, rollupTasks = {};
|
|
578
|
-
function addRollupTaskEntry(format2, runtime, entry) {
|
|
579
|
-
const buildId = `${format2}:${runtime}`;
|
|
580
|
-
ctx.dts === "rolldown" && (rolldownDtsTask2[buildId] ? rolldownDtsTask2[buildId].entries.push(entry) : rolldownDtsTask2[buildId] = {
|
|
581
|
-
type: "rolldown:dts",
|
|
582
|
-
buildId,
|
|
583
|
-
entries: [entry],
|
|
584
|
-
runtime,
|
|
585
|
-
format: format2,
|
|
586
|
-
target: target[runtime]
|
|
587
|
-
}), ctx.emitDeclarationOnly || (rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
|
|
588
|
-
type: "build:js",
|
|
589
|
-
buildId,
|
|
590
|
-
entries: [entry],
|
|
591
|
-
runtime,
|
|
592
|
-
format: format2,
|
|
593
|
-
target: target[runtime]
|
|
594
|
-
});
|
|
595
|
-
}
|
|
596
|
-
if (ctx.dts === "api-extractor") {
|
|
597
|
-
for (const exp of exports) {
|
|
598
|
-
const importId = path.join(pkg.name, exp._path);
|
|
599
|
-
exp.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
600
|
-
importId,
|
|
601
|
-
exportPath: exp._path,
|
|
602
|
-
sourcePath: exp.source,
|
|
603
|
-
targetPaths: getTargetPaths(pkg.type, exp)
|
|
604
|
-
}), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
605
|
-
importId,
|
|
606
|
-
exportPath: exp._path,
|
|
607
|
-
sourcePath: exp.browser.source,
|
|
608
|
-
targetPaths: getTargetPaths(pkg.type, exp.browser)
|
|
609
|
-
}), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
610
|
-
importId,
|
|
611
|
-
exportPath: exp._path,
|
|
612
|
-
sourcePath: exp.node.source,
|
|
613
|
-
targetPaths: getTargetPaths(pkg.type, exp.node)
|
|
614
|
-
});
|
|
615
|
-
}
|
|
616
|
-
for (const bundle of bundles)
|
|
617
|
-
if (bundle.source?.endsWith(".ts")) {
|
|
618
|
-
const exportPath = (bundle.import || bundle.require).replace(/\.[mc]?js$/, ""), importId = path.join(pkg.name, exportPath);
|
|
619
|
-
dtsTask2.entries.push({
|
|
620
|
-
importId,
|
|
621
|
-
exportPath,
|
|
622
|
-
sourcePath: bundle.source,
|
|
623
|
-
targetPaths: getTargetPaths(pkg.type, bundle)
|
|
624
|
-
});
|
|
625
|
-
}
|
|
626
|
-
dtsTask2.entries.length && tasks.push(dtsTask2);
|
|
627
|
-
}
|
|
628
|
-
for (const exp of exports) {
|
|
629
|
-
const output = exp.require;
|
|
630
|
-
output && addRollupTaskEntry("commonjs", ctx.runtime, {
|
|
631
|
-
path: exp._path,
|
|
632
|
-
source: exp.source,
|
|
633
|
-
output
|
|
634
|
-
});
|
|
635
|
-
}
|
|
636
|
-
for (const exp of exports) {
|
|
637
|
-
const output = exp.import;
|
|
638
|
-
output && addRollupTaskEntry("esm", ctx.runtime, {
|
|
639
|
-
path: exp._path,
|
|
640
|
-
source: exp.source,
|
|
641
|
-
output
|
|
642
|
-
});
|
|
643
|
-
}
|
|
644
|
-
for (const exp of exports) {
|
|
645
|
-
const output = exp.browser?.require;
|
|
646
|
-
output && addRollupTaskEntry("commonjs", "browser", {
|
|
647
|
-
path: exp._path,
|
|
648
|
-
source: exp.browser?.source || exp.source,
|
|
649
|
-
output
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
for (const exp of exports) {
|
|
653
|
-
const output = exp.browser?.import;
|
|
654
|
-
output && addRollupTaskEntry("esm", "browser", {
|
|
655
|
-
path: exp._path,
|
|
656
|
-
source: exp.browser?.source || exp.source,
|
|
657
|
-
output
|
|
658
|
-
});
|
|
659
|
-
}
|
|
660
|
-
for (const bundle of bundles) {
|
|
661
|
-
const idx = bundles.indexOf(bundle);
|
|
662
|
-
bundle.require && addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
|
|
663
|
-
path: `__$$bundle_cjs_${idx}$$__`,
|
|
664
|
-
source: bundle.source,
|
|
665
|
-
output: bundle.require
|
|
666
|
-
}), bundle.import && addRollupTaskEntry("esm", bundle.runtime || ctx.runtime, {
|
|
667
|
-
path: `__$$bundle_esm_${idx}$$__`,
|
|
668
|
-
source: bundle.source,
|
|
669
|
-
output: bundle.import
|
|
670
|
-
});
|
|
671
|
-
}
|
|
672
|
-
return tasks.push(...Object.values(rolldownDtsTask2)), tasks.push(...Object.values(rollupTasks)), tasks;
|
|
673
|
-
}
|
|
674
|
-
function createSpinner(msg) {
|
|
675
|
-
const startTime = Date.now();
|
|
676
|
-
return console.log(msg), {
|
|
677
|
-
complete: () => {
|
|
678
|
-
console.log(`${chalk.green("[success]")} ${chalk.gray(`${Date.now() - startTime}ms`)}`);
|
|
679
|
-
},
|
|
680
|
-
error: () => {
|
|
681
|
-
console.log(`${chalk.red("[error]")} ${chalk.gray(`${Date.now() - startTime}ms`)}`);
|
|
682
|
-
}
|
|
683
|
-
};
|
|
684
|
-
}
|
|
685
26
|
function printExtractMessages(ctx, messages) {
|
|
686
27
|
const { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === "warning");
|
|
687
28
|
warnings.length && logger.log();
|
|
@@ -978,7 +319,7 @@ async function extractTypes(options) {
|
|
|
978
319
|
return shouldCleanUpDts && await fs.unlink(typesPath), { extractorResult, messages };
|
|
979
320
|
}
|
|
980
321
|
async function doExtract(ctx, task) {
|
|
981
|
-
const { config
|
|
322
|
+
const { config, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
|
|
982
323
|
if (!ts2.config || !ts2.configPath)
|
|
983
324
|
return { type: "dts", messages: [], results: [] };
|
|
984
325
|
const { outDir, rootDir = cwd } = ts2.config.options;
|
|
@@ -993,18 +334,18 @@ async function doExtract(ctx, task) {
|
|
|
993
334
|
path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
|
|
994
335
|
), targetPaths = entry.targetPaths.map((targetPath) => path.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path.relative(outDir, targetPath)), result = await extractTypes({
|
|
995
336
|
bundledPackages: bundledPackages || [],
|
|
996
|
-
customTags:
|
|
337
|
+
customTags: config?.extract?.customTags,
|
|
997
338
|
distPath: outDir,
|
|
998
339
|
exportPath,
|
|
999
340
|
files,
|
|
1000
341
|
filePaths,
|
|
1001
342
|
projectPath: cwd,
|
|
1002
|
-
rules:
|
|
343
|
+
rules: config?.extract?.rules,
|
|
1003
344
|
sourceTypesPath,
|
|
1004
345
|
tsconfig: ts2.config,
|
|
1005
346
|
tmpPath,
|
|
1006
347
|
tsconfigPath: path.resolve(cwd, ts2.configPath || "tsconfig.json"),
|
|
1007
|
-
extractorDisabled:
|
|
348
|
+
extractorDisabled: config?.extract?.enabled === !1
|
|
1008
349
|
});
|
|
1009
350
|
messages.push(...result.messages);
|
|
1010
351
|
const errors = result.messages.filter((msg) => msg.logLevel === "error");
|
|
@@ -1049,7 +390,7 @@ const dtsTask = {
|
|
|
1049
390
|
].join(`
|
|
1050
391
|
`),
|
|
1051
392
|
exec: (ctx, task) => {
|
|
1052
|
-
const { config
|
|
393
|
+
const { config, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
|
|
1053
394
|
return new Observable((observer) => {
|
|
1054
395
|
if (!tsContext.config || !tsContext.configPath) {
|
|
1055
396
|
observer.next({ type: "dts", messages: [], results: [] }), observer.complete();
|
|
@@ -1103,19 +444,19 @@ const dtsTask = {
|
|
|
1103
444
|
try {
|
|
1104
445
|
const result = await extractTypes({
|
|
1105
446
|
bundledPackages: bundledPackages || [],
|
|
1106
|
-
customTags:
|
|
447
|
+
customTags: config?.extract?.customTags,
|
|
1107
448
|
cwd,
|
|
1108
449
|
distPath: outDir,
|
|
1109
450
|
exportPath,
|
|
1110
451
|
files,
|
|
1111
452
|
filePaths,
|
|
1112
453
|
projectPath: cwd,
|
|
1113
|
-
rules:
|
|
454
|
+
rules: config?.extract?.rules,
|
|
1114
455
|
sourceTypesPath,
|
|
1115
456
|
tsconfig: tsContext.config,
|
|
1116
457
|
tmpPath,
|
|
1117
458
|
tsconfigPath: path.resolve(cwd, tsContext.configPath || "tsconfig.json"),
|
|
1118
|
-
extractorDisabled:
|
|
459
|
+
extractorDisabled: config?.extract?.enabled === !1
|
|
1119
460
|
});
|
|
1120
461
|
messages.push(...result.messages), results.push({ sourcePath: path.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
|
|
1121
462
|
} catch (err) {
|
|
@@ -1149,21 +490,7 @@ const dtsTask = {
|
|
|
1149
490
|
const { logger } = ctx;
|
|
1150
491
|
err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
|
|
1151
492
|
}
|
|
1152
|
-
}
|
|
1153
|
-
function createConsoleSpy(options) {
|
|
1154
|
-
const { onRestored } = options || {}, original = {
|
|
1155
|
-
log: console.log,
|
|
1156
|
-
warn: console.warn,
|
|
1157
|
-
error: console.error
|
|
1158
|
-
}, messages = [];
|
|
1159
|
-
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 }), {
|
|
1160
|
-
messages,
|
|
1161
|
-
restore: () => {
|
|
1162
|
-
console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
|
|
1163
|
-
}
|
|
1164
|
-
};
|
|
1165
|
-
}
|
|
1166
|
-
const rolldownDtsTask = {
|
|
493
|
+
}, rolldownDtsTask = {
|
|
1167
494
|
name: (ctx, task) => {
|
|
1168
495
|
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 ? [
|
|
1169
496
|
" bundles:",
|
|
@@ -1246,14 +573,14 @@ function replaceFileEnding(path2) {
|
|
|
1246
573
|
}
|
|
1247
574
|
}
|
|
1248
575
|
function resolveRollupConfig(ctx, buildTask) {
|
|
1249
|
-
const { format
|
|
576
|
+
const { format, runtime, target } = buildTask, { config, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format], minify = config?.minify ?? !1, outDir = path.relative(cwd, distPath), pathAliases = Object.fromEntries(
|
|
1250
577
|
Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
|
|
1251
578
|
), entries = buildTask.entries.map((entry) => ({
|
|
1252
579
|
...entry,
|
|
1253
580
|
name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
|
|
1254
581
|
}), {}), 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(
|
|
1255
|
-
Object.entries(
|
|
1256
|
-
), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } =
|
|
582
|
+
Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
|
|
583
|
+
), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config?.rollup || {}, defaultPlugins = [
|
|
1257
584
|
replace({
|
|
1258
585
|
preventAssignment: !0,
|
|
1259
586
|
values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
|
|
@@ -1263,7 +590,7 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
1263
590
|
path.relative(cwd, path.resolve(outDir, entry.name + outputExt))
|
|
1264
591
|
) : (console.error(`could not find source entry: ${sourcePath}`), "null");
|
|
1265
592
|
},
|
|
1266
|
-
"process.env.PKG_FORMAT": JSON.stringify(
|
|
593
|
+
"process.env.PKG_FORMAT": JSON.stringify(format),
|
|
1267
594
|
"process.env.PKG_RUNTIME": JSON.stringify(runtime),
|
|
1268
595
|
"process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
|
|
1269
596
|
...replacements
|
|
@@ -1279,14 +606,14 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
1279
606
|
}),
|
|
1280
607
|
commonjs(),
|
|
1281
608
|
json(),
|
|
1282
|
-
(
|
|
609
|
+
(config?.babel?.reactCompiler || config?.babel?.styledComponents) && babel({
|
|
1283
610
|
babelrc: !1,
|
|
1284
611
|
presets: ["@babel/preset-typescript"],
|
|
1285
612
|
babelHelpers: "bundled",
|
|
1286
613
|
extensions: [".ts", ".tsx", ".js", ".jsx"],
|
|
1287
614
|
plugins: [
|
|
1288
615
|
// The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
|
|
1289
|
-
|
|
616
|
+
config?.babel?.styledComponents && [
|
|
1290
617
|
"babel-plugin-styled-components",
|
|
1291
618
|
{
|
|
1292
619
|
// 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``"
|
|
@@ -1297,35 +624,35 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
1297
624
|
pure: !0,
|
|
1298
625
|
// disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
|
|
1299
626
|
cssProp: !1,
|
|
1300
|
-
...typeof
|
|
627
|
+
...typeof config.babel.styledComponents == "object" ? config.babel.styledComponents : {}
|
|
1301
628
|
}
|
|
1302
629
|
],
|
|
1303
|
-
|
|
630
|
+
config?.babel?.reactCompiler && [
|
|
1304
631
|
"babel-plugin-react-compiler",
|
|
1305
|
-
|
|
632
|
+
config?.reactCompilerOptions || {}
|
|
1306
633
|
]
|
|
1307
634
|
].filter(Boolean)
|
|
1308
635
|
}),
|
|
1309
636
|
esbuild({
|
|
1310
|
-
jsx:
|
|
1311
|
-
jsxFactory:
|
|
1312
|
-
jsxFragment:
|
|
1313
|
-
jsxImportSource:
|
|
637
|
+
jsx: config?.jsx ?? "automatic",
|
|
638
|
+
jsxFactory: config?.jsxFactory ?? "createElement",
|
|
639
|
+
jsxFragment: config?.jsxFragment ?? "Fragment",
|
|
640
|
+
jsxImportSource: config?.jsxImportSource ?? "react",
|
|
1314
641
|
target,
|
|
1315
642
|
tsconfig: ctx.ts.configPath || "tsconfig.json",
|
|
1316
643
|
treeShaking: !0,
|
|
1317
|
-
minifySyntax:
|
|
644
|
+
minifySyntax: config?.minify !== !1,
|
|
1318
645
|
supported: {
|
|
1319
646
|
"template-literal": !0
|
|
1320
647
|
}
|
|
1321
648
|
}),
|
|
1322
|
-
Array.isArray(
|
|
649
|
+
Array.isArray(config?.babel?.plugins) && getBabelOutputPlugin({
|
|
1323
650
|
babelrc: !1,
|
|
1324
|
-
plugins:
|
|
651
|
+
plugins: config.babel.plugins
|
|
1325
652
|
}),
|
|
1326
653
|
enableOptimizeLodash && optimizeLodashImports({
|
|
1327
|
-
useLodashEs:
|
|
1328
|
-
...typeof
|
|
654
|
+
useLodashEs: format === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
|
|
655
|
+
...typeof config?.rollup?.optimizeLodash == "boolean" ? {} : config?.rollup?.optimizeLodash
|
|
1329
656
|
}),
|
|
1330
657
|
minify && terser({
|
|
1331
658
|
compress: { directives: !1, passes: 10 },
|
|
@@ -1338,7 +665,7 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
1338
665
|
preserve_annotations: !0
|
|
1339
666
|
}
|
|
1340
667
|
})
|
|
1341
|
-
].filter(Boolean), userPlugins =
|
|
668
|
+
].filter(Boolean), userPlugins = config?.rollup?.plugins, plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty(config?.rollup?.plugins, defaultPlugins), hashChunkFileNames = config?.rollup?.hashChunkFileNames ?? !1, chunkFileNames = `${hashChunkFileNames ? "_chunks" : "_chunks-[format]"}/${hashChunkFileNames ? "[name]-[hash]" : "[name]"}${outputExt}`, entryFileNames = `[name]${outputExt}`;
|
|
1342
669
|
return {
|
|
1343
670
|
inputOptions: {
|
|
1344
671
|
context: cwd,
|
|
@@ -1372,9 +699,9 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
1372
699
|
preset: "recommended",
|
|
1373
700
|
propertyReadSideEffects: !1,
|
|
1374
701
|
moduleSideEffects: "no-external",
|
|
1375
|
-
...
|
|
702
|
+
...config?.rollup?.treeshake
|
|
1376
703
|
},
|
|
1377
|
-
experimentalLogSideEffects:
|
|
704
|
+
experimentalLogSideEffects: config?.rollup?.experimentalLogSideEffects
|
|
1378
705
|
},
|
|
1379
706
|
outputOptions: {
|
|
1380
707
|
chunkFileNames,
|
|
@@ -1382,12 +709,12 @@ function resolveRollupConfig(ctx, buildTask) {
|
|
|
1382
709
|
dir: outDir,
|
|
1383
710
|
entryFileNames,
|
|
1384
711
|
esModule: !0,
|
|
1385
|
-
format
|
|
712
|
+
format,
|
|
1386
713
|
interop: "compat",
|
|
1387
|
-
sourcemap:
|
|
714
|
+
sourcemap: config?.sourcemap ?? !0,
|
|
1388
715
|
hoistTransitiveImports: !1,
|
|
1389
716
|
minifyInternalExports: minify,
|
|
1390
|
-
...
|
|
717
|
+
...config?.rollup?.output
|
|
1391
718
|
}
|
|
1392
719
|
};
|
|
1393
720
|
}
|
|
@@ -1477,7 +804,7 @@ const rollupWatchTask = {
|
|
|
1477
804
|
const watchOptions = {
|
|
1478
805
|
...inputOptions,
|
|
1479
806
|
output: outputOptions
|
|
1480
|
-
}, watcher = watch
|
|
807
|
+
}, watcher = watch(watchOptions);
|
|
1481
808
|
return watcher.on("event", (event) => {
|
|
1482
809
|
observer.next(event);
|
|
1483
810
|
}), () => {
|
|
@@ -1512,810 +839,9 @@ const rollupWatchTask = {
|
|
|
1512
839
|
"watch:dts": dtsWatchTask,
|
|
1513
840
|
"watch:js": rollupWatchTask
|
|
1514
841
|
};
|
|
1515
|
-
async function build(options) {
|
|
1516
|
-
const {
|
|
1517
|
-
cwd,
|
|
1518
|
-
emitDeclarationOnly,
|
|
1519
|
-
strict = !1,
|
|
1520
|
-
tsconfig: tsconfigOption,
|
|
1521
|
-
clean = !1
|
|
1522
|
-
} = options, logger = createLogger(), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({
|
|
1523
|
-
config: config2,
|
|
1524
|
-
cwd,
|
|
1525
|
-
emitDeclarationOnly,
|
|
1526
|
-
logger,
|
|
1527
|
-
pkg,
|
|
1528
|
-
strict,
|
|
1529
|
-
tsconfig
|
|
1530
|
-
});
|
|
1531
|
-
clean && (logger.log(
|
|
1532
|
-
`Deleting the \`dist\` folder: './${path.relative(cwd, ctx.distPath)}' before building...`
|
|
1533
|
-
), await rimraf$1(ctx.distPath));
|
|
1534
|
-
const buildTasks = resolveBuildTasks(ctx);
|
|
1535
|
-
for (const task of buildTasks) {
|
|
1536
|
-
const handler = buildTaskHandlers[task.type], taskName = handler.name(ctx, task), spinner = createSpinner(taskName);
|
|
1537
|
-
try {
|
|
1538
|
-
const result = await handler.exec(ctx, task).toPromise();
|
|
1539
|
-
spinner.complete(), ctx.logger.log(), handler.complete(ctx, task, result);
|
|
1540
|
-
} catch (err) {
|
|
1541
|
-
if (spinner.error(), err instanceof Error) {
|
|
1542
|
-
const RE_CWD = new RegExp(`${cwd}`, "g");
|
|
1543
|
-
ctx.logger.error(err.message.replace(RE_CWD, ".")), ctx.logger.log();
|
|
1544
|
-
}
|
|
1545
|
-
handler.error(ctx, task, err), process.exit(1);
|
|
1546
|
-
}
|
|
1547
|
-
}
|
|
1548
|
-
}
|
|
1549
|
-
function getFilesize(file) {
|
|
1550
|
-
const stats = statSync(file);
|
|
1551
|
-
return prettyBytes(stats.size);
|
|
1552
|
-
}
|
|
1553
|
-
function getFileInfo(cwd, filePath) {
|
|
1554
|
-
const p = path.resolve(cwd, filePath), exists = fileExists(p), size = exists ? getFilesize(p) : void 0;
|
|
1555
|
-
return { exists, size };
|
|
1556
|
-
}
|
|
1557
|
-
function printPackageTree(ctx) {
|
|
1558
|
-
const { cwd, exports, logger, pkg } = ctx;
|
|
1559
|
-
if (!exports) return;
|
|
1560
|
-
logger.log(`${chalk.blue(pkg.name)}@${chalk.green(pkg.version)}`);
|
|
1561
|
-
const tree = {};
|
|
1562
|
-
pkg.type && (tree.type = chalk.yellow(pkg.type)), pkg.bin && (tree.bin = Object.fromEntries(
|
|
1563
|
-
Object.entries(pkg.bin).map(([name, file]) => [chalk.cyan(name), fileInfo(file)])
|
|
1564
|
-
));
|
|
1565
|
-
function fileInfo(file) {
|
|
1566
|
-
const info = getFileInfo(cwd, file);
|
|
1567
|
-
return info.size ? `${chalk.yellow(file)} ${chalk.gray(info.size)}` : `${chalk.gray(file)} ${chalk.red("does not exist")}`;
|
|
1568
|
-
}
|
|
1569
|
-
tree.exports = Object.fromEntries(
|
|
1570
|
-
Object.entries(exports).filter(([, entry]) => entry._exported).map(([exportPath, entry]) => {
|
|
1571
|
-
const exp = {
|
|
1572
|
-
source: fileInfo(entry.source),
|
|
1573
|
-
browser: void 0,
|
|
1574
|
-
require: void 0,
|
|
1575
|
-
node: void 0,
|
|
1576
|
-
import: void 0,
|
|
1577
|
-
default: fileInfo(entry.default)
|
|
1578
|
-
};
|
|
1579
|
-
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];
|
|
1580
|
-
})
|
|
1581
|
-
), logger.log(treeify.asTree(tree, !0, !0));
|
|
1582
|
-
}
|
|
1583
|
-
async function check(options) {
|
|
1584
|
-
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 });
|
|
1585
|
-
if (printPackageTree(ctx), strict) {
|
|
1586
|
-
const missingFiles = [];
|
|
1587
|
-
for (const [, exp] of Object.entries(ctx.exports || {}))
|
|
1588
|
-
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);
|
|
1589
|
-
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));
|
|
1590
|
-
const exportPaths = {
|
|
1591
|
-
require: [],
|
|
1592
|
-
import: []
|
|
1593
|
-
};
|
|
1594
|
-
for (const exp of Object.values(ctx.exports || {}))
|
|
1595
|
-
exp._exported && (exp.require && exportPaths.require.push(exp.require), exp.import && exportPaths.import.push(exp.import));
|
|
1596
|
-
const external = [
|
|
1597
|
-
...Object.keys(pkg.dependencies || {}),
|
|
1598
|
-
...Object.keys(pkg.devDependencies || {})
|
|
1599
|
-
], consoleSpy = createConsoleSpy();
|
|
1600
|
-
exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger }), exportPaths.require.length && checkExports(exportPaths.require, { cwd, external, format: "cjs", logger }), consoleSpy.restore();
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
|
-
async function checkExports(exportPaths, options) {
|
|
1604
|
-
const { cwd, external, format: format2, logger } = options, code = exportPaths.map((id) => format2 ? `import('${id}');` : `require('${id}');`).join(`
|
|
1605
|
-
`);
|
|
1606
|
-
try {
|
|
1607
|
-
const esbuildResult = await esbuild$1.build({
|
|
1608
|
-
bundle: !0,
|
|
1609
|
-
external,
|
|
1610
|
-
format: format2,
|
|
1611
|
-
logLevel: "silent",
|
|
1612
|
-
// otherwise output maps to stdout as we're using stdin
|
|
1613
|
-
outfile: "/dev/null",
|
|
1614
|
-
platform: "node",
|
|
1615
|
-
stdin: {
|
|
1616
|
-
contents: code,
|
|
1617
|
-
loader: "js",
|
|
1618
|
-
resolveDir: cwd
|
|
1619
|
-
}
|
|
1620
|
-
});
|
|
1621
|
-
if (esbuildResult.errors.length > 0) {
|
|
1622
|
-
for (const msg of esbuildResult.errors)
|
|
1623
|
-
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
1624
|
-
process.exit(1);
|
|
1625
|
-
}
|
|
1626
|
-
const esbuildWarnings = esbuildResult.warnings.filter((msg) => {
|
|
1627
|
-
(msg.detail || msg.text).includes("does not affect esbuild's own target setting");
|
|
1628
|
-
});
|
|
1629
|
-
for (const msg of esbuildWarnings)
|
|
1630
|
-
printEsbuildMessage(logger.warn, msg), logger.log();
|
|
1631
|
-
} catch (err) {
|
|
1632
|
-
if (isEsbuildFailure(err)) {
|
|
1633
|
-
const { errors } = err;
|
|
1634
|
-
for (const msg of errors)
|
|
1635
|
-
printEsbuildMessage(logger.error, msg), logger.log();
|
|
1636
|
-
} else err instanceof Error ? (logger.error(err.stack || err.message), logger.log()) : (logger.error(`${err}`), logger.log());
|
|
1637
|
-
process.exit(1);
|
|
1638
|
-
}
|
|
1639
|
-
}
|
|
1640
|
-
function printEsbuildMessage(log, msg) {
|
|
1641
|
-
msg.location ? log(
|
|
1642
|
-
[
|
|
1643
|
-
`${msg.detail || msg.text}
|
|
1644
|
-
`,
|
|
1645
|
-
`${msg.location.line} | ${msg.location.lineText}
|
|
1646
|
-
`,
|
|
1647
|
-
`in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`
|
|
1648
|
-
].join("")
|
|
1649
|
-
) : log(msg.detail || msg.text);
|
|
1650
|
-
}
|
|
1651
|
-
function isEsbuildFailure(err) {
|
|
1652
|
-
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);
|
|
1653
|
-
}
|
|
1654
|
-
function isEsbuildMessage(msg) {
|
|
1655
|
-
return typeof msg == "object" && msg !== null && "text" in msg && typeof msg.text == "string" && "location" in msg && (msg.location === null || typeof msg.location == "object");
|
|
1656
|
-
}
|
|
1657
|
-
function defineConfig(configOptions) {
|
|
1658
|
-
return configOptions;
|
|
1659
|
-
}
|
|
1660
|
-
function defineTemplateOption(option) {
|
|
1661
|
-
return option;
|
|
1662
|
-
}
|
|
1663
|
-
const promptsTypes = {
|
|
1664
|
-
string: "text"
|
|
1665
|
-
};
|
|
1666
|
-
async function createFromTemplate(options) {
|
|
1667
|
-
const { cwd, logger, packagePath, template: templateOrResolver } = options, template = typeof templateOrResolver == "function" ? await templateOrResolver({ cwd, logger, packagePath }) : templateOrResolver;
|
|
1668
|
-
logger.log("create new package at", relative(cwd, packagePath));
|
|
1669
|
-
const templateOptions = {};
|
|
1670
|
-
for (const templateOption of template.options) {
|
|
1671
|
-
const templateValidate = templateOption.validate, res = await prompts(
|
|
1672
|
-
{
|
|
1673
|
-
type: promptsTypes[templateOption.type],
|
|
1674
|
-
name: templateOption.name,
|
|
1675
|
-
message: templateOption.description,
|
|
1676
|
-
validate: templateValidate ? (prev) => templateValidate(prev) : void 0,
|
|
1677
|
-
initial: typeof templateOption.initial == "function" ? templateOption.initial(templateOptions) : templateOption.initial
|
|
1678
|
-
},
|
|
1679
|
-
{ onCancel: () => process.exit(0) }
|
|
1680
|
-
);
|
|
1681
|
-
templateOptions[templateOption.name] = templateOption.parse ? templateOption.parse(res[templateOption.name]) : res[templateOption.name];
|
|
1682
|
-
}
|
|
1683
|
-
const features = {};
|
|
1684
|
-
for (const templateFeature of template.features) {
|
|
1685
|
-
const res = templateFeature.optional ? await prompts(
|
|
1686
|
-
{
|
|
1687
|
-
type: "confirm",
|
|
1688
|
-
name: "confirm",
|
|
1689
|
-
message: `use ${templateFeature.name}?`,
|
|
1690
|
-
initial: templateFeature.initial
|
|
1691
|
-
},
|
|
1692
|
-
{ onCancel: () => process.exit(0) }
|
|
1693
|
-
) : void 0;
|
|
1694
|
-
features[templateFeature.name] = res?.confirm || !templateFeature.optional;
|
|
1695
|
-
}
|
|
1696
|
-
const files = await template.getFiles(templateOptions, features);
|
|
1697
|
-
files.sort((a, b) => a.name.localeCompare(b.name));
|
|
1698
|
-
for (const file of files) {
|
|
1699
|
-
const filePath = resolve(packagePath, file.name);
|
|
1700
|
-
await mkdirp(dirname(filePath)), await writeFile(filePath, file.contents.trim() + `
|
|
1701
|
-
`), logger.success(`wrote ${relative(cwd, filePath)}`);
|
|
1702
|
-
}
|
|
1703
|
-
}
|
|
1704
|
-
async function isEmptyDirectory(dirPath) {
|
|
1705
|
-
return (await readdir(dirPath)).length === 0;
|
|
1706
|
-
}
|
|
1707
|
-
const overridableDefaults = {
|
|
1708
|
-
endOfLine: "lf",
|
|
1709
|
-
tabWidth: 2,
|
|
1710
|
-
useTabs: !1
|
|
1711
|
-
}, config = {
|
|
1712
|
-
...overridableDefaults,
|
|
1713
|
-
printWidth: 100,
|
|
1714
|
-
semi: !1,
|
|
1715
|
-
singleQuote: !0,
|
|
1716
|
-
quoteProps: "consistent",
|
|
1717
|
-
bracketSpacing: !1,
|
|
1718
|
-
plugins: ["prettier-plugin-packagejson"],
|
|
1719
|
-
overrides: [
|
|
1720
|
-
{
|
|
1721
|
-
files: ["*.json5"],
|
|
1722
|
-
options: {
|
|
1723
|
-
quoteProps: "preserve",
|
|
1724
|
-
singleQuote: !1
|
|
1725
|
-
}
|
|
1726
|
-
},
|
|
1727
|
-
{
|
|
1728
|
-
files: ["*.yml"],
|
|
1729
|
-
options: {
|
|
1730
|
-
singleQuote: !1
|
|
1731
|
-
}
|
|
1732
|
-
}
|
|
1733
|
-
]
|
|
1734
|
-
}, RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i, defaultTemplate = async ({ cwd, logger, packagePath }) => {
|
|
1735
|
-
const gitConfig = getGitUserConfig(cwd);
|
|
1736
|
-
return {
|
|
1737
|
-
options: [
|
|
1738
|
-
{
|
|
1739
|
-
name: "repo",
|
|
1740
|
-
type: "string",
|
|
1741
|
-
description: "git url",
|
|
1742
|
-
validate: (v) => {
|
|
1743
|
-
if (!v) return !0;
|
|
1744
|
-
try {
|
|
1745
|
-
return gitUrlParse(v), !0;
|
|
1746
|
-
} catch {
|
|
1747
|
-
return "invalid git url";
|
|
1748
|
-
}
|
|
1749
|
-
},
|
|
1750
|
-
parse: (v) => {
|
|
1751
|
-
if (!v) return null;
|
|
1752
|
-
const result = gitUrlParse(v);
|
|
1753
|
-
return { source: result.source, owner: result.owner, name: result.name };
|
|
1754
|
-
}
|
|
1755
|
-
},
|
|
1756
|
-
{
|
|
1757
|
-
name: "pkgName",
|
|
1758
|
-
type: "string",
|
|
1759
|
-
description: "package name",
|
|
1760
|
-
initial: (options) => options.repo?.name || void 0,
|
|
1761
|
-
validate: (v) => v ? RE_NAME.exec(v) ? !0 : "invalid package name" : "package name is required",
|
|
1762
|
-
parse: (v) => {
|
|
1763
|
-
if (!v)
|
|
1764
|
-
throw new Error("package name is required");
|
|
1765
|
-
if (!RE_NAME.exec(v))
|
|
1766
|
-
throw new Error("invalid package name");
|
|
1767
|
-
const [scope, name] = v.split("/");
|
|
1768
|
-
return { scope, name, fullName: v };
|
|
1769
|
-
}
|
|
1770
|
-
},
|
|
1771
|
-
{
|
|
1772
|
-
name: "description",
|
|
1773
|
-
type: "string",
|
|
1774
|
-
description: "package description"
|
|
1775
|
-
},
|
|
1776
|
-
{
|
|
1777
|
-
name: "authorName",
|
|
1778
|
-
type: "string",
|
|
1779
|
-
description: "package author name",
|
|
1780
|
-
initial: gitConfig.user
|
|
1781
|
-
},
|
|
1782
|
-
{
|
|
1783
|
-
name: "authorEmail",
|
|
1784
|
-
type: "string",
|
|
1785
|
-
description: "package author email",
|
|
1786
|
-
initial: gitConfig.email
|
|
1787
|
-
},
|
|
1788
|
-
{
|
|
1789
|
-
name: "license",
|
|
1790
|
-
type: "string",
|
|
1791
|
-
description: "package license",
|
|
1792
|
-
initial: "MIT",
|
|
1793
|
-
validate: (v) => v ? !0 : "license is required"
|
|
1794
|
-
}
|
|
1795
|
-
],
|
|
1796
|
-
features: [
|
|
1797
|
-
{
|
|
1798
|
-
name: "eslint",
|
|
1799
|
-
optional: !0,
|
|
1800
|
-
initial: !0
|
|
1801
|
-
},
|
|
1802
|
-
{
|
|
1803
|
-
name: "prettier",
|
|
1804
|
-
optional: !0,
|
|
1805
|
-
initial: !0
|
|
1806
|
-
},
|
|
1807
|
-
{
|
|
1808
|
-
name: "typescript",
|
|
1809
|
-
optional: !0,
|
|
1810
|
-
initial: !0
|
|
1811
|
-
}
|
|
1812
|
-
],
|
|
1813
|
-
async getFiles(options, features) {
|
|
1814
|
-
const { pkgName, repo } = options, { fullName: name } = pkgName, author = [options.authorName, options.authorEmail && `<${options.authorEmail}>`].filter(Boolean).join(" ") ?? void 0, pkgJson = {
|
|
1815
|
-
name,
|
|
1816
|
-
version: "0.0.0",
|
|
1817
|
-
description: options.description ?? void 0,
|
|
1818
|
-
keywords: [],
|
|
1819
|
-
homepage: void 0,
|
|
1820
|
-
bugs: void 0,
|
|
1821
|
-
repository: void 0,
|
|
1822
|
-
license: options.license,
|
|
1823
|
-
author,
|
|
1824
|
-
sideEffects: !1,
|
|
1825
|
-
type: "module",
|
|
1826
|
-
exports: {
|
|
1827
|
-
".": {
|
|
1828
|
-
source: features.typescript ? "./src/index.ts" : "./src/index.js",
|
|
1829
|
-
require: "./dist/index.cjs",
|
|
1830
|
-
default: "./dist/index.js"
|
|
1831
|
-
},
|
|
1832
|
-
"./package.json": "./package.json"
|
|
1833
|
-
},
|
|
1834
|
-
main: "./dist/index.cjs",
|
|
1835
|
-
module: "./dist/index.js",
|
|
1836
|
-
types: void 0,
|
|
1837
|
-
files: ["dist", "src"],
|
|
1838
|
-
scripts: {
|
|
1839
|
-
build: "pkg build --strict --clean --check",
|
|
1840
|
-
format: features.prettier ? "prettier --write --cache --ignore-unknown ." : void 0
|
|
1841
|
-
},
|
|
1842
|
-
"lint-staged": features.prettier ? {
|
|
1843
|
-
"*": ["prettier --write --cache --ignore-unknown"]
|
|
1844
|
-
} : void 0,
|
|
1845
|
-
browserslist: "extends @sanity/browserslist-config",
|
|
1846
|
-
prettier: features.prettier ? "@sanity/prettier-config" : void 0,
|
|
1847
|
-
dependencies: {},
|
|
1848
|
-
devDependencies: {
|
|
1849
|
-
"@sanity/pkg-utils": "^6",
|
|
1850
|
-
"@sanity/prettier-config": features.prettier ? "^1" : void 0,
|
|
1851
|
-
"@typescript-eslint/eslint-plugin": void 0,
|
|
1852
|
-
"@typescript-eslint/parser": void 0,
|
|
1853
|
-
eslint: void 0,
|
|
1854
|
-
"eslint-config-prettier": void 0,
|
|
1855
|
-
"eslint-plugin-import": void 0,
|
|
1856
|
-
"eslint-plugin-prettier": void 0,
|
|
1857
|
-
"eslint-plugin-simple-import-sort": void 0,
|
|
1858
|
-
"lint-staged": "^15",
|
|
1859
|
-
prettier: features.prettier ? "^3" : void 0,
|
|
1860
|
-
typescript: void 0
|
|
1861
|
-
},
|
|
1862
|
-
engines: {
|
|
1863
|
-
node: ">=18.0.0"
|
|
1864
|
-
}
|
|
1865
|
-
}, files = [];
|
|
1866
|
-
if (files.push({
|
|
1867
|
-
name: ".editorconfig",
|
|
1868
|
-
contents: outdent`
|
|
1869
|
-
root = true
|
|
1870
|
-
|
|
1871
|
-
[*]
|
|
1872
|
-
charset = utf-8
|
|
1873
|
-
indent_style = space
|
|
1874
|
-
indent_size = 2
|
|
1875
|
-
end_of_line = lf
|
|
1876
|
-
insert_final_newline = true
|
|
1877
|
-
trim_trailing_whitespace = true
|
|
1878
|
-
`
|
|
1879
|
-
}), files.push({
|
|
1880
|
-
name: ".gitignore",
|
|
1881
|
-
contents: outdent`
|
|
1882
|
-
*.local
|
|
1883
|
-
*.log
|
|
1884
|
-
*.tgz
|
|
1885
|
-
|
|
1886
|
-
.DS_Store
|
|
1887
|
-
dist
|
|
1888
|
-
etc
|
|
1889
|
-
node_modules
|
|
1890
|
-
`
|
|
1891
|
-
}), features.prettier && files.push({
|
|
1892
|
-
name: ".prettierignore",
|
|
1893
|
-
contents: outdent`
|
|
1894
|
-
dist
|
|
1895
|
-
pnpm-lock.yaml
|
|
1896
|
-
`
|
|
1897
|
-
}), repo && (pkgJson.repository = {
|
|
1898
|
-
type: "git",
|
|
1899
|
-
url: `git+ssh://git@${repo.source}/${repo.owner}/${repo.name}.git`
|
|
1900
|
-
}, pkgJson.bugs = {
|
|
1901
|
-
url: `https://${repo.source}/${repo.owner}/${repo.name}/issues`
|
|
1902
|
-
}, pkgJson.homepage = `https://${repo.source}/${repo.owner}/${repo.name}#readme`), features.typescript) {
|
|
1903
|
-
pkgJson.types = "./dist/index.d.ts", pkgJson.scripts = {
|
|
1904
|
-
...pkgJson.scripts,
|
|
1905
|
-
"ts:check": "tsc --noEmit"
|
|
1906
|
-
};
|
|
1907
|
-
const devDependencies = pkgJson.devDependencies;
|
|
1908
|
-
isRecord(devDependencies) && (devDependencies.typescript = "^5.4");
|
|
1909
|
-
}
|
|
1910
|
-
if (features.eslint) {
|
|
1911
|
-
const eslintConfig = {
|
|
1912
|
-
root: !0,
|
|
1913
|
-
env: {
|
|
1914
|
-
browser: !0,
|
|
1915
|
-
es6: !0,
|
|
1916
|
-
node: !0
|
|
1917
|
-
},
|
|
1918
|
-
extends: [
|
|
1919
|
-
"eslint:recommended",
|
|
1920
|
-
features.prettier ? "plugin:prettier/recommended" : void 0
|
|
1921
|
-
].filter(Boolean),
|
|
1922
|
-
parserOptions: {
|
|
1923
|
-
ecmaVersion: 2020,
|
|
1924
|
-
sourceType: "module"
|
|
1925
|
-
},
|
|
1926
|
-
plugins: [
|
|
1927
|
-
"import",
|
|
1928
|
-
"simple-import-sort",
|
|
1929
|
-
features.prettier ? "prettier" : void 0
|
|
1930
|
-
].filter(Boolean),
|
|
1931
|
-
rules: {
|
|
1932
|
-
"no-console": "error",
|
|
1933
|
-
"no-shadow": "error",
|
|
1934
|
-
"no-warning-comments": ["warn", { location: "start", terms: ["todo", "fixme"] }],
|
|
1935
|
-
"quote-props": ["warn", "consistent-as-needed"],
|
|
1936
|
-
"simple-import-sort/exports": "warn",
|
|
1937
|
-
"simple-import-sort/imports": "warn",
|
|
1938
|
-
strict: ["warn", "global"]
|
|
1939
|
-
}
|
|
1940
|
-
};
|
|
1941
|
-
if (files.push({
|
|
1942
|
-
name: ".eslintignore",
|
|
1943
|
-
contents: outdent`
|
|
1944
|
-
dist
|
|
1945
|
-
`
|
|
1946
|
-
}), pkgJson.scripts = {
|
|
1947
|
-
...pkgJson.scripts,
|
|
1948
|
-
lint: features.typescript ? "eslint . --ext .cjs,.js,.ts,.tsx" : "eslint . --ext .cjs,.js"
|
|
1949
|
-
}, pkgJson.devDependencies = {
|
|
1950
|
-
...pkgJson.devDependencies,
|
|
1951
|
-
eslint: "^8",
|
|
1952
|
-
"eslint-config-prettier": features.prettier ? "^9" : void 0,
|
|
1953
|
-
"eslint-plugin-import": "^2",
|
|
1954
|
-
"eslint-plugin-prettier": features.prettier ? "^5" : void 0,
|
|
1955
|
-
"eslint-plugin-simple-import-sort": "^12"
|
|
1956
|
-
}, features.typescript) {
|
|
1957
|
-
pkgJson.devDependencies = {
|
|
1958
|
-
...pkgJson.devDependencies,
|
|
1959
|
-
"@typescript-eslint/eslint-plugin": "^7",
|
|
1960
|
-
"@typescript-eslint/parser": "^7"
|
|
1961
|
-
};
|
|
1962
|
-
const eslintConfigOverride = {
|
|
1963
|
-
files: ["**/*.ts", "**/*.tsx"],
|
|
1964
|
-
parser: "@typescript-eslint/parser",
|
|
1965
|
-
parserOptions: {
|
|
1966
|
-
project: ["./tsconfig.json"]
|
|
1967
|
-
},
|
|
1968
|
-
extends: [
|
|
1969
|
-
"eslint:recommended",
|
|
1970
|
-
features.prettier ? "plugin:prettier/recommended" : void 0,
|
|
1971
|
-
"plugin:@typescript-eslint/eslint-recommended",
|
|
1972
|
-
"plugin:@typescript-eslint/recommended"
|
|
1973
|
-
].filter(Boolean),
|
|
1974
|
-
plugins: [
|
|
1975
|
-
"import",
|
|
1976
|
-
"@typescript-eslint",
|
|
1977
|
-
"simple-import-sort",
|
|
1978
|
-
features.prettier ? "prettier" : void 0
|
|
1979
|
-
].filter(Boolean),
|
|
1980
|
-
rules: {
|
|
1981
|
-
"@typescript-eslint/explicit-module-boundary-types": "error",
|
|
1982
|
-
"@typescript-eslint/interface-name-prefix": "off",
|
|
1983
|
-
"@typescript-eslint/member-delimiter-style": "off",
|
|
1984
|
-
"@typescript-eslint/no-empty-interface": "off"
|
|
1985
|
-
}
|
|
1986
|
-
};
|
|
1987
|
-
eslintConfig.overrides = [eslintConfigOverride];
|
|
1988
|
-
}
|
|
1989
|
-
files.push({
|
|
1990
|
-
name: ".eslintrc.cjs",
|
|
1991
|
-
contents: await prettierFormat(
|
|
1992
|
-
resolve(packagePath, ".eslintrc.cjs"),
|
|
1993
|
-
outdent`
|
|
1994
|
-
'use strict'
|
|
1995
|
-
|
|
1996
|
-
/** @type import('eslint').Linter.Config */
|
|
1997
|
-
module.exports = ${JSON.stringify(eslintConfig, null, 2)}
|
|
1998
|
-
`,
|
|
1999
|
-
config
|
|
2000
|
-
)
|
|
2001
|
-
});
|
|
2002
|
-
}
|
|
2003
|
-
features.typescript && (files.push({
|
|
2004
|
-
name: "tsconfig.settings.json",
|
|
2005
|
-
contents: await prettierFormat(
|
|
2006
|
-
resolve(packagePath, "tsconfig.settings.json"),
|
|
2007
|
-
outdent`
|
|
2008
|
-
{
|
|
2009
|
-
"extends": "@sanity/pkg-utils/tsconfig/strictest.json",
|
|
2010
|
-
"compilerOptions": {
|
|
2011
|
-
"rootDir": ".",
|
|
2012
|
-
"outDir": "./dist"
|
|
2013
|
-
}
|
|
2014
|
-
}
|
|
2015
|
-
`,
|
|
2016
|
-
config
|
|
2017
|
-
)
|
|
2018
|
-
}), files.push({
|
|
2019
|
-
name: "tsconfig.dist.json",
|
|
2020
|
-
contents: await prettierFormat(
|
|
2021
|
-
resolve(packagePath, "tsconfig.dist.json"),
|
|
2022
|
-
outdent`
|
|
2023
|
-
{
|
|
2024
|
-
"extends": "./tsconfig.settings",
|
|
2025
|
-
"include": ["./src"],
|
|
2026
|
-
"exclude": ["./src/**/*.test.ts"]
|
|
2027
|
-
}
|
|
2028
|
-
`,
|
|
2029
|
-
config
|
|
2030
|
-
)
|
|
2031
|
-
}), files.push({
|
|
2032
|
-
name: "tsconfig.json",
|
|
2033
|
-
contents: await prettierFormat(
|
|
2034
|
-
resolve(packagePath, "tsconfig.json"),
|
|
2035
|
-
outdent`
|
|
2036
|
-
{
|
|
2037
|
-
"extends": "./tsconfig.settings",
|
|
2038
|
-
"include": ["./**/*.cjs", "./**/*.ts", "./**/*.tsx"],
|
|
2039
|
-
"exclude": ["./node_modules"]
|
|
2040
|
-
}
|
|
2041
|
-
`,
|
|
2042
|
-
config
|
|
2043
|
-
)
|
|
2044
|
-
})), features.typescript ? (files.push({
|
|
2045
|
-
name: "package.config.ts",
|
|
2046
|
-
contents: await prettierFormat(
|
|
2047
|
-
resolve(packagePath, "package.config.ts"),
|
|
2048
|
-
outdent`
|
|
2049
|
-
import {defineConfig} from '@sanity/pkg-utils'
|
|
2050
|
-
|
|
2051
|
-
// https://github.com/sanity-io/pkg-utils#configuration
|
|
2052
|
-
export default defineConfig({
|
|
2053
|
-
// the path to the tsconfig file for distributed builds
|
|
2054
|
-
tsconfig: 'tsconfig.dist.json',
|
|
2055
|
-
})
|
|
2056
|
-
`,
|
|
2057
|
-
config
|
|
2058
|
-
)
|
|
2059
|
-
}), files.push({
|
|
2060
|
-
name: "src/index.ts",
|
|
2061
|
-
contents: await prettierFormat(
|
|
2062
|
-
resolve(packagePath, "src/index.ts"),
|
|
2063
|
-
outdent`
|
|
2064
|
-
/** @public */
|
|
2065
|
-
export function main(): void {
|
|
2066
|
-
//
|
|
2067
|
-
}
|
|
2068
|
-
`,
|
|
2069
|
-
config
|
|
2070
|
-
)
|
|
2071
|
-
})) : (files.push({
|
|
2072
|
-
name: "package.config.js",
|
|
2073
|
-
contents: await prettierFormat(
|
|
2074
|
-
resolve(packagePath, "package.config.js"),
|
|
2075
|
-
outdent`
|
|
2076
|
-
import {defineConfig} from '@sanity/pkg-utils'
|
|
2077
|
-
|
|
2078
|
-
export default defineConfig({
|
|
2079
|
-
extract: {
|
|
2080
|
-
rules: {
|
|
2081
|
-
// do not require internal members to be prefixed with \`_\`
|
|
2082
|
-
'ae-internal-missing-underscore': 'off',
|
|
2083
|
-
},
|
|
2084
|
-
},
|
|
2085
|
-
})
|
|
2086
|
-
`,
|
|
2087
|
-
config
|
|
2088
|
-
)
|
|
2089
|
-
}), files.push({
|
|
2090
|
-
name: "src/index.js",
|
|
2091
|
-
contents: await prettierFormat(
|
|
2092
|
-
resolve(packagePath, "src/index.js"),
|
|
2093
|
-
outdent`
|
|
2094
|
-
/** @public */
|
|
2095
|
-
export function main() {
|
|
2096
|
-
//
|
|
2097
|
-
}
|
|
2098
|
-
`,
|
|
2099
|
-
config
|
|
2100
|
-
)
|
|
2101
|
-
}));
|
|
2102
|
-
try {
|
|
2103
|
-
pkgJson.dependencies = await resolveLatestDeps(pkgJson.dependencies ?? {});
|
|
2104
|
-
} catch (error) {
|
|
2105
|
-
logger.warn(error instanceof Error ? error.message : error);
|
|
2106
|
-
}
|
|
2107
|
-
try {
|
|
2108
|
-
pkgJson.devDependencies = await resolveLatestDeps(pkgJson.devDependencies ?? {});
|
|
2109
|
-
} catch (error) {
|
|
2110
|
-
logger.warn(error instanceof Error ? error.message : error);
|
|
2111
|
-
}
|
|
2112
|
-
return files.push({
|
|
2113
|
-
name: "package.json",
|
|
2114
|
-
contents: await prettierFormat(
|
|
2115
|
-
resolve(packagePath, "package.json"),
|
|
2116
|
-
JSON.stringify(pkgJson, null, 2),
|
|
2117
|
-
config
|
|
2118
|
-
)
|
|
2119
|
-
}), files;
|
|
2120
|
-
}
|
|
2121
|
-
};
|
|
2122
|
-
};
|
|
2123
|
-
function prettierFormat(filepath, input, prettierOptions) {
|
|
2124
|
-
return format(input, { ...prettierOptions, plugins: [], filepath });
|
|
2125
|
-
}
|
|
2126
|
-
async function resolveLatestDeps(deps) {
|
|
2127
|
-
const depsEntries = Object.entries(deps), latestDeps = {};
|
|
2128
|
-
for (const entry of depsEntries) {
|
|
2129
|
-
const [name, version] = entry;
|
|
2130
|
-
if (version) {
|
|
2131
|
-
const latestVersion = await getLatestVersion(name, version);
|
|
2132
|
-
latestDeps[name] = latestVersion ? `^${latestVersion}` : version;
|
|
2133
|
-
}
|
|
2134
|
-
}
|
|
2135
|
-
return latestDeps;
|
|
2136
|
-
}
|
|
2137
|
-
function getGitUserConfig(cwd) {
|
|
2138
|
-
let user, email;
|
|
2139
|
-
try {
|
|
2140
|
-
user = execSync("git config user.name", { encoding: "utf8", cwd }).trim() || void 0, email = execSync("git config user.email", { encoding: "utf8", cwd }).trim() || void 0;
|
|
2141
|
-
} catch {
|
|
2142
|
-
}
|
|
2143
|
-
return { user, email };
|
|
2144
|
-
}
|
|
2145
|
-
async function init(options) {
|
|
2146
|
-
if (!options.cwd)
|
|
2147
|
-
throw new Error("Missing required option: cwd");
|
|
2148
|
-
if (!options.path)
|
|
2149
|
-
throw new Error("Missing required option: path");
|
|
2150
|
-
const logger = createLogger(), packagePath = resolve(options.cwd, options.path);
|
|
2151
|
-
await ensurePackagePath(packagePath), await createFromTemplate({
|
|
2152
|
-
cwd: options.cwd,
|
|
2153
|
-
logger,
|
|
2154
|
-
template: defaultTemplate,
|
|
2155
|
-
packagePath
|
|
2156
|
-
});
|
|
2157
|
-
}
|
|
2158
|
-
async function ensurePackagePath(packagePath) {
|
|
2159
|
-
if (!fileExists(packagePath)) {
|
|
2160
|
-
await mkdirp(packagePath);
|
|
2161
|
-
return;
|
|
2162
|
-
}
|
|
2163
|
-
if (!(await lstat(packagePath)).isDirectory())
|
|
2164
|
-
throw new Error("the package path is a file, not a directory");
|
|
2165
|
-
if (!await isEmptyDirectory(packagePath))
|
|
2166
|
-
throw new Error("the package directory is not empty");
|
|
2167
|
-
}
|
|
2168
|
-
function resolveWatchTasks(ctx) {
|
|
2169
|
-
const { pkg, target } = ctx, tasks = [], exports = Object.entries(ctx.exports || {}).map(
|
|
2170
|
-
([_path, exp]) => ({ _path, ...exp })
|
|
2171
|
-
), dtsTask2 = {
|
|
2172
|
-
type: "watch:dts",
|
|
2173
|
-
entries: []
|
|
2174
|
-
}, rollupTasks = {};
|
|
2175
|
-
function addRollupTaskEntry(format2, runtime, entry) {
|
|
2176
|
-
const buildId = `${format2}:${runtime}`;
|
|
2177
|
-
rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
|
|
2178
|
-
type: "watch:js",
|
|
2179
|
-
buildId,
|
|
2180
|
-
entries: [entry],
|
|
2181
|
-
runtime,
|
|
2182
|
-
format: format2,
|
|
2183
|
-
target: target[runtime]
|
|
2184
|
-
};
|
|
2185
|
-
}
|
|
2186
|
-
for (const exp of exports) {
|
|
2187
|
-
const importId = path.join(pkg.name, exp._path);
|
|
2188
|
-
exp.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2189
|
-
importId,
|
|
2190
|
-
exportPath: exp._path,
|
|
2191
|
-
sourcePath: exp.source,
|
|
2192
|
-
targetPaths: getTargetPaths(pkg.type, exp)
|
|
2193
|
-
}), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2194
|
-
importId,
|
|
2195
|
-
exportPath: exp._path,
|
|
2196
|
-
sourcePath: exp.browser.source,
|
|
2197
|
-
targetPaths: getTargetPaths(pkg.type, exp.browser)
|
|
2198
|
-
}), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
|
|
2199
|
-
importId,
|
|
2200
|
-
exportPath: exp._path,
|
|
2201
|
-
sourcePath: exp.node.source,
|
|
2202
|
-
targetPaths: getTargetPaths(pkg.type, exp.node)
|
|
2203
|
-
});
|
|
2204
|
-
}
|
|
2205
|
-
for (const exp of exports) {
|
|
2206
|
-
const output = exp.require;
|
|
2207
|
-
output && addRollupTaskEntry("commonjs", ctx.runtime, {
|
|
2208
|
-
path: exp._path,
|
|
2209
|
-
source: exp.source,
|
|
2210
|
-
output
|
|
2211
|
-
});
|
|
2212
|
-
}
|
|
2213
|
-
for (const exp of exports) {
|
|
2214
|
-
const output = exp.browser?.require;
|
|
2215
|
-
output && addRollupTaskEntry("commonjs", "browser", {
|
|
2216
|
-
path: exp._path,
|
|
2217
|
-
source: exp.browser?.source || exp.source,
|
|
2218
|
-
output
|
|
2219
|
-
});
|
|
2220
|
-
}
|
|
2221
|
-
for (const exp of exports) {
|
|
2222
|
-
const output = exp.import;
|
|
2223
|
-
output && addRollupTaskEntry("esm", ctx.runtime, {
|
|
2224
|
-
path: exp._path,
|
|
2225
|
-
source: exp.source,
|
|
2226
|
-
output
|
|
2227
|
-
});
|
|
2228
|
-
}
|
|
2229
|
-
for (const exp of exports) {
|
|
2230
|
-
const output = exp.browser?.import;
|
|
2231
|
-
output && addRollupTaskEntry("esm", "browser", {
|
|
2232
|
-
path: exp._path,
|
|
2233
|
-
source: exp.browser?.source || exp.source,
|
|
2234
|
-
output
|
|
2235
|
-
});
|
|
2236
|
-
}
|
|
2237
|
-
return dtsTask2.entries.length && tasks.push(dtsTask2), tasks.push(...Object.values(rollupTasks)), tasks;
|
|
2238
|
-
}
|
|
2239
|
-
function globFiles(patterns) {
|
|
2240
|
-
return globby(patterns.map((pattern) => pattern.split(path.sep).join(path.posix.sep)));
|
|
2241
|
-
}
|
|
2242
|
-
function watchFiles(patterns) {
|
|
2243
|
-
return new Observable((observer) => {
|
|
2244
|
-
const watcher = chokidar.watch(patterns, {
|
|
2245
|
-
ignoreInitial: !0
|
|
2246
|
-
});
|
|
2247
|
-
function handleFileEvent(type, file) {
|
|
2248
|
-
type === "error" || file instanceof Error ? observer.error(file) : observer.next({ type, file });
|
|
2249
|
-
}
|
|
2250
|
-
return watcher.on("all", handleFileEvent), () => {
|
|
2251
|
-
watcher.off("all", handleFileEvent), watcher.close();
|
|
2252
|
-
};
|
|
2253
|
-
});
|
|
2254
|
-
}
|
|
2255
|
-
async function watchConfigFiles(options) {
|
|
2256
|
-
const { cwd, logger } = options, initialFiles = await globFiles([
|
|
2257
|
-
path.resolve(cwd, "package.json"),
|
|
2258
|
-
path.resolve(cwd, "package.config.cjs"),
|
|
2259
|
-
path.resolve(cwd, "package.config.js"),
|
|
2260
|
-
path.resolve(cwd, "package.config.ts")
|
|
2261
|
-
]);
|
|
2262
|
-
return watchFiles([
|
|
2263
|
-
path.resolve(cwd, "package.json"),
|
|
2264
|
-
path.resolve(cwd, "package.config.cjs"),
|
|
2265
|
-
path.resolve(cwd, "package.config.js"),
|
|
2266
|
-
path.resolve(cwd, "package.config.ts")
|
|
2267
|
-
]).pipe(
|
|
2268
|
-
scan((files, fileEvent) => fileEvent.type === "add" ? files.concat(fileEvent.file) : fileEvent.type === "unlink" ? files.filter((f) => f !== fileEvent.file) : fileEvent.type === "change" ? (logger.log(
|
|
2269
|
-
"--------------------------------------------------------------------------------"
|
|
2270
|
-
), logger.info(path.relative(cwd, fileEvent.file), "changed"), logger.log(""), files.slice(0)) : files, initialFiles),
|
|
2271
|
-
startWith(initialFiles),
|
|
2272
|
-
distinctUntilChanged()
|
|
2273
|
-
);
|
|
2274
|
-
}
|
|
2275
|
-
async function watch(options) {
|
|
2276
|
-
const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger();
|
|
2277
|
-
(await watchConfigFiles({ cwd, logger })).pipe(
|
|
2278
|
-
switchMap(async (configFiles) => {
|
|
2279
|
-
if (!configFiles.map((f) => path.relative(cwd, f)).find((f) => f === "package.json"))
|
|
2280
|
-
throw new Error("missing package.json");
|
|
2281
|
-
const config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json";
|
|
2282
|
-
return resolveBuildContext({ config: config2, cwd, logger, pkg, strict, tsconfig });
|
|
2283
|
-
})
|
|
2284
|
-
).subscribe(async (ctx) => {
|
|
2285
|
-
const watchTasks = resolveWatchTasks(ctx);
|
|
2286
|
-
for (const task of watchTasks) {
|
|
2287
|
-
const handler = watchTaskHandlers[task.type];
|
|
2288
|
-
handler.exec(ctx, task).subscribe({
|
|
2289
|
-
error: (err) => {
|
|
2290
|
-
ctx.logger.error(err), ctx.logger.log(), process.exit(1);
|
|
2291
|
-
},
|
|
2292
|
-
next: (result) => {
|
|
2293
|
-
handler.complete(ctx, task, result);
|
|
2294
|
-
},
|
|
2295
|
-
complete: () => {
|
|
2296
|
-
ctx.logger.success(handler.name(ctx, task)), ctx.logger.log();
|
|
2297
|
-
}
|
|
2298
|
-
});
|
|
2299
|
-
}
|
|
2300
|
-
});
|
|
2301
|
-
}
|
|
2302
842
|
export {
|
|
2303
|
-
|
|
2304
|
-
build,
|
|
2305
|
-
check,
|
|
2306
|
-
createLogger,
|
|
2307
|
-
defineConfig,
|
|
2308
|
-
defineTemplateOption,
|
|
843
|
+
buildTaskHandlers,
|
|
2309
844
|
getExtractMessagesConfig,
|
|
2310
|
-
|
|
2311
|
-
loadConfig,
|
|
2312
|
-
loadPkg,
|
|
2313
|
-
loadPkgWithReporting,
|
|
2314
|
-
parseExports,
|
|
2315
|
-
parseStrictOptions,
|
|
2316
|
-
pkgExtMap,
|
|
2317
|
-
strictOptions,
|
|
2318
|
-
toggle,
|
|
2319
|
-
watch
|
|
845
|
+
watchTaskHandlers
|
|
2320
846
|
};
|
|
2321
847
|
//# sourceMappingURL=index.js.map
|