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