@sanity/pkg-utils 7.11.9 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2466 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __copyProps = (to, from, except, desc) => {
8
- if (from && typeof from == "object" || typeof from == "function")
9
- for (let key of __getOwnPropNames(from))
10
- !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- return to;
12
- };
13
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
14
- // If the importer is in node compatibility mode or this is not an ESM
15
- // file that has been converted to a CommonJS file using a Babel-
16
- // compatible transform (i.e. "__esModule" has not been set), then set
17
- // "default" to the CommonJS "module.exports" for node compatibility.
18
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
19
- mod
20
- ));
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$1 = 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"), rollupPlugin = require("@vanilla-extract/rollup-plugin"), esbuild = require("rollup-plugin-esbuild"), lightningcss = require("lightningcss"), 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
- function _interopDefaultCompat(e) {
23
- return e && typeof e == "object" && "default" in e ? e : { default: e };
24
- }
25
- function _interopNamespaceCompat(e) {
26
- if (e && typeof e == "object" && "default" in e) return e;
27
- var n = /* @__PURE__ */ Object.create(null);
28
- return e && Object.keys(e).forEach(function(k) {
29
- if (k !== "default") {
30
- var d = Object.getOwnPropertyDescriptor(e, k);
31
- Object.defineProperty(n, k, d.get ? d : {
32
- enumerable: !0,
33
- get: function() {
34
- return e[k];
35
- }
36
- });
37
- }
38
- }), n.default = e, Object.freeze(n);
39
- }
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), 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$2 = 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$2(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(quiet = !1) {
215
- return {
216
- log: (...args) => {
217
- quiet || console.log(...args);
218
- },
219
- info: (...args) => {
220
- quiet || 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
- quiet || 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
- noCheckTypes: toggle.default("warn")
459
- }).strict(), validationSchema = zod.z.object({
460
- strictOptions: strictOptions.default({})
461
- });
462
- function parseStrictOptions(input) {
463
- return validationSchema.parse({ strictOptions: input }, { errorMap: zodValidationError.errorMap }).strictOptions;
464
- }
465
- async function resolveBuildContext(options) {
466
- const {
467
- config: config2,
468
- cwd,
469
- emitDeclarationOnly = !1,
470
- logger,
471
- pkg,
472
- strict,
473
- tsconfig: tsconfigPath
474
- } = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config2?.strictOptions ?? {});
475
- if (strictOptions2.noCheckTypes !== "off" && tsconfig?.options && config2?.dts !== "rolldown" && tsconfig.options.noCheck !== !1 && !tsconfig.options.noCheck) {
476
- if (strictOptions2.noCheckTypes === "error")
477
- throw new Error(
478
- "`noCheck` is not set to `true` in the tsconfig.json file used by `package.config.ts`. This makes generating dts files slower than it needs to be, as it will perform type checking on the dts files while at it."
479
- );
480
- logger.warn(
481
- "`noCheck` is not set to `true` in the tsconfig.json file used by `package.config.ts`. This makes generating dts files slower than it needs to be, as it will perform type checking on the dts files while at it."
482
- );
483
- }
484
- let browserslist2 = pkg.browserslist;
485
- if (!browserslist2) {
486
- if (strict && strictOptions2.noImplicitBrowsersList !== "off") {
487
- if (strictOptions2.noImplicitBrowsersList === "error")
488
- throw new Error(
489
- '\n- package.json: "browserslist" is missing, set it to `"browserslist": "extends @sanity/browserslist-config"`'
490
- );
491
- logger.warn(
492
- 'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `"browserslist": "extends @sanity/browserslist-config"` to silence this warning.'
493
- );
494
- }
495
- browserslist2 = DEFAULT_BROWSERSLIST_QUERY;
496
- }
497
- const targetVersions = browserslistToEsbuild(browserslist2);
498
- if (strict && strictOptions2.noImplicitSideEffects !== "off" && typeof pkg.sideEffects > "u") {
499
- 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`";
500
- if (strictOptions2.noImplicitSideEffects === "error")
501
- throw new Error(msg);
502
- logger.warn(msg);
503
- }
504
- const nodeTarget = resolveNodeTarget(targetVersions), webTarget = resolveBrowserTarget(targetVersions);
505
- if (!nodeTarget)
506
- throw new Error("no matching `node` target");
507
- if (!webTarget)
508
- throw new Error("no matching `web` target");
509
- const target = {
510
- "*": webTarget.concat(nodeTarget),
511
- browser: webTarget,
512
- node: nodeTarget
513
- }, parsedExports = parseExports({
514
- cwd,
515
- pkg,
516
- strict,
517
- strictOptions: strictOptions2,
518
- logger
519
- }).reduce(
520
- (acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
521
- {}
522
- ), exports2 = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
523
- ...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
524
- ...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
525
- ], 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(
526
- // Do not bundle anything that is marked as external
527
- (_) => !externalWithTypes.has(_)
528
- ), bundledPackages = config2 && Array.isArray(config2.extract?.bundledPackages) ? [...bundledDependencies, ...config2.extract.bundledPackages] : resolveConfigProperty(config2?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports2).flatMap((exportEntry) => [
529
- exportEntry.import,
530
- exportEntry.require,
531
- exportEntry.browser?.import,
532
- exportEntry.browser?.require,
533
- exportEntry.node?.source && exportEntry.node.import,
534
- exportEntry.node?.source && exportEntry.node.require
535
- ].filter(Boolean)).map((p) => path__default.default.resolve(cwd, p)), commonDistPath = findCommonDirPath(outputPaths);
536
- if (commonDistPath === cwd)
537
- throw new Error(
538
- "all output files must share a common parent directory which is not the root package directory"
539
- );
540
- if (commonDistPath && !pathContains(cwd, commonDistPath))
541
- throw new Error("all output files must be located within the package");
542
- const configDistPath = config2?.dist ? path__default.default.resolve(cwd, config2.dist) : void 0;
543
- if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
544
- 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");
545
- const distPath = configDistPath || commonDistPath;
546
- if (!distPath)
547
- throw new Error("could not detect `dist` path");
548
- return {
549
- config: config2,
550
- cwd,
551
- distPath,
552
- emitDeclarationOnly,
553
- exports: exports2,
554
- external,
555
- bundledPackages,
556
- files: [],
557
- logger,
558
- pkg,
559
- runtime: config2?.runtime ?? "*",
560
- strict,
561
- target,
562
- ts: {
563
- config: tsconfig,
564
- configPath: tsconfigPath
565
- },
566
- dts: config2?.dts === "rolldown" ? "rolldown" : "api-extractor"
567
- };
568
- }
569
- function transformPackageName(packageName) {
570
- if (packageName.startsWith("@types/"))
571
- return packageName;
572
- if (packageName.startsWith("@")) {
573
- const [scope, name] = packageName.split("/");
574
- return `@types/${scope?.slice(1)}__${name}`;
575
- } else
576
- return `@types/${packageName}`;
577
- }
578
- function resolveBuildTasks(ctx) {
579
- const { config: config2, pkg, target } = ctx, bundles = config2?.bundles || [], tasks = [], exports2 = Object.entries(ctx.exports || {}).map(
580
- ([_path, exp]) => ({ _path, ...exp })
581
- ), dtsTask2 = {
582
- type: "build:dts",
583
- entries: []
584
- }, rolldownDtsTask2 = {}, rollupTasks = {};
585
- function addRollupTaskEntry(format, runtime, entry) {
586
- const buildId = `${format}:${runtime}`;
587
- ctx.dts === "rolldown" && (rolldownDtsTask2[buildId] ? rolldownDtsTask2[buildId].entries.push(entry) : rolldownDtsTask2[buildId] = {
588
- type: "rolldown:dts",
589
- buildId,
590
- entries: [entry],
591
- runtime,
592
- format,
593
- target: target[runtime]
594
- }), ctx.emitDeclarationOnly || (rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
595
- type: "build:js",
596
- buildId,
597
- entries: [entry],
598
- runtime,
599
- format,
600
- target: target[runtime]
601
- });
602
- }
603
- if (ctx.dts === "api-extractor") {
604
- for (const exp of exports2) {
605
- const importId = path__default.default.join(pkg.name, exp._path);
606
- exp.source?.endsWith(".ts") && dtsTask2.entries.push({
607
- importId,
608
- exportPath: exp._path,
609
- sourcePath: exp.source,
610
- targetPaths: getTargetPaths(pkg.type, exp)
611
- }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
612
- importId,
613
- exportPath: exp._path,
614
- sourcePath: exp.browser.source,
615
- targetPaths: getTargetPaths(pkg.type, exp.browser)
616
- }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
617
- importId,
618
- exportPath: exp._path,
619
- sourcePath: exp.node.source,
620
- targetPaths: getTargetPaths(pkg.type, exp.node)
621
- });
622
- }
623
- for (const bundle of bundles)
624
- if (bundle.source?.endsWith(".ts")) {
625
- const exportPath = (bundle.import || bundle.require).replace(/\.[mc]?js$/, ""), importId = path__default.default.join(pkg.name, exportPath);
626
- dtsTask2.entries.push({
627
- importId,
628
- exportPath,
629
- sourcePath: bundle.source,
630
- targetPaths: getTargetPaths(pkg.type, bundle)
631
- });
632
- }
633
- dtsTask2.entries.length && tasks.push(dtsTask2);
634
- }
635
- for (const exp of exports2) {
636
- const output = exp.require;
637
- output && addRollupTaskEntry("commonjs", ctx.runtime, {
638
- path: exp._path,
639
- source: exp.source,
640
- output
641
- });
642
- }
643
- for (const exp of exports2) {
644
- const output = exp.import;
645
- output && addRollupTaskEntry("esm", ctx.runtime, {
646
- path: exp._path,
647
- source: exp.source,
648
- output
649
- });
650
- }
651
- for (const exp of exports2) {
652
- const output = exp.browser?.require;
653
- output && addRollupTaskEntry("commonjs", "browser", {
654
- path: exp._path,
655
- source: exp.browser?.source || exp.source,
656
- output
657
- });
658
- }
659
- for (const exp of exports2) {
660
- const output = exp.browser?.import;
661
- output && addRollupTaskEntry("esm", "browser", {
662
- path: exp._path,
663
- source: exp.browser?.source || exp.source,
664
- output
665
- });
666
- }
667
- for (const bundle of bundles) {
668
- const idx = bundles.indexOf(bundle);
669
- bundle.require && addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
670
- path: `__$$bundle_cjs_${idx}$$__`,
671
- source: bundle.source,
672
- output: bundle.require
673
- }), bundle.import && addRollupTaskEntry("esm", bundle.runtime || ctx.runtime, {
674
- path: `__$$bundle_esm_${idx}$$__`,
675
- source: bundle.source,
676
- output: bundle.import
677
- });
678
- }
679
- return tasks.push(...Object.values(rolldownDtsTask2)), tasks.push(...Object.values(rollupTasks)), tasks;
680
- }
681
- function createSpinner(msg, quiet = !1) {
682
- const startTime = Date.now();
683
- return quiet || console.log(msg), {
684
- complete: () => {
685
- quiet || console.log(`${chalk__default.default.green("[success]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
686
- },
687
- error: () => {
688
- console.log(`${chalk__default.default.red("[error]")} ${chalk__default.default.gray(`${Date.now() - startTime}ms`)}`);
689
- }
690
- };
691
- }
692
- function printExtractMessages(ctx, messages) {
693
- const { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === "warning");
694
- warnings.length && logger.log();
695
- for (const msg of warnings) {
696
- const sourceFilePath = msg.sourceFilePath && path__default.default.relative(cwd, msg.sourceFilePath);
697
- msg.messageId !== "TS6307" && logger.log(
698
- [
699
- `${chalk__default.default.cyan(sourceFilePath || "?")}`,
700
- `:${chalk__default.default.yellow(msg.sourceFileLine)}:${chalk__default.default.yellow(msg.sourceFileColumn)}`,
701
- ` - ${chalk__default.default.yellow("warning")} ${chalk__default.default.gray(msg.messageId)}
702
- `,
703
- msg.text,
704
- `
705
- `
706
- ].join("")
707
- );
708
- }
709
- const errors = messages.filter((msg) => msg.logLevel === "error");
710
- !warnings.length && errors.length && logger.log("");
711
- for (const msg of errors) {
712
- const sourceFilePath = msg.sourceFilePath && path__default.default.relative(cwd, msg.sourceFilePath);
713
- logger.log(
714
- [
715
- `${chalk__default.default.cyan(sourceFilePath || "?")}`,
716
- `:${chalk__default.default.yellow(msg.sourceFileLine)}:${chalk__default.default.yellow(msg.sourceFileColumn)}`,
717
- ` - ${chalk__default.default.red("error")} ${chalk__default.default.gray(msg.messageId)}
718
- `,
719
- msg.text,
720
- `
721
- `
722
- ].join("")
723
- );
724
- }
725
- errors.length && process.exit(1);
726
- }
727
- var printExtractMessages$1 = /* @__PURE__ */ Object.freeze({
728
- __proto__: null,
729
- printExtractMessages
730
- });
731
- function printDiagnostic(options) {
732
- const { cwd, logger, diagnostic } = options;
733
- if (diagnostic.file && diagnostic.start) {
734
- const { line, character } = ts__default.default.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), message = ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
735
- `), file = path__default.default.relative(cwd, diagnostic.file.fileName), output = [
736
- `${chalk__default.default.yellow(file)}:${chalk__default.default.blue(line + 1)}:${chalk__default.default.blue(character + 1)} - `,
737
- `${chalk__default.default.gray(`TS${diagnostic.code}:`)} ${message}`
738
- ].join("");
739
- diagnostic.category === ts__default.default.DiagnosticCategory.Error && logger.error(output), diagnostic.category === ts__default.default.DiagnosticCategory.Warning && logger.warn(output), diagnostic.category === ts__default.default.DiagnosticCategory.Message && logger.log(output), diagnostic.category === ts__default.default.DiagnosticCategory.Suggestion && logger.log(output);
740
- } else
741
- logger.log(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
742
- `));
743
- }
744
- async function buildTypes(options) {
745
- const { cwd, logger, outDir, tsconfig, strict = !1 } = options, compilerOptions = {
746
- ...tsconfig.options,
747
- declaration: !0,
748
- declarationDir: outDir,
749
- emitDeclarationOnly: !0,
750
- noEmit: !1,
751
- noEmitOnError: strict ? !0 : tsconfig.options.noEmitOnError ?? !0,
752
- noCheck: tsconfig.options.noCheck ?? tsconfig.options.isolatedDeclarations,
753
- outDir
754
- }, program = ts__default.default.createProgram(tsconfig.fileNames, compilerOptions), emitResult = program.emit(), allDiagnostics = ts__default.default.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
755
- for (const diagnostic of allDiagnostics)
756
- printDiagnostic({ cwd, logger, diagnostic });
757
- if (emitResult.emitSkipped && allDiagnostics.filter((diag) => diag.category === ts__default.default.DiagnosticCategory.Error).length)
758
- throw new Error("failed to compile TypeScript definitions");
759
- }
760
- class DtsError extends Error {
761
- messages;
762
- constructor(message, messages) {
763
- super(message), this.messages = messages;
764
- }
765
- }
766
- function createApiExtractorConfig(options) {
767
- const {
768
- bundledPackages,
769
- distPath,
770
- exportPath,
771
- filePath,
772
- messages,
773
- projectFolder,
774
- mainEntryPointFilePath,
775
- tsconfig,
776
- tsconfigPath,
777
- dtsRollupEnabled
778
- } = options;
779
- return {
780
- apiReport: {
781
- enabled: !1,
782
- reportFileName: "<unscopedPackageName>.api.md"
783
- },
784
- bundledPackages,
785
- // If `paths` are used for self-referencing imports (e.g. the module is named `sanity`, and the `sanity/structure` export is also importing from `sanity/router`),
786
- compiler: tsconfig.options.paths ? {
787
- overrideTsconfig: {
788
- extends: tsconfigPath,
789
- compilerOptions: {
790
- // An empty object replaces whatever is in the original tsconfig file
791
- paths: {}
792
- }
793
- }
794
- } : { tsconfigFilePath: tsconfigPath },
795
- docModel: {
796
- enabled: !1,
797
- apiJsonFilePath: path__default.default.resolve(distPath, `${exportPath}.api.json`)
798
- },
799
- dtsRollup: {
800
- enabled: dtsRollupEnabled,
801
- untrimmedFilePath: path__default.default.resolve(distPath, filePath)
802
- // betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
803
- // publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
804
- },
805
- tsdocMetadata: {
806
- enabled: !1
807
- },
808
- messages,
809
- mainEntryPointFilePath,
810
- projectFolder
811
- };
812
- }
813
- var createApiExtractorConfig$1 = /* @__PURE__ */ Object.freeze({
814
- __proto__: null,
815
- createApiExtractorConfig
816
- });
817
- 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);
818
- async function createTSDocConfig(opts) {
819
- const { customTags } = opts;
820
- if (customTags.length === 0)
821
- return;
822
- const tsDocBaseBuf = await fs.readFile(
823
- require$1.resolve("@microsoft/api-extractor/extends/tsdoc-base.json")
824
- ), tsDocBaseConfig = jsoncParser.parse(tsDocBaseBuf.toString()), tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(
825
- customTags.map((t) => ({
826
- tagName: `@${t.name}`,
827
- syntaxKind: t.syntaxKind,
828
- allowMultiple: t.allowMultiple
829
- }))
830
- ), supportForTags = { ...tsDocBaseConfig.supportForTags };
831
- for (const customTag of customTags)
832
- supportForTags[`@${customTag.name}`] = !0;
833
- return tsdocConfig.TSDocConfigFile.loadFromObject({
834
- ...tsDocBaseConfig,
835
- noStandardTags: !1,
836
- tagDefinitions,
837
- supportForTags
838
- });
839
- }
840
- var createTSDocConfig$1 = /* @__PURE__ */ Object.freeze({
841
- __proto__: null,
842
- createTSDocConfig
843
- });
844
- async function extractModuleBlocksFromTypes({
845
- tsOutDir,
846
- extractResult
847
- }) {
848
- const program = extractResult.compilerState.program, moduleBlocks = [], sourceFiles = [...program.getSourceFiles()].filter((sourceFile) => sourceFile.fileName.includes(tsOutDir));
849
- for (const sourceFile of sourceFiles)
850
- sourceFile.text.includes("declare module") && moduleBlocks.push(...extractModuleBlocks(sourceFile.text));
851
- return moduleBlocks;
852
- }
853
- function extractModuleBlocks(fileContent) {
854
- return recast.parse(fileContent, {
855
- parser: typeScriptParser__default.default
856
- }).program.body.filter((node2) => node2.type === "TSModuleDeclaration").map((node2) => recast.print(node2).code);
857
- }
858
- const LOG_LEVELS = {
859
- error: "error",
860
- info: "info",
861
- off: "none",
862
- warn: "warning"
863
- };
864
- function getExtractMessagesConfig(options) {
865
- const { rules, disabled = !1 } = options;
866
- function ruleToLogLevel(key, defaultLevel) {
867
- const r = rules?.[key];
868
- return r ? LOG_LEVELS[r] : defaultLevel || "warning";
869
- }
870
- return {
871
- compilerMessageReporting: {
872
- default: {
873
- logLevel: disabled ? "none" : "warning"
874
- }
875
- },
876
- extractorMessageReporting: disabled ? {
877
- default: {
878
- logLevel: "none",
879
- addToApiReportFile: !1
880
- }
881
- } : {
882
- default: {
883
- logLevel: "warning",
884
- addToApiReportFile: !1
885
- },
886
- "ae-forgotten-export": {
887
- /**
888
- * This is hardcoded to `none` as it's no longer needed since TypeScript 5.5 https://github.com/microsoft/TypeScript/issues/42873
889
- * It's hardcoded to `none` since supported by API Extractor when using `module: 'Preserve'` doesn't support it well since `@microsoft/api-extractor` v7.49.0, which upgraded from TS 5.4 to 5.7 internally
890
- */
891
- logLevel: "none",
892
- addToApiReportFile: !1
893
- },
894
- "ae-incompatible-release-tags": {
895
- logLevel: ruleToLogLevel("ae-incompatible-release-tags", "error"),
896
- addToApiReportFile: !1
897
- },
898
- "ae-internal-missing-underscore": {
899
- logLevel: ruleToLogLevel("ae-internal-missing-underscore"),
900
- addToApiReportFile: !1
901
- },
902
- "ae-missing-release-tag": {
903
- logLevel: ruleToLogLevel("ae-missing-release-tag", "error"),
904
- addToApiReportFile: !1
905
- },
906
- "ae-wrong-input-file-type": {
907
- logLevel: "none",
908
- addToApiReportFile: !1
909
- }
910
- },
911
- tsdocMessageReporting: disabled ? {
912
- default: {
913
- logLevel: "none",
914
- addToApiReportFile: !1
915
- }
916
- } : {
917
- default: {
918
- logLevel: "warning",
919
- addToApiReportFile: !1
920
- },
921
- "tsdoc-link-tag-unescaped-text": {
922
- logLevel: ruleToLogLevel(
923
- "tsdoc-link-tag-unescaped-text",
924
- "warning"
925
- ),
926
- addToApiReportFile: !1
927
- },
928
- "tsdoc-undefined-tag": {
929
- logLevel: ruleToLogLevel("tsdoc-undefined-tag", "error"),
930
- addToApiReportFile: !1
931
- },
932
- "tsdoc-unsupported-tag": {
933
- logLevel: ruleToLogLevel("tsdoc-unsupported-tag", "none"),
934
- addToApiReportFile: !1
935
- }
936
- }
937
- };
938
- }
939
- var getExtractMessagesConfig$1 = /* @__PURE__ */ Object.freeze({
940
- __proto__: null,
941
- getExtractMessagesConfig
942
- });
943
- async function extractTypes(options) {
944
- const {
945
- bundledPackages,
946
- customTags,
947
- distPath,
948
- exportPath,
949
- files,
950
- filePaths,
951
- projectPath,
952
- rules,
953
- sourceTypesPath,
954
- tmpPath,
955
- tsconfig,
956
- tsconfigPath,
957
- extractorDisabled
958
- } = options, tsdocConfigFile = await createTSDocConfig({
959
- customTags: customTags || []
960
- }), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = apiExtractor.ExtractorConfig.prepare({
961
- configObject: createApiExtractorConfig({
962
- bundledPackages,
963
- distPath,
964
- exportPath,
965
- filePath,
966
- messages: getExtractMessagesConfig({ rules, disabled: extractorDisabled }),
967
- projectFolder: projectPath,
968
- mainEntryPointFilePath: sourceTypesPath,
969
- tsconfig,
970
- tsconfigPath,
971
- dtsRollupEnabled: !0
972
- }),
973
- configObjectFullPath: void 0,
974
- tsdocConfigFile,
975
- packageJsonFullPath: path__default.default.resolve(projectPath, "package.json")
976
- }), messages = [], extractorResult = apiExtractor.Extractor.invoke(extractorConfig, {
977
- // Equivalent to the "--local" command-line parameter
978
- localBuild: !0,
979
- // Equivalent to the "--verbose" command-line parameter
980
- showVerboseMessages: !0,
981
- // handle messages
982
- messageCallback(message) {
983
- messages.push(message), message.handled = !0;
984
- }
985
- }), typesPath = path__default.default.resolve(distPath, filePath), typesBuf = await fs__default.default.readFile(typesPath), prettierConfig = await prettier__namespace.resolveConfig(typesPath);
986
- await mkdirp.mkdirp(path__default.default.dirname(typesPath));
987
- const moduleBlocks = await extractModuleBlocksFromTypes({
988
- extractResult: extractorResult,
989
- tsOutDir: tmpPath
990
- }), code = [typesBuf.toString(), ...moduleBlocks].join(`
991
-
992
- `), prettyCode = await prettier__namespace.format(code, {
993
- ...prettierConfig,
994
- filepath: typesPath
995
- });
996
- for (const expFilePath of filePaths) {
997
- const expTypesPath = path__default.default.resolve(distPath, expFilePath);
998
- await fs__default.default.writeFile(expTypesPath, prettyCode), files.push({
999
- type: "types",
1000
- path: expTypesPath
1001
- });
1002
- }
1003
- return shouldCleanUpDts && await fs__default.default.unlink(typesPath), { extractorResult, messages };
1004
- }
1005
- async function doExtract(ctx, task) {
1006
- const { config: config2, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
1007
- if (!ts2.config || !ts2.configPath)
1008
- return { type: "dts", messages: [], results: [] };
1009
- const { outDir, rootDir = cwd } = ts2.config.options;
1010
- if (!outDir)
1011
- throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
1012
- const tmpPath = path__default.default.resolve(outDir, "__tmp__");
1013
- await buildTypes({ cwd, logger, outDir: tmpPath, strict, tsconfig: ts2.config });
1014
- const messages = [], results = [];
1015
- for (const entry of task.entries) {
1016
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path__default.default.resolve(
1017
- tmpPath,
1018
- path__default.default.relative(rootDir, path__default.default.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
1019
- ), targetPaths = entry.targetPaths.map((targetPath) => path__default.default.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path__default.default.relative(outDir, targetPath)), result = await extractTypes({
1020
- bundledPackages: bundledPackages || [],
1021
- customTags: config2?.extract?.customTags,
1022
- distPath: outDir,
1023
- exportPath,
1024
- files,
1025
- filePaths,
1026
- projectPath: cwd,
1027
- rules: config2?.extract?.rules,
1028
- sourceTypesPath,
1029
- tsconfig: ts2.config,
1030
- tmpPath,
1031
- tsconfigPath: path__default.default.resolve(cwd, ts2.configPath || "tsconfig.json"),
1032
- extractorDisabled: config2?.extract?.enabled === !1
1033
- });
1034
- messages.push(...result.messages);
1035
- const errors = result.messages.filter((msg) => msg.logLevel === "error");
1036
- if (errors.length > 0)
1037
- throw await rimraf.rimraf(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
1038
- results.push({ sourcePath: path__default.default.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
1039
- }
1040
- return await rimraf.rimraf(tmpPath), { type: "dts", messages, results };
1041
- }
1042
- const dtsTask = {
1043
- name: (ctx, task) => [
1044
- `Build type definitions with ${chalk__default.default.bold(ctx.dts)}...`,
1045
- " entries:",
1046
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
1047
- ` - ${chalk__default.default.cyan(entry.importId)}: `,
1048
- `${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(targetPath)}`
1049
- ].join("")).join(`
1050
- `))
1051
- ].join(`
1052
- `),
1053
- exec: (ctx, task) => new rxjs.Observable((observer) => {
1054
- doExtract(ctx, task).then((result) => {
1055
- observer.next(result), observer.complete();
1056
- }).catch((err) => {
1057
- observer.error(err);
1058
- });
1059
- }),
1060
- complete: (ctx, _task, result) => {
1061
- printExtractMessages(ctx, result.messages);
1062
- },
1063
- error: (ctx, _task, err) => {
1064
- const { logger } = ctx;
1065
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
1066
- }
1067
- }, dtsWatchTask = {
1068
- name: (_ctx, task) => [
1069
- "build type definitions",
1070
- ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
1071
- ` - ${chalk__default.default.cyan(entry.importId)}: `,
1072
- `${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(targetPath)}`
1073
- ].join("")))
1074
- ].join(`
1075
- `),
1076
- exec: (ctx, task) => {
1077
- const { config: config2, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
1078
- return new rxjs.Observable((observer) => {
1079
- if (!tsContext.config || !tsContext.configPath) {
1080
- observer.next({ type: "dts", messages: [], results: [] }), observer.complete();
1081
- return;
1082
- }
1083
- const { outDir, rootDir = cwd } = tsContext.config.options;
1084
- if (!outDir) {
1085
- observer.error(new Error("tsconfig.json is missing `compilerOptions.outDir`"));
1086
- return;
1087
- }
1088
- const tmpPath = path__default.default.resolve(outDir, "__tmp__");
1089
- buildTypes({
1090
- cwd,
1091
- logger,
1092
- outDir: tmpPath,
1093
- tsconfig: tsContext.config,
1094
- strict
1095
- }).catch((err) => {
1096
- observer.error(err);
1097
- });
1098
- const host = ts__default.default.createWatchCompilerHost(
1099
- tsContext.configPath,
1100
- {
1101
- ...tsContext.config.options,
1102
- declaration: !0,
1103
- declarationDir: tmpPath,
1104
- emitDeclarationOnly: !0,
1105
- noEmit: !1,
1106
- noEmitOnError: strict ? !0 : tsContext.config.options.noEmitOnError ?? !0,
1107
- outDir: tmpPath
1108
- },
1109
- ts__default.default.sys,
1110
- ts__default.default.createEmitAndSemanticDiagnosticsBuilderProgram,
1111
- (diagnostic) => {
1112
- logger.error(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
1113
- `));
1114
- },
1115
- (diagnostic) => {
1116
- logger.info(ts__default.default.flattenDiagnosticMessageText(diagnostic.messageText, `
1117
- `));
1118
- }
1119
- ), origPostProgramCreate = host.afterProgramCreate;
1120
- host.afterProgramCreate = async (program) => {
1121
- origPostProgramCreate?.(program);
1122
- const messages = [], results = [];
1123
- for (const entry of task.entries) {
1124
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path__default.default.resolve(
1125
- tmpPath,
1126
- path__default.default.relative(rootDir, path__default.default.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
1127
- ), targetPaths = entry.targetPaths.map((targetPath) => path__default.default.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path__default.default.relative(outDir, targetPath));
1128
- try {
1129
- const result = await extractTypes({
1130
- bundledPackages: bundledPackages || [],
1131
- customTags: config2?.extract?.customTags,
1132
- cwd,
1133
- distPath: outDir,
1134
- exportPath,
1135
- files,
1136
- filePaths,
1137
- projectPath: cwd,
1138
- rules: config2?.extract?.rules,
1139
- sourceTypesPath,
1140
- tsconfig: tsContext.config,
1141
- tmpPath,
1142
- tsconfigPath: path__default.default.resolve(cwd, tsContext.configPath || "tsconfig.json"),
1143
- extractorDisabled: config2?.extract?.enabled === !1
1144
- });
1145
- messages.push(...result.messages), results.push({ sourcePath: path__default.default.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
1146
- } catch (err) {
1147
- if (err instanceof DtsError)
1148
- messages.push(...err.messages);
1149
- else {
1150
- observer.error(err);
1151
- return;
1152
- }
1153
- }
1154
- }
1155
- observer.next({ type: "dts", messages, results });
1156
- };
1157
- const watchProgram = ts__default.default.createWatchProgram(host);
1158
- return () => {
1159
- watchProgram.close(), rimraf__namespace.sync(tmpPath);
1160
- };
1161
- });
1162
- },
1163
- complete: (ctx, task, result) => {
1164
- const { logger } = ctx;
1165
- printExtractMessages(ctx, result.messages), logger.success(
1166
- `build type definitions
1167
- ${task.entries.map(
1168
- (entry) => ` - ${chalk__default.default.cyan(entry.importId)}: ${chalk__default.default.yellow(entry.sourcePath)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(entry.targetPaths.join(", "))}`
1169
- ).join(`
1170
- `)}`
1171
- ), logger.log("");
1172
- },
1173
- error: (ctx, _task, err) => {
1174
- const { logger } = ctx;
1175
- err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
1176
- }
1177
- };
1178
- function createConsoleSpy(options) {
1179
- const { onRestored } = options || {}, original = {
1180
- log: console.log,
1181
- warn: console.warn,
1182
- error: console.error
1183
- }, messages = [];
1184
- 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 }), {
1185
- messages,
1186
- restore: () => {
1187
- console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
1188
- }
1189
- };
1190
- }
1191
- const rolldownDtsTask = {
1192
- name: (ctx, task) => {
1193
- 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 ? [
1194
- " bundles:",
1195
- ...bundleEntries.map(
1196
- (e) => [
1197
- " - ",
1198
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
1199
- ].join("")
1200
- )
1201
- ] : [], entriesLines = entries.length ? [
1202
- " entries:",
1203
- ...entries.map(
1204
- (e) => [
1205
- " - ",
1206
- `${chalk__default.default.cyan(path__default.default.join(ctx.pkg.name, e.path))}: `,
1207
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(replaceFileEnding(e.output))}`
1208
- ].join("")
1209
- )
1210
- ] : [];
1211
- return [
1212
- `Build type definitions with ${chalk__default.default.bold("rolldown")}...`,
1213
- ` format: ${chalk__default.default.yellow(task.format)}`,
1214
- ...targetLines,
1215
- ...bundlesLines,
1216
- ...entriesLines
1217
- ].join(`
1218
- `);
1219
- },
1220
- exec: (ctx, task) => rxjs.from(execPromise$1(ctx, task)),
1221
- complete: () => {
1222
- },
1223
- error: (_ctx, _task, err) => {
1224
- console.error(err);
1225
- }
1226
- };
1227
- async function execPromise$1(ctx, task) {
1228
- const [{ rolldown }, { resolveRolldownConfig }] = await Promise.all([
1229
- import("rolldown"),
1230
- Promise.resolve().then(function() {
1231
- return require("./resolveRolldownConfig.cjs");
1232
- })
1233
- ]), { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
1234
- onRestored: (messages) => {
1235
- for (const msg of messages) {
1236
- const text = String(msg.args[0]);
1237
- msg.code !== "CIRCULAR_DEPENDENCY" && (text.startsWith("Dynamic import can only") || text.startsWith("Sourcemap is likely to be incorrect") || (msg.type === "log" && logger.info(...msg.args), msg.type === "warn" && logger.warn(...msg.args), msg.type === "error" && logger.error(...msg.args)));
1238
- }
1239
- }
1240
- });
1241
- try {
1242
- const { inputOptions, outputOptions } = resolveRolldownConfig(ctx, task), bundle = await rolldown({
1243
- ...inputOptions,
1244
- onwarn(warning) {
1245
- consoleSpy.messages.push({
1246
- type: "warn",
1247
- code: warning.code,
1248
- args: [warning.message]
1249
- });
1250
- }
1251
- }), { output } = await bundle.generate(outputOptions);
1252
- for (const chunkOrAsset of output)
1253
- chunkOrAsset.type === "asset" ? files.push({
1254
- type: "asset",
1255
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1256
- }) : files.push({
1257
- type: "chunk",
1258
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1259
- });
1260
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
1261
- } catch (err) {
1262
- throw consoleSpy.restore(), err;
1263
- }
1264
- }
1265
- function replaceFileEnding(path2) {
1266
- switch (!0) {
1267
- case path2.endsWith(".mjs"):
1268
- return path2.replace(/\.mjs$/, ".d.mts");
1269
- case path2.endsWith(".cjs"):
1270
- return path2.replace(/\.cjs$/, ".d.cts");
1271
- default:
1272
- return path2.replace(/\.js$/, ".d.ts");
1273
- }
1274
- }
1275
- function optimizeCss(options) {
1276
- return {
1277
- name: "optimize-css",
1278
- async generateBundle(_outputOptions, bundle, _isWrite) {
1279
- for (const [fileName, assetOrChunk] of Object.entries(bundle))
1280
- if (assetOrChunk.type === "asset") {
1281
- const asset = assetOrChunk;
1282
- if (asset.originalFileNames.includes(options.extractFileName)) {
1283
- const sourceMapFileName = `${fileName}.map`;
1284
- await transformCss(
1285
- asset,
1286
- bundle[sourceMapFileName]?.type === "asset" ? bundle[sourceMapFileName] : void 0,
1287
- options.browserslist
1288
- );
1289
- }
1290
- }
1291
- }
1292
- };
1293
- }
1294
- async function transformCss(asset, sourceMapAsset, browserslistConfig) {
1295
- const css = asset.source.toString(), file = asset.fileName, targets = lightningcss.browserslistToTargets(browserslist__default.default(browserslistConfig)), lightningCssResult = lightningcss.transform({
1296
- filename: file,
1297
- code: Buffer.from(css),
1298
- minify: !0,
1299
- cssModules: !1,
1300
- targets,
1301
- sourceMap: !!sourceMapAsset,
1302
- inputSourceMap: sourceMapAsset ? sourceMapAsset.source.toString() : void 0
1303
- });
1304
- lightningCssResult.warnings.length && console.warn(lightningCssResult.warnings), asset.source = new TextDecoder().decode(lightningCssResult.code), sourceMapAsset && lightningCssResult.map && (sourceMapAsset.source = new TextDecoder().decode(lightningCssResult.map), asset.source += `
1305
- /*# sourceMappingURL=${path.basename(sourceMapAsset.fileName)}*/
1306
- `);
1307
- }
1308
- function resolveRollupConfig(ctx, buildTask) {
1309
- 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(
1310
- Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path__default.default.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
1311
- ), entries = buildTask.entries.map((entry) => ({
1312
- ...entry,
1313
- name: path__default.default.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
1314
- }), {}), 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(
1315
- Object.entries(config2?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
1316
- ), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config2?.rollup || {}, defaultPlugins = [
1317
- replace__default.default({
1318
- preventAssignment: !0,
1319
- values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
1320
- "process.env.PKG_FILE_PATH": (arg) => {
1321
- const sourcePath = `./${path__default.default.relative(cwd, arg)}`, entry = entries.find((e) => e.source === sourcePath);
1322
- return entry ? JSON.stringify(
1323
- path__default.default.relative(cwd, path__default.default.resolve(outDir, entry.name + outputExt))
1324
- ) : (console.error(`could not find source entry: ${sourcePath}`), "null");
1325
- },
1326
- "process.env.PKG_FORMAT": JSON.stringify(format),
1327
- "process.env.PKG_RUNTIME": JSON.stringify(runtime),
1328
- "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
1329
- ...replacements
1330
- }
1331
- }),
1332
- alias__default.default({
1333
- entries: { ...pathAliases }
1334
- }),
1335
- pluginNodeResolve.nodeResolve({
1336
- browser: runtime === "browser",
1337
- extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
1338
- preferBuiltins: !0
1339
- }),
1340
- commonjs__default.default(),
1341
- json__default.default(),
1342
- config2?.rollup?.vanillaExtract && rollupPlugin.vanillaExtractPlugin(
1343
- config2?.rollup?.vanillaExtract === !0 ? {
1344
- extract: {
1345
- name: runtime === "node" ? "bundle.node.css" : runtime === "browser" ? "bundle.browser.css" : "bundle.css",
1346
- sourcemap: !0
1347
- },
1348
- identifiers: "short"
1349
- } : config2?.rollup?.vanillaExtract
1350
- ),
1351
- config2?.rollup?.vanillaExtract && optimizeCss(
1352
- config2?.rollup?.vanillaExtract === !0 ? {
1353
- extractFileName: runtime === "node" ? "bundle.node.css" : runtime === "browser" ? "bundle.browser.css" : "bundle.css",
1354
- browserslist: DEFAULT_BROWSERSLIST_QUERY
1355
- } : {
1356
- extractFileName: typeof config2.rollup.vanillaExtract.extract == "object" && config2.rollup.vanillaExtract.extract.name ? config2.rollup.vanillaExtract.extract.name : runtime === "node" ? "bundle.node.css" : runtime === "browser" ? "bundle.browser.css" : "bundle.css",
1357
- browserslist: config2.rollup.vanillaExtract.browserslist || DEFAULT_BROWSERSLIST_QUERY
1358
- }
1359
- ),
1360
- (config2?.babel?.reactCompiler || config2?.babel?.styledComponents) && pluginBabel.babel({
1361
- babelrc: !1,
1362
- presets: ["@babel/preset-typescript"],
1363
- babelHelpers: "bundled",
1364
- extensions: [".ts", ".tsx", ".js", ".jsx"],
1365
- plugins: [
1366
- // The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
1367
- config2?.babel?.styledComponents && [
1368
- "babel-plugin-styled-components",
1369
- {
1370
- // 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``"
1371
- fileName: !1,
1372
- // Native template literals take less space than this transpilation
1373
- transpileTemplateLiterals: !1,
1374
- // Massively helps dead code elimination and tree-shaking
1375
- pure: !0,
1376
- // disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
1377
- cssProp: !1,
1378
- ...typeof config2.babel.styledComponents == "object" ? config2.babel.styledComponents : {}
1379
- }
1380
- ],
1381
- config2?.babel?.reactCompiler && [
1382
- "babel-plugin-react-compiler",
1383
- config2?.reactCompilerOptions || {}
1384
- ]
1385
- ].filter(Boolean)
1386
- }),
1387
- esbuild__default.default({
1388
- jsx: config2?.jsx ?? "automatic",
1389
- jsxFactory: config2?.jsxFactory ?? "createElement",
1390
- jsxFragment: config2?.jsxFragment ?? "Fragment",
1391
- jsxImportSource: config2?.jsxImportSource ?? "react",
1392
- target,
1393
- tsconfig: ctx.ts.configPath || "tsconfig.json",
1394
- treeShaking: !0,
1395
- minifySyntax: config2?.minify !== !1,
1396
- supported: {
1397
- "template-literal": !0
1398
- }
1399
- }),
1400
- Array.isArray(config2?.babel?.plugins) && pluginBabel.getBabelOutputPlugin({
1401
- babelrc: !1,
1402
- plugins: config2.babel.plugins
1403
- }),
1404
- enableOptimizeLodash && rollupPlugin$1.optimizeLodashImports({
1405
- useLodashEs: format === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
1406
- ...typeof config2?.rollup?.optimizeLodash == "boolean" ? {} : config2?.rollup?.optimizeLodash
1407
- }),
1408
- minify && terser__default.default({
1409
- compress: { directives: !1, passes: 10 },
1410
- ecma: 2020,
1411
- output: {
1412
- comments: (_node, comment) => {
1413
- const text = comment.value;
1414
- return comment.type === "comment2" ? /@preserve|@license|@cc_on/i.test(text) : !1;
1415
- },
1416
- preserve_annotations: !0
1417
- }
1418
- })
1419
- ].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}`;
1420
- return {
1421
- inputOptions: {
1422
- context: cwd,
1423
- external: (id, importer) => {
1424
- if (exportIds?.includes(id))
1425
- return !0;
1426
- if (importer && (id.startsWith(".") || id.startsWith("/"))) {
1427
- const idPath = path__default.default.resolve(path__default.default.dirname(importer), id);
1428
- if (sourcePaths?.includes(idPath))
1429
- return logger.warn(
1430
- `detected self-referencing import \u2013 treating as external: ${path__default.default.relative(
1431
- cwd,
1432
- idPath
1433
- )}`
1434
- ), !0;
1435
- }
1436
- const idParts = id.split("/"), name = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0];
1437
- return !!(name && external.includes(name));
1438
- },
1439
- input: entries.reduce(
1440
- (acc, entry) => Object.assign(acc, { [entry.name]: entry.source }),
1441
- {}
1442
- ),
1443
- watch: {
1444
- chokidar: {
1445
- usePolling: !0
1446
- }
1447
- },
1448
- plugins,
1449
- treeshake: {
1450
- preset: "recommended",
1451
- propertyReadSideEffects: !1,
1452
- // If the module ends with `.css` it is considered to be a side effect, even if the module is marked as no side effect,
1453
- // this option used to be `moduleSideEffects: 'no-external'`, and thus if it's not CSS it uses `!external`, which is equivalent to `'no-external'`
1454
- moduleSideEffects: (id, external2) => id.endsWith(".css") ? !0 : !external2,
1455
- annotations: !0,
1456
- ...config2?.rollup?.treeshake
1457
- },
1458
- experimentalLogSideEffects: config2?.rollup?.experimentalLogSideEffects
1459
- },
1460
- outputOptions: {
1461
- chunkFileNames,
1462
- compact: minify,
1463
- dir: outDir,
1464
- entryFileNames,
1465
- esModule: !0,
1466
- format,
1467
- interop: "compat",
1468
- sourcemap: config2?.sourcemap ?? !0,
1469
- hoistTransitiveImports: !1,
1470
- minifyInternalExports: minify,
1471
- assetFileNames: "[name][extname]",
1472
- ...config2?.rollup?.output
1473
- }
1474
- };
1475
- }
1476
- function hasDependency(pkg, packageName) {
1477
- return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
1478
- }
1479
- const rollupTask = {
1480
- name: (ctx, task) => {
1481
- 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 ? [
1482
- " bundles:",
1483
- ...bundleEntries.map(
1484
- (e) => [
1485
- " - ",
1486
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
1487
- ].join("")
1488
- )
1489
- ] : [], entriesLines = entries.length ? [
1490
- " entries:",
1491
- ...entries.map(
1492
- (e) => [
1493
- " - ",
1494
- `${chalk__default.default.cyan(path__default.default.join(ctx.pkg.name, e.path))}: `,
1495
- `${chalk__default.default.yellow(e.source)} ${chalk__default.default.gray("\u2192")} ${chalk__default.default.yellow(e.output)}`
1496
- ].join("")
1497
- )
1498
- ] : [];
1499
- return [
1500
- "Build javascript files...",
1501
- ` format: ${chalk__default.default.yellow(task.format)}`,
1502
- ...targetLines,
1503
- ...bundlesLines,
1504
- ...entriesLines
1505
- ].join(`
1506
- `);
1507
- },
1508
- exec: (ctx, task) => new rxjs.Observable((observer) => {
1509
- execPromise(ctx, task).then((result) => {
1510
- observer.next(result), observer.complete();
1511
- }).catch((err) => observer.error(err));
1512
- }),
1513
- complete: () => {
1514
- },
1515
- error: (_ctx, _task, err) => {
1516
- console.error(err);
1517
- }
1518
- };
1519
- async function execPromise(ctx, task) {
1520
- const { distPath, files, logger } = ctx, outDir = path__default.default.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
1521
- onRestored: (messages) => {
1522
- for (const msg of messages) {
1523
- const text = String(msg.args[0]);
1524
- msg.code !== "CIRCULAR_DEPENDENCY" && (text.startsWith("Dynamic import can only") || text.startsWith("Sourcemap is likely to be incorrect") || (msg.type === "log" && logger.info(...msg.args), msg.type === "warn" && logger.warn(...msg.args), msg.type === "error" && logger.error(...msg.args)));
1525
- }
1526
- }
1527
- });
1528
- try {
1529
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task), bundle = await rollup.rollup({
1530
- ...inputOptions,
1531
- onwarn(warning) {
1532
- consoleSpy.messages.push({
1533
- type: "warn",
1534
- code: warning.code,
1535
- args: [warning.message]
1536
- });
1537
- }
1538
- }), { output } = await bundle.generate(outputOptions);
1539
- for (const chunkOrAsset of output)
1540
- chunkOrAsset.type === "asset" ? files.push({
1541
- type: "asset",
1542
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1543
- }) : files.push({
1544
- type: "chunk",
1545
- path: path__default.default.resolve(outDir, chunkOrAsset.fileName)
1546
- });
1547
- await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
1548
- } catch (err) {
1549
- throw consoleSpy.restore(), err;
1550
- }
1551
- }
1552
- const rollupWatchTask = {
1553
- name: (ctx, task) => `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
1554
- ${task.entries.map((e) => `${chalk__default.default.blue(path__default.default.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
1555
- `)}`,
1556
- exec: (ctx, task) => {
1557
- const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task);
1558
- return new rxjs.Observable((observer) => {
1559
- const watchOptions = {
1560
- ...inputOptions,
1561
- output: outputOptions
1562
- }, watcher = rollup.watch(watchOptions);
1563
- return watcher.on("event", (event) => {
1564
- observer.next(event);
1565
- }), () => {
1566
- watcher.close();
1567
- };
1568
- });
1569
- },
1570
- complete: (ctx, task, event) => {
1571
- const { logger } = ctx;
1572
- if (event.code === "BUNDLE_END") {
1573
- logger.success(
1574
- `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
1575
- ${task.entries.map((e) => `${chalk__default.default.blue(path__default.default.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
1576
- `)}`
1577
- ), logger.log("");
1578
- return;
1579
- }
1580
- if (event.code !== "BUNDLE_START" && event.code !== "END" && event.code === "ERROR") {
1581
- logger.error(event.code, event);
1582
- return;
1583
- }
1584
- },
1585
- error: (ctx, _task, err) => {
1586
- const { logger } = ctx;
1587
- err instanceof Error && logger.log(err);
1588
- }
1589
- }, buildTaskHandlers = {
1590
- "build:dts": dtsTask,
1591
- "build:js": rollupTask,
1592
- "rolldown:dts": rolldownDtsTask
1593
- }, watchTaskHandlers = {
1594
- "watch:dts": dtsWatchTask,
1595
- "watch:js": rollupWatchTask
1596
- };
1597
- async function build(options) {
1598
- const {
1599
- cwd,
1600
- emitDeclarationOnly,
1601
- strict = !1,
1602
- tsconfig: tsconfigOption,
1603
- clean = !1,
1604
- quiet = !1
1605
- } = options, logger = createLogger(quiet), config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json", ctx = await resolveBuildContext({
1606
- config: config2,
1607
- cwd,
1608
- emitDeclarationOnly,
1609
- logger,
1610
- pkg,
1611
- strict,
1612
- tsconfig
1613
- });
1614
- clean && (quiet || logger.log(
1615
- `Deleting the \`dist\` folder: './${path__default.default.relative(cwd, ctx.distPath)}' before building...`
1616
- ), await rimraf.rimraf(ctx.distPath));
1617
- const buildTasks = resolveBuildTasks(ctx);
1618
- for (const task of buildTasks) {
1619
- const handler = buildTaskHandlers[task.type], taskName = handler.name(ctx, task), spinner = createSpinner(taskName, quiet);
1620
- try {
1621
- const result = await handler.exec(ctx, task).toPromise();
1622
- spinner.complete(), ctx.logger.log(), handler.complete(ctx, task, result);
1623
- } catch (err) {
1624
- if (spinner.error(), err instanceof Error) {
1625
- const RE_CWD = new RegExp(`${cwd}`, "g");
1626
- ctx.logger.error(err.message.replace(RE_CWD, ".")), ctx.logger.log();
1627
- }
1628
- handler.error(ctx, task, err), process.exit(1);
1629
- }
1630
- }
1631
- }
1632
- function getFilesize(file) {
1633
- const stats = node_fs.statSync(file);
1634
- return prettyBytes__default.default(stats.size);
1635
- }
1636
- function getFileInfo(cwd, filePath) {
1637
- const p = path__default.default.resolve(cwd, filePath), exists = fileExists(p), size = exists ? getFilesize(p) : void 0;
1638
- return { exists, size };
1639
- }
1640
- function printPackageTree(ctx) {
1641
- const { cwd, exports: exports2, logger, pkg } = ctx;
1642
- if (!exports2) return;
1643
- logger.log(`${chalk__default.default.blue(pkg.name)}@${chalk__default.default.green(pkg.version)}`);
1644
- const tree = {};
1645
- pkg.type && (tree.type = chalk__default.default.yellow(pkg.type)), pkg.bin && (tree.bin = Object.fromEntries(
1646
- Object.entries(pkg.bin).map(([name, file]) => [chalk__default.default.cyan(name), fileInfo(file)])
1647
- ));
1648
- function fileInfo(file) {
1649
- const info = getFileInfo(cwd, file);
1650
- 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")}`;
1651
- }
1652
- tree.exports = Object.fromEntries(
1653
- Object.entries(exports2).filter(([, entry]) => entry._exported).map(([exportPath, entry]) => {
1654
- const exp = {
1655
- source: fileInfo(entry.source),
1656
- browser: void 0,
1657
- require: void 0,
1658
- node: void 0,
1659
- import: void 0,
1660
- default: fileInfo(entry.default)
1661
- };
1662
- 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];
1663
- })
1664
- ), logger.log(treeify__default.default.asTree(tree, !0, !0));
1665
- }
1666
- async function check(options) {
1667
- const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger(), spinner = createSpinner("");
1668
- try {
1669
- const 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 });
1670
- if (printPackageTree(ctx), strict) {
1671
- const missingFiles = [];
1672
- for (const [, exp] of Object.entries(ctx.exports || {}))
1673
- 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);
1674
- 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));
1675
- const exportPaths = {
1676
- require: [],
1677
- import: []
1678
- };
1679
- for (const exp of Object.values(ctx.exports || {}))
1680
- exp._exported && (exp.require && exportPaths.require.push(exp.require), exp.import && exportPaths.import.push(exp.import));
1681
- const external = [
1682
- ...Object.keys(pkg.dependencies || {}),
1683
- ...Object.keys(pkg.devDependencies || {})
1684
- ], consoleSpy = createConsoleSpy();
1685
- exportPaths.import.length && checkExports(exportPaths.import, { cwd, external, format: "esm", logger }), exportPaths.require.length && checkExports(exportPaths.require, { cwd, external, format: "cjs", logger }), consoleSpy.restore();
1686
- }
1687
- ctx.dts === "rolldown" && ctx.config?.extract?.enabled !== !1 && await checkApiExtractorReleaseTags(ctx), spinner.complete();
1688
- } catch (err) {
1689
- if (spinner.error(), err instanceof Error) {
1690
- const RE_CWD = new RegExp(`${cwd}`, "g");
1691
- logger.error(err.message.replace(RE_CWD, ".")), logger.log();
1692
- }
1693
- process.exit(1);
1694
- }
1695
- }
1696
- async function checkExports(exportPaths, options) {
1697
- const { build: build2 } = await import("esbuild"), { cwd, external, format, logger } = options, code = exportPaths.map((id) => format ? `import('${id}');` : `require('${id}');`).join(`
1698
- `);
1699
- try {
1700
- const esbuildResult = await build2({
1701
- bundle: !0,
1702
- external,
1703
- format,
1704
- logLevel: "silent",
1705
- // otherwise output maps to stdout as we're using stdin
1706
- outfile: "/dev/null",
1707
- platform: "node",
1708
- // We're not interested in CSS files that might be imported as a side effect, so we'll treat them as empty
1709
- loader: { ".css": "empty" },
1710
- stdin: {
1711
- contents: code,
1712
- loader: "js",
1713
- resolveDir: cwd
1714
- }
1715
- });
1716
- if (esbuildResult.errors.length > 0) {
1717
- for (const msg of esbuildResult.errors)
1718
- printEsbuildMessage(logger.warn, msg), logger.log();
1719
- process.exit(1);
1720
- }
1721
- const esbuildWarnings = esbuildResult.warnings.filter((msg) => {
1722
- (msg.detail || msg.text).includes("does not affect esbuild's own target setting");
1723
- });
1724
- for (const msg of esbuildWarnings)
1725
- printEsbuildMessage(logger.warn, msg), logger.log();
1726
- } catch (err) {
1727
- if (isEsbuildFailure(err)) {
1728
- const { errors } = err;
1729
- for (const msg of errors)
1730
- printEsbuildMessage(logger.error, msg), logger.log();
1731
- } else err instanceof Error ? (logger.error(err.stack || err.message), logger.log()) : (logger.error(`${err}`), logger.log());
1732
- process.exit(1);
1733
- }
1734
- }
1735
- function printEsbuildMessage(log, msg) {
1736
- msg.location ? log(
1737
- [
1738
- `${msg.detail || msg.text}
1739
- `,
1740
- `${msg.location.line} | ${msg.location.lineText}
1741
- `,
1742
- `in ./${msg.location.file}:${msg.location.line}:${msg.location.column}`
1743
- ].join("")
1744
- ) : log(msg.detail || msg.text);
1745
- }
1746
- function isEsbuildFailure(err) {
1747
- 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);
1748
- }
1749
- function isEsbuildMessage(msg) {
1750
- return typeof msg == "object" && msg !== null && "text" in msg && typeof msg.text == "string" && "location" in msg && (msg.location === null || typeof msg.location == "object");
1751
- }
1752
- async function checkApiExtractorReleaseTags(ctx) {
1753
- const [
1754
- { Extractor, ExtractorConfig },
1755
- { createApiExtractorConfig: createApiExtractorConfig2 },
1756
- { createTSDocConfig: createTSDocConfig2 },
1757
- { getExtractMessagesConfig: getExtractMessagesConfig2 },
1758
- { printExtractMessages: printExtractMessages2 }
1759
- ] = await Promise.all([
1760
- import("@microsoft/api-extractor"),
1761
- Promise.resolve().then(function() {
1762
- return createApiExtractorConfig$1;
1763
- }),
1764
- Promise.resolve().then(function() {
1765
- return createTSDocConfig$1;
1766
- }),
1767
- Promise.resolve().then(function() {
1768
- return getExtractMessagesConfig$1;
1769
- }),
1770
- Promise.resolve().then(function() {
1771
- return printExtractMessages$1;
1772
- })
1773
- ]), customTags = ctx.config?.extract?.customTags || [], bundledPackages = ctx.bundledPackages, distPath = ctx.distPath, outDir = ctx.ts.config?.options.outDir, rules = ctx.config?.extract?.rules || {};
1774
- if (!outDir)
1775
- throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
1776
- for (const exp of Object.values(ctx.exports || {})) {
1777
- if (!exp._exported || !exp.default.endsWith(".js")) continue;
1778
- const dtsPath = exp.default.replace(/\.js$/, ".d.ts"), exportPath = path__default.default.resolve(ctx.cwd, dtsPath), tsdocConfigFile = await createTSDocConfig2({
1779
- customTags
1780
- }), extractorConfig = ExtractorConfig.prepare({
1781
- configObject: createApiExtractorConfig2({
1782
- bundledPackages,
1783
- distPath,
1784
- exportPath,
1785
- filePath: path__default.default.relative(outDir, dtsPath),
1786
- messages: getExtractMessagesConfig2({ rules }),
1787
- projectFolder: ctx.cwd,
1788
- mainEntryPointFilePath: exportPath,
1789
- tsconfig: ctx.ts.config,
1790
- tsconfigPath: path__default.default.resolve(ctx.cwd, ctx.ts.configPath || "tsconfig.json"),
1791
- dtsRollupEnabled: !1
1792
- }),
1793
- configObjectFullPath: void 0,
1794
- tsdocConfigFile,
1795
- packageJsonFullPath: path__default.default.resolve(ctx.cwd, "package.json")
1796
- }), messages = [];
1797
- Extractor.invoke(extractorConfig, {
1798
- // Equivalent to the "--local" command-line parameter
1799
- localBuild: !0,
1800
- // Equivalent to the "--verbose" command-line parameter
1801
- showVerboseMessages: !0,
1802
- // handle messages
1803
- messageCallback(message) {
1804
- messages.push(message), message.handled = !0;
1805
- }
1806
- }), printExtractMessages2(ctx, messages);
1807
- }
1808
- }
1809
- function defineConfig(configOptions) {
1810
- return configOptions;
1811
- }
1812
- function defineTemplateOption(option) {
1813
- return option;
1814
- }
1815
- const promptsTypes = {
1816
- string: "text"
1817
- };
1818
- async function createFromTemplate(options) {
1819
- const { cwd, logger, packagePath, template: templateOrResolver } = options, template = typeof templateOrResolver == "function" ? await templateOrResolver({ cwd, logger, packagePath }) : templateOrResolver;
1820
- logger.log("create new package at", path.relative(cwd, packagePath));
1821
- const templateOptions = {};
1822
- for (const templateOption of template.options) {
1823
- const templateValidate = templateOption.validate, res = await prompts__default.default(
1824
- {
1825
- type: promptsTypes[templateOption.type],
1826
- name: templateOption.name,
1827
- message: templateOption.description,
1828
- validate: templateValidate ? (prev) => templateValidate(prev) : void 0,
1829
- initial: typeof templateOption.initial == "function" ? templateOption.initial(templateOptions) : templateOption.initial
1830
- },
1831
- { onCancel: () => process.exit(0) }
1832
- );
1833
- templateOptions[templateOption.name] = templateOption.parse ? templateOption.parse(res[templateOption.name]) : res[templateOption.name];
1834
- }
1835
- const features = {};
1836
- for (const templateFeature of template.features) {
1837
- const res = templateFeature.optional ? await prompts__default.default(
1838
- {
1839
- type: "confirm",
1840
- name: "confirm",
1841
- message: `use ${templateFeature.name}?`,
1842
- initial: templateFeature.initial
1843
- },
1844
- { onCancel: () => process.exit(0) }
1845
- ) : void 0;
1846
- features[templateFeature.name] = res?.confirm || !templateFeature.optional;
1847
- }
1848
- const files = await template.getFiles(templateOptions, features);
1849
- files.sort((a, b) => a.name.localeCompare(b.name));
1850
- for (const file of files) {
1851
- const filePath = path.resolve(packagePath, file.name);
1852
- await mkdirp.mkdirp(path.dirname(filePath)), await fs.writeFile(filePath, file.contents.trim() + `
1853
- `), logger.success(`wrote ${path.relative(cwd, filePath)}`);
1854
- }
1855
- }
1856
- async function isEmptyDirectory(dirPath) {
1857
- return (await fs.readdir(dirPath)).length === 0;
1858
- }
1859
- const overridableDefaults = {
1860
- endOfLine: "lf",
1861
- tabWidth: 2,
1862
- useTabs: !1
1863
- }, json5 = {
1864
- files: ["*.json5"],
1865
- options: {
1866
- quoteProps: "preserve",
1867
- singleQuote: !1
1868
- }
1869
- }, yaml = {
1870
- files: ["*.yml"],
1871
- options: {
1872
- singleQuote: !1
1873
- }
1874
- }, config = {
1875
- ...overridableDefaults,
1876
- printWidth: 100,
1877
- semi: !1,
1878
- singleQuote: !0,
1879
- quoteProps: "consistent",
1880
- bracketSpacing: !1,
1881
- plugins: ["prettier-plugin-packagejson"],
1882
- overrides: [json5, yaml]
1883
- }, RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i, defaultTemplate = async ({ cwd, logger, packagePath }) => {
1884
- const gitConfig = getGitUserConfig(cwd);
1885
- return {
1886
- options: [
1887
- {
1888
- name: "repo",
1889
- type: "string",
1890
- description: "git url",
1891
- validate: (v) => {
1892
- if (!v) return !0;
1893
- try {
1894
- return gitUrlParse__default.default(v), !0;
1895
- } catch {
1896
- return "invalid git url";
1897
- }
1898
- },
1899
- parse: (v) => {
1900
- if (!v) return null;
1901
- const result = gitUrlParse__default.default(v);
1902
- return { source: result.source, owner: result.owner, name: result.name };
1903
- }
1904
- },
1905
- {
1906
- name: "pkgName",
1907
- type: "string",
1908
- description: "package name",
1909
- initial: (options) => options.repo?.name || void 0,
1910
- validate: (v) => v ? RE_NAME.exec(v) ? !0 : "invalid package name" : "package name is required",
1911
- parse: (v) => {
1912
- if (!v)
1913
- throw new Error("package name is required");
1914
- if (!RE_NAME.exec(v))
1915
- throw new Error("invalid package name");
1916
- const [scope, name] = v.split("/");
1917
- return { scope, name, fullName: v };
1918
- }
1919
- },
1920
- {
1921
- name: "description",
1922
- type: "string",
1923
- description: "package description"
1924
- },
1925
- {
1926
- name: "authorName",
1927
- type: "string",
1928
- description: "package author name",
1929
- initial: gitConfig.user
1930
- },
1931
- {
1932
- name: "authorEmail",
1933
- type: "string",
1934
- description: "package author email",
1935
- initial: gitConfig.email
1936
- },
1937
- {
1938
- name: "license",
1939
- type: "string",
1940
- description: "package license",
1941
- initial: "MIT",
1942
- validate: (v) => v ? !0 : "license is required"
1943
- }
1944
- ],
1945
- features: [
1946
- {
1947
- name: "eslint",
1948
- optional: !0,
1949
- initial: !0
1950
- },
1951
- {
1952
- name: "prettier",
1953
- optional: !0,
1954
- initial: !0
1955
- },
1956
- {
1957
- name: "typescript",
1958
- optional: !0,
1959
- initial: !0
1960
- }
1961
- ],
1962
- async getFiles(options, features) {
1963
- const { pkgName, repo } = options, { fullName: name } = pkgName, author = [options.authorName, options.authorEmail && `<${options.authorEmail}>`].filter(Boolean).join(" ") ?? void 0, pkgJson = {
1964
- name,
1965
- version: "0.0.0",
1966
- description: options.description ?? void 0,
1967
- keywords: [],
1968
- homepage: void 0,
1969
- bugs: void 0,
1970
- repository: void 0,
1971
- license: options.license,
1972
- author,
1973
- sideEffects: !1,
1974
- type: "module",
1975
- exports: {
1976
- ".": {
1977
- source: features.typescript ? "./src/index.ts" : "./src/index.js",
1978
- require: "./dist/index.cjs",
1979
- default: "./dist/index.js"
1980
- },
1981
- "./package.json": "./package.json"
1982
- },
1983
- main: "./dist/index.cjs",
1984
- module: "./dist/index.js",
1985
- types: void 0,
1986
- files: ["dist", "src"],
1987
- scripts: {
1988
- build: "pkg build --strict --clean --check",
1989
- format: features.prettier ? "prettier --write --cache --ignore-unknown ." : void 0
1990
- },
1991
- "lint-staged": features.prettier ? {
1992
- "*": ["prettier --write --cache --ignore-unknown"]
1993
- } : void 0,
1994
- browserslist: "extends @sanity/browserslist-config",
1995
- prettier: features.prettier ? "@sanity/prettier-config" : void 0,
1996
- dependencies: {},
1997
- devDependencies: {
1998
- "@sanity/pkg-utils": "^6",
1999
- "@sanity/prettier-config": features.prettier ? "^1" : void 0,
2000
- "@typescript-eslint/eslint-plugin": void 0,
2001
- "@typescript-eslint/parser": void 0,
2002
- eslint: void 0,
2003
- "eslint-config-prettier": void 0,
2004
- "eslint-plugin-import": void 0,
2005
- "eslint-plugin-prettier": void 0,
2006
- "eslint-plugin-simple-import-sort": void 0,
2007
- "lint-staged": "^15",
2008
- prettier: features.prettier ? "^3" : void 0,
2009
- typescript: void 0
2010
- },
2011
- engines: {
2012
- node: ">=18.0.0"
2013
- }
2014
- }, files = [];
2015
- if (files.push({
2016
- name: ".editorconfig",
2017
- contents: outdent.outdent`
2018
- root = true
2019
-
2020
- [*]
2021
- charset = utf-8
2022
- indent_style = space
2023
- indent_size = 2
2024
- end_of_line = lf
2025
- insert_final_newline = true
2026
- trim_trailing_whitespace = true
2027
- `
2028
- }), files.push({
2029
- name: ".gitignore",
2030
- contents: outdent.outdent`
2031
- *.local
2032
- *.log
2033
- *.tgz
2034
-
2035
- .DS_Store
2036
- dist
2037
- etc
2038
- node_modules
2039
- `
2040
- }), features.prettier && files.push({
2041
- name: ".prettierignore",
2042
- contents: outdent.outdent`
2043
- dist
2044
- pnpm-lock.yaml
2045
- `
2046
- }), repo && (pkgJson.repository = {
2047
- type: "git",
2048
- url: `git+ssh://git@${repo.source}/${repo.owner}/${repo.name}.git`
2049
- }, pkgJson.bugs = {
2050
- url: `https://${repo.source}/${repo.owner}/${repo.name}/issues`
2051
- }, pkgJson.homepage = `https://${repo.source}/${repo.owner}/${repo.name}#readme`), features.typescript) {
2052
- pkgJson.types = "./dist/index.d.ts", pkgJson.scripts = {
2053
- ...pkgJson.scripts,
2054
- "ts:check": "tsc --noEmit"
2055
- };
2056
- const devDependencies = pkgJson.devDependencies;
2057
- isRecord(devDependencies) && (devDependencies.typescript = "^5.4");
2058
- }
2059
- if (features.eslint) {
2060
- const eslintConfig = {
2061
- root: !0,
2062
- env: {
2063
- browser: !0,
2064
- es6: !0,
2065
- node: !0
2066
- },
2067
- extends: [
2068
- "eslint:recommended",
2069
- features.prettier ? "plugin:prettier/recommended" : void 0
2070
- ].filter(Boolean),
2071
- parserOptions: {
2072
- ecmaVersion: 2020,
2073
- sourceType: "module"
2074
- },
2075
- plugins: [
2076
- "import",
2077
- "simple-import-sort",
2078
- features.prettier ? "prettier" : void 0
2079
- ].filter(Boolean),
2080
- rules: {
2081
- "no-console": "error",
2082
- "no-shadow": "error",
2083
- "no-warning-comments": ["warn", { location: "start", terms: ["todo", "fixme"] }],
2084
- "quote-props": ["warn", "consistent-as-needed"],
2085
- "simple-import-sort/exports": "warn",
2086
- "simple-import-sort/imports": "warn",
2087
- strict: ["warn", "global"]
2088
- }
2089
- };
2090
- if (files.push({
2091
- name: ".eslintignore",
2092
- contents: outdent.outdent`
2093
- dist
2094
- `
2095
- }), pkgJson.scripts = {
2096
- ...pkgJson.scripts,
2097
- lint: features.typescript ? "eslint . --ext .cjs,.js,.ts,.tsx" : "eslint . --ext .cjs,.js"
2098
- }, pkgJson.devDependencies = {
2099
- ...pkgJson.devDependencies,
2100
- eslint: "^8",
2101
- "eslint-config-prettier": features.prettier ? "^9" : void 0,
2102
- "eslint-plugin-import": "^2",
2103
- "eslint-plugin-prettier": features.prettier ? "^5" : void 0,
2104
- "eslint-plugin-simple-import-sort": "^12"
2105
- }, features.typescript) {
2106
- pkgJson.devDependencies = {
2107
- ...pkgJson.devDependencies,
2108
- "@typescript-eslint/eslint-plugin": "^7",
2109
- "@typescript-eslint/parser": "^7"
2110
- };
2111
- const eslintConfigOverride = {
2112
- files: ["**/*.ts", "**/*.tsx"],
2113
- parser: "@typescript-eslint/parser",
2114
- parserOptions: {
2115
- project: ["./tsconfig.json"]
2116
- },
2117
- extends: [
2118
- "eslint:recommended",
2119
- features.prettier ? "plugin:prettier/recommended" : void 0,
2120
- "plugin:@typescript-eslint/eslint-recommended",
2121
- "plugin:@typescript-eslint/recommended"
2122
- ].filter(Boolean),
2123
- plugins: [
2124
- "import",
2125
- "@typescript-eslint",
2126
- "simple-import-sort",
2127
- features.prettier ? "prettier" : void 0
2128
- ].filter(Boolean),
2129
- rules: {
2130
- "@typescript-eslint/explicit-module-boundary-types": "error",
2131
- "@typescript-eslint/interface-name-prefix": "off",
2132
- "@typescript-eslint/member-delimiter-style": "off",
2133
- "@typescript-eslint/no-empty-interface": "off"
2134
- }
2135
- };
2136
- eslintConfig.overrides = [eslintConfigOverride];
2137
- }
2138
- files.push({
2139
- name: ".eslintrc.cjs",
2140
- contents: await prettierFormat(
2141
- path.resolve(packagePath, ".eslintrc.cjs"),
2142
- outdent.outdent`
2143
- 'use strict'
2144
-
2145
- /** @type import('eslint').Linter.Config */
2146
- module.exports = ${JSON.stringify(eslintConfig, null, 2)}
2147
- `,
2148
- config
2149
- )
2150
- });
2151
- }
2152
- features.typescript && (files.push({
2153
- name: "tsconfig.settings.json",
2154
- contents: await prettierFormat(
2155
- path.resolve(packagePath, "tsconfig.settings.json"),
2156
- outdent.outdent`
2157
- {
2158
- "extends": "@sanity/pkg-utils/tsconfig/strictest.json",
2159
- "compilerOptions": {
2160
- "rootDir": ".",
2161
- "outDir": "./dist"
2162
- }
2163
- }
2164
- `,
2165
- config
2166
- )
2167
- }), files.push({
2168
- name: "tsconfig.dist.json",
2169
- contents: await prettierFormat(
2170
- path.resolve(packagePath, "tsconfig.dist.json"),
2171
- outdent.outdent`
2172
- {
2173
- "extends": "./tsconfig.settings",
2174
- "include": ["./src"],
2175
- "exclude": ["./src/**/*.test.ts"]
2176
- }
2177
- `,
2178
- config
2179
- )
2180
- }), files.push({
2181
- name: "tsconfig.json",
2182
- contents: await prettierFormat(
2183
- path.resolve(packagePath, "tsconfig.json"),
2184
- outdent.outdent`
2185
- {
2186
- "extends": "./tsconfig.settings",
2187
- "include": ["./**/*.cjs", "./**/*.ts", "./**/*.tsx"],
2188
- "exclude": ["./node_modules"]
2189
- }
2190
- `,
2191
- config
2192
- )
2193
- })), features.typescript ? (files.push({
2194
- name: "package.config.ts",
2195
- contents: await prettierFormat(
2196
- path.resolve(packagePath, "package.config.ts"),
2197
- outdent.outdent`
2198
- import {defineConfig} from '@sanity/pkg-utils'
2199
-
2200
- // https://github.com/sanity-io/pkg-utils#configuration
2201
- export default defineConfig({
2202
- // the path to the tsconfig file for distributed builds
2203
- tsconfig: 'tsconfig.dist.json',
2204
- })
2205
- `,
2206
- config
2207
- )
2208
- }), files.push({
2209
- name: "src/index.ts",
2210
- contents: await prettierFormat(
2211
- path.resolve(packagePath, "src/index.ts"),
2212
- outdent.outdent`
2213
- /** @public */
2214
- export function main(): void {
2215
- //
2216
- }
2217
- `,
2218
- config
2219
- )
2220
- })) : (files.push({
2221
- name: "package.config.js",
2222
- contents: await prettierFormat(
2223
- path.resolve(packagePath, "package.config.js"),
2224
- outdent.outdent`
2225
- import {defineConfig} from '@sanity/pkg-utils'
2226
-
2227
- export default defineConfig({
2228
- extract: {
2229
- rules: {
2230
- // do not require internal members to be prefixed with \`_\`
2231
- 'ae-internal-missing-underscore': 'off',
2232
- },
2233
- },
2234
- })
2235
- `,
2236
- config
2237
- )
2238
- }), files.push({
2239
- name: "src/index.js",
2240
- contents: await prettierFormat(
2241
- path.resolve(packagePath, "src/index.js"),
2242
- outdent.outdent`
2243
- /** @public */
2244
- export function main() {
2245
- //
2246
- }
2247
- `,
2248
- config
2249
- )
2250
- }));
2251
- try {
2252
- pkgJson.dependencies = await resolveLatestDeps(pkgJson.dependencies ?? {});
2253
- } catch (error) {
2254
- logger.warn(error instanceof Error ? error.message : error);
2255
- }
2256
- try {
2257
- pkgJson.devDependencies = await resolveLatestDeps(pkgJson.devDependencies ?? {});
2258
- } catch (error) {
2259
- logger.warn(error instanceof Error ? error.message : error);
2260
- }
2261
- return files.push({
2262
- name: "package.json",
2263
- contents: await prettierFormat(
2264
- path.resolve(packagePath, "package.json"),
2265
- JSON.stringify(pkgJson, null, 2),
2266
- config
2267
- )
2268
- }), files;
2269
- }
2270
- };
2271
- };
2272
- function prettierFormat(filepath, input, prettierOptions) {
2273
- return prettier.format(input, { ...prettierOptions, plugins: [], filepath });
2274
- }
2275
- async function resolveLatestDeps(deps) {
2276
- const depsEntries = Object.entries(deps), latestDeps = {};
2277
- for (const entry of depsEntries) {
2278
- const [name, version] = entry;
2279
- if (version) {
2280
- const latestVersion = await getLatestVersion__default.default(name, version);
2281
- latestDeps[name] = latestVersion ? `^${latestVersion}` : version;
2282
- }
2283
- }
2284
- return latestDeps;
2285
- }
2286
- function getGitUserConfig(cwd) {
2287
- let user, email;
2288
- try {
2289
- 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;
2290
- } catch {
2291
- }
2292
- return { user, email };
2293
- }
2294
- async function init(options) {
2295
- if (!options.cwd)
2296
- throw new Error("Missing required option: cwd");
2297
- if (!options.path)
2298
- throw new Error("Missing required option: path");
2299
- const logger = createLogger(), packagePath = path.resolve(options.cwd, options.path);
2300
- await ensurePackagePath(packagePath), await createFromTemplate({
2301
- cwd: options.cwd,
2302
- logger,
2303
- template: defaultTemplate,
2304
- packagePath
2305
- });
2306
- }
2307
- async function ensurePackagePath(packagePath) {
2308
- if (!fileExists(packagePath)) {
2309
- await mkdirp.mkdirp(packagePath);
2310
- return;
2311
- }
2312
- if (!(await fs.lstat(packagePath)).isDirectory())
2313
- throw new Error("the package path is a file, not a directory");
2314
- if (!await isEmptyDirectory(packagePath))
2315
- throw new Error("the package directory is not empty");
2316
- }
2317
- function resolveWatchTasks(ctx) {
2318
- const { pkg, target } = ctx, tasks = [], exports2 = Object.entries(ctx.exports || {}).map(
2319
- ([_path, exp]) => ({ _path, ...exp })
2320
- ), dtsTask2 = {
2321
- type: "watch:dts",
2322
- entries: []
2323
- }, rollupTasks = {};
2324
- function addRollupTaskEntry(format, runtime, entry) {
2325
- const buildId = `${format}:${runtime}`;
2326
- rollupTasks[buildId] ? rollupTasks[buildId].entries.push(entry) : rollupTasks[buildId] = {
2327
- type: "watch:js",
2328
- buildId,
2329
- entries: [entry],
2330
- runtime,
2331
- format,
2332
- target: target[runtime]
2333
- };
2334
- }
2335
- for (const exp of exports2) {
2336
- const importId = path__default.default.join(pkg.name, exp._path);
2337
- exp.source?.endsWith(".ts") && dtsTask2.entries.push({
2338
- importId,
2339
- exportPath: exp._path,
2340
- sourcePath: exp.source,
2341
- targetPaths: getTargetPaths(pkg.type, exp)
2342
- }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
2343
- importId,
2344
- exportPath: exp._path,
2345
- sourcePath: exp.browser.source,
2346
- targetPaths: getTargetPaths(pkg.type, exp.browser)
2347
- }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
2348
- importId,
2349
- exportPath: exp._path,
2350
- sourcePath: exp.node.source,
2351
- targetPaths: getTargetPaths(pkg.type, exp.node)
2352
- });
2353
- }
2354
- for (const exp of exports2) {
2355
- const output = exp.require;
2356
- output && addRollupTaskEntry("commonjs", ctx.runtime, {
2357
- path: exp._path,
2358
- source: exp.source,
2359
- output
2360
- });
2361
- }
2362
- for (const exp of exports2) {
2363
- const output = exp.browser?.require;
2364
- output && addRollupTaskEntry("commonjs", "browser", {
2365
- path: exp._path,
2366
- source: exp.browser?.source || exp.source,
2367
- output
2368
- });
2369
- }
2370
- for (const exp of exports2) {
2371
- const output = exp.import;
2372
- output && addRollupTaskEntry("esm", ctx.runtime, {
2373
- path: exp._path,
2374
- source: exp.source,
2375
- output
2376
- });
2377
- }
2378
- for (const exp of exports2) {
2379
- const output = exp.browser?.import;
2380
- output && addRollupTaskEntry("esm", "browser", {
2381
- path: exp._path,
2382
- source: exp.browser?.source || exp.source,
2383
- output
2384
- });
2385
- }
2386
- return dtsTask2.entries.length && tasks.push(dtsTask2), tasks.push(...Object.values(rollupTasks)), tasks;
2387
- }
2388
- function globFiles(patterns) {
2389
- return globby__default.default(patterns.map((pattern) => pattern.split(path__default.default.sep).join(path__default.default.posix.sep)));
2390
- }
2391
- function watchFiles(patterns) {
2392
- return new rxjs.Observable((observer) => {
2393
- const watcher = chokidar__namespace.watch(patterns, {
2394
- ignoreInitial: !0
2395
- });
2396
- function handleFileEvent(type, file) {
2397
- type === "error" || file instanceof Error ? observer.error(file) : observer.next({ type, file });
2398
- }
2399
- return watcher.on("all", handleFileEvent), () => {
2400
- watcher.off("all", handleFileEvent), watcher.close();
2401
- };
2402
- });
2403
- }
2404
- async function watchConfigFiles(options) {
2405
- const { cwd, logger } = options, initialFiles = await globFiles([
2406
- path__default.default.resolve(cwd, "package.json"),
2407
- path__default.default.resolve(cwd, "package.config.cjs"),
2408
- path__default.default.resolve(cwd, "package.config.js"),
2409
- path__default.default.resolve(cwd, "package.config.ts")
2410
- ]);
2411
- return watchFiles([
2412
- path__default.default.resolve(cwd, "package.json"),
2413
- path__default.default.resolve(cwd, "package.config.cjs"),
2414
- path__default.default.resolve(cwd, "package.config.js"),
2415
- path__default.default.resolve(cwd, "package.config.ts")
2416
- ]).pipe(
2417
- 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(
2418
- "--------------------------------------------------------------------------------"
2419
- ), logger.info(path__default.default.relative(cwd, fileEvent.file), "changed"), logger.log(""), files.slice(0)) : files, initialFiles),
2420
- operators.startWith(initialFiles),
2421
- operators.distinctUntilChanged()
2422
- );
2423
- }
2424
- async function watch(options) {
2425
- const { cwd, strict = !1, tsconfig: tsconfigOption } = options, logger = createLogger();
2426
- (await watchConfigFiles({ cwd, logger })).pipe(
2427
- rxjs.switchMap(async (configFiles) => {
2428
- if (!configFiles.map((f) => path__default.default.relative(cwd, f)).find((f) => f === "package.json"))
2429
- throw new Error("missing package.json");
2430
- const config2 = await loadConfig({ cwd }), pkg = await loadPkgWithReporting({ cwd, logger, strict }), tsconfig = tsconfigOption || config2?.tsconfig || "tsconfig.json";
2431
- return resolveBuildContext({ config: config2, cwd, logger, pkg, strict, tsconfig });
2432
- })
2433
- ).subscribe(async (ctx) => {
2434
- const watchTasks = resolveWatchTasks(ctx);
2435
- for (const task of watchTasks) {
2436
- const handler = watchTaskHandlers[task.type];
2437
- handler.exec(ctx, task).subscribe({
2438
- error: (err) => {
2439
- ctx.logger.error(err), ctx.logger.log(), process.exit(1);
2440
- },
2441
- next: (result) => {
2442
- handler.complete(ctx, task, result);
2443
- },
2444
- complete: () => {
2445
- ctx.logger.success(handler.name(ctx, task)), ctx.logger.log();
2446
- }
2447
- });
2448
- }
2449
- });
2450
- }
2451
- exports.DEFAULT_BROWSERSLIST_QUERY = DEFAULT_BROWSERSLIST_QUERY;
2452
- exports.build = build;
2453
- exports.check = check;
2454
- exports.createLogger = createLogger;
2455
- exports.defineConfig = defineConfig;
2456
- exports.defineTemplateOption = defineTemplateOption;
2457
- exports.getExtractMessagesConfig = getExtractMessagesConfig;
2458
- exports.init = init;
2459
- exports.loadConfig = loadConfig;
2460
- exports.loadPkg = loadPkg;
2461
- exports.loadPkgWithReporting = loadPkgWithReporting;
2462
- exports.parseExports = parseExports;
2463
- exports.parseStrictOptions = parseStrictOptions;
2464
- exports.pkgExtMap = pkgExtMap;
2465
- exports.watch = watch;
2466
- //# sourceMappingURL=index.cjs.map