@sanity/pkg-utils 7.4.1-canary.0 → 7.5.1-canary.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.
Files changed (75) hide show
  1. package/dist/_chunks-cjs/index.cjs +2022 -260
  2. package/dist/_chunks-cjs/index.cjs.map +1 -1
  3. package/dist/_chunks-es/build.js +106 -17
  4. package/dist/_chunks-es/build.js.map +1 -1
  5. package/dist/_chunks-es/check.js +125 -37
  6. package/dist/_chunks-es/check.js.map +1 -1
  7. package/dist/_chunks-es/consoleSpy.js +541 -0
  8. package/dist/_chunks-es/consoleSpy.js.map +1 -0
  9. package/dist/_chunks-es/index.js +774 -180
  10. package/dist/_chunks-es/index.js.map +1 -1
  11. package/dist/_chunks-es/init.js +493 -9
  12. package/dist/_chunks-es/init.js.map +1 -1
  13. package/dist/_chunks-es/{logger.js → isRecord.js} +15 -2
  14. package/dist/_chunks-es/isRecord.js.map +1 -0
  15. package/dist/_chunks-es/resolveRolldownConfig.js +1 -1
  16. package/dist/_chunks-es/spinner.js +16 -0
  17. package/dist/_chunks-es/spinner.js.map +1 -0
  18. package/dist/_chunks-es/watch.js +115 -9
  19. package/dist/_chunks-es/watch.js.map +1 -1
  20. package/dist/cli.d.ts +1 -1
  21. package/dist/cli.js +1 -1
  22. package/dist/index.d.cts +421 -487
  23. package/dist/index.d.ts +421 -487
  24. package/dist/index.js +7 -4
  25. package/dist/index.js.map +1 -1
  26. package/package.json +3 -2
  27. package/dist/_chunks-cjs/findConfigFile.cjs +0 -24
  28. package/dist/_chunks-cjs/findConfigFile.cjs.map +0 -1
  29. package/dist/_chunks-cjs/index2.cjs +0 -781
  30. package/dist/_chunks-cjs/index2.cjs.map +0 -1
  31. package/dist/_chunks-cjs/index3.cjs +0 -50
  32. package/dist/_chunks-cjs/index3.cjs.map +0 -1
  33. package/dist/_chunks-cjs/printPackageTree.cjs +0 -42
  34. package/dist/_chunks-cjs/printPackageTree.cjs.map +0 -1
  35. package/dist/_chunks-cjs/resolveBuildContext.cjs +0 -176
  36. package/dist/_chunks-cjs/resolveBuildContext.cjs.map +0 -1
  37. package/dist/_chunks-cjs/resolveBuildTasks.cjs +0 -111
  38. package/dist/_chunks-cjs/resolveBuildTasks.cjs.map +0 -1
  39. package/dist/_chunks-cjs/resolveConfigProperty.cjs +0 -6
  40. package/dist/_chunks-cjs/resolveConfigProperty.cjs.map +0 -1
  41. package/dist/_chunks-cjs/resolveWatchTasks.cjs +0 -79
  42. package/dist/_chunks-cjs/resolveWatchTasks.cjs.map +0 -1
  43. package/dist/_chunks-cjs/template.cjs +0 -446
  44. package/dist/_chunks-cjs/template.cjs.map +0 -1
  45. package/dist/_chunks-cjs/validatePkg.cjs +0 -71
  46. package/dist/_chunks-cjs/validatePkg.cjs.map +0 -1
  47. package/dist/_chunks-cjs/watchConfigFiles.cjs +0 -59
  48. package/dist/_chunks-cjs/watchConfigFiles.cjs.map +0 -1
  49. package/dist/_chunks-es/fileExists.js +0 -12
  50. package/dist/_chunks-es/fileExists.js.map +0 -1
  51. package/dist/_chunks-es/findConfigFile.js +0 -23
  52. package/dist/_chunks-es/findConfigFile.js.map +0 -1
  53. package/dist/_chunks-es/index2.js +0 -769
  54. package/dist/_chunks-es/index2.js.map +0 -1
  55. package/dist/_chunks-es/index3.js +0 -51
  56. package/dist/_chunks-es/index3.js.map +0 -1
  57. package/dist/_chunks-es/loadPkgWithReporting.js +0 -100
  58. package/dist/_chunks-es/loadPkgWithReporting.js.map +0 -1
  59. package/dist/_chunks-es/logger.js.map +0 -1
  60. package/dist/_chunks-es/printPackageTree.js +0 -44
  61. package/dist/_chunks-es/printPackageTree.js.map +0 -1
  62. package/dist/_chunks-es/resolveBuildContext.js +0 -177
  63. package/dist/_chunks-es/resolveBuildContext.js.map +0 -1
  64. package/dist/_chunks-es/resolveBuildTasks.js +0 -109
  65. package/dist/_chunks-es/resolveBuildTasks.js.map +0 -1
  66. package/dist/_chunks-es/resolveConfigProperty.js +0 -7
  67. package/dist/_chunks-es/resolveConfigProperty.js.map +0 -1
  68. package/dist/_chunks-es/resolveWatchTasks.js +0 -77
  69. package/dist/_chunks-es/resolveWatchTasks.js.map +0 -1
  70. package/dist/_chunks-es/template.js +0 -449
  71. package/dist/_chunks-es/template.js.map +0 -1
  72. package/dist/_chunks-es/validatePkg.js +0 -72
  73. package/dist/_chunks-es/validatePkg.js.map +0 -1
  74. package/dist/_chunks-es/watchConfigFiles.js +0 -45
  75. package/dist/_chunks-es/watchConfigFiles.js.map +0 -1
@@ -0,0 +1,541 @@
1
+ import { createRequire } from "node:module";
2
+ import path, { resolve } from "node:path";
3
+ import { register } from "esbuild-register/dist/node";
4
+ import pkgUp from "pkg-up";
5
+ import findConfig from "find-config";
6
+ import { fileExists, isRecord } from "./isRecord.js";
7
+ import chalk from "chalk";
8
+ import { z, ZodError } from "zod";
9
+ import fs from "node:fs/promises";
10
+ import browserslist from "browserslist";
11
+ import config from "@sanity/browserslist-config";
12
+ import { existsSync } from "node:fs";
13
+ import ts from "typescript";
14
+ import { errorMap } from "zod-validation-error";
15
+ const CONFIG_FILE_NAMES = [
16
+ "package.config.ts",
17
+ "package.config.js",
18
+ "package.config.cjs",
19
+ "package.config.mjs"
20
+ ];
21
+ function findConfigFile(cwd) {
22
+ const pkgJsonPath = findConfig("package.json", { cwd });
23
+ if (!pkgJsonPath) return;
24
+ const pkgPath = path.dirname(pkgJsonPath);
25
+ for (const fileName of CONFIG_FILE_NAMES) {
26
+ const configPath = path.resolve(pkgPath, fileName);
27
+ if (fileExists(configPath))
28
+ return configPath;
29
+ }
30
+ }
31
+ const require2 = createRequire(import.meta.url);
32
+ async function loadConfig(options) {
33
+ const { cwd } = options, pkgPath = await pkgUp({ cwd });
34
+ if (!pkgPath) return;
35
+ const root = path.dirname(pkgPath), configFile = await findConfigFile(root);
36
+ if (!configFile || !configFile.startsWith(cwd))
37
+ return;
38
+ const esbuildOptions = { extensions: [".js", ".mjs", ".ts"] }, { unregister } = globalThis.__DEV__ ? { unregister: () => {
39
+ } } : register(esbuildOptions), mod = require2(configFile);
40
+ return unregister(), mod?.default || mod || void 0;
41
+ }
42
+ function assertLast(a, arr) {
43
+ const aIdx = arr.indexOf(a);
44
+ return aIdx === -1 ? !0 : aIdx === arr.length - 1;
45
+ }
46
+ function assertOrder(a, b, arr) {
47
+ const aIdx = arr.indexOf(a), bIdx = arr.indexOf(b);
48
+ return aIdx === -1 || bIdx === -1 ? !0 : aIdx < bIdx;
49
+ }
50
+ const pkgSchema = z.object({
51
+ type: z.optional(z.enum(["commonjs", "module"])),
52
+ name: z.string(),
53
+ version: z.string(),
54
+ license: z.string(),
55
+ bin: z.optional(z.record(z.string())),
56
+ dependencies: z.optional(z.record(z.string())),
57
+ devDependencies: z.optional(z.record(z.string())),
58
+ peerDependencies: z.optional(z.record(z.string())),
59
+ source: z.optional(z.string()),
60
+ main: z.optional(z.string()),
61
+ browser: z.optional(z.record(z.string())),
62
+ module: z.optional(z.string()),
63
+ types: z.optional(z.string()),
64
+ exports: z.optional(
65
+ z.record(
66
+ z.union([
67
+ z.custom((val) => /^\.\/.*\.json$/.test(val)),
68
+ z.custom((val) => /^\.\/.*\.css$/.test(val)),
69
+ z.object({
70
+ types: z.optional(z.string()),
71
+ source: z.optional(z.string()),
72
+ browser: z.optional(
73
+ z.object({
74
+ source: z.string(),
75
+ import: z.optional(z.string()),
76
+ require: z.optional(z.string())
77
+ })
78
+ ),
79
+ node: z.optional(
80
+ z.object({
81
+ source: z.optional(z.string()),
82
+ import: z.optional(z.string()),
83
+ require: z.optional(z.string())
84
+ })
85
+ ),
86
+ import: z.optional(z.string()),
87
+ require: z.optional(z.string()),
88
+ default: z.string()
89
+ }),
90
+ z.object({
91
+ types: z.optional(z.string()),
92
+ svelte: z.string(),
93
+ default: z.optional(z.string())
94
+ })
95
+ ])
96
+ )
97
+ ),
98
+ browserslist: z.optional(z.union([z.string(), z.array(z.string())])),
99
+ sideEffects: z.optional(z.union([z.boolean(), z.array(z.string())])),
100
+ // @TODO type this properly
101
+ typesVersions: z.optional(z.any())
102
+ }), typoMap = /* @__PURE__ */ new Map();
103
+ for (const key of pkgSchema.keyof()._def.values)
104
+ typoMap.set(key.toUpperCase(), key);
105
+ function validatePkg(input) {
106
+ const pkg = pkgSchema.parse(input), invalidKey = Object.keys(input).find((key) => {
107
+ const needle = key.toUpperCase();
108
+ return typoMap.has(needle) ? typoMap.get(needle) !== key : !1;
109
+ });
110
+ if (invalidKey)
111
+ throw new TypeError(
112
+ `
113
+ - package.json: "${invalidKey}" is not a valid key. Did you mean "${typoMap.get(invalidKey.toUpperCase())}"?`
114
+ );
115
+ return pkg;
116
+ }
117
+ async function loadPkg(options) {
118
+ const { cwd } = options, pkgPath = await pkgUp({ cwd });
119
+ if (!pkgPath) throw new Error("no package.json found");
120
+ const buf = await fs.readFile(pkgPath), raw = JSON.parse(buf.toString());
121
+ return validatePkg(raw), raw;
122
+ }
123
+ async function loadPkgWithReporting(options) {
124
+ const { cwd, logger, strict } = options;
125
+ try {
126
+ const pkg = await loadPkg({ cwd });
127
+ let shouldError = !1;
128
+ if (strict && (pkg.type || (shouldError = !0, logger.error(
129
+ 'the `type` field in `./package.json` must be either "module" or "commonjs")'
130
+ ))), pkg.exports) {
131
+ const _exports = Object.entries(pkg.exports);
132
+ for (const [expPath, exp] of _exports) {
133
+ if (typeof exp == "string" || "svelte" in exp)
134
+ continue;
135
+ const keys = Object.keys(exp);
136
+ exp.types && (shouldError = !0, logger.error(
137
+ `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`
138
+ )), exp.module && (shouldError = !0, logger.error(
139
+ `exports["${expPath}"]: the \`module\` condition shouldn't be used as it's not well supported in all bundlers.`
140
+ )), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0, logger.error(
141
+ `exports["${expPath}"]: the \`node\` property should come before the \`import\` property`
142
+ )), exp.node.module && (shouldError = !0, logger.error(
143
+ `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"`
144
+ )), !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(
145
+ `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"`
146
+ )), exp.require && exp.node.require && exp.require === exp.node.require ? (shouldError = !0, logger.error(
147
+ `exports["${expPath}"]: the \`node.require\` property isn't necessary as it's identical to \`require\``
148
+ )) : exp.require && exp.node.require && !assertOrder("node", "require", keys) && (shouldError = !0, logger.error(
149
+ `exports["${expPath}"]: the \`node\` property should come before the \`require\` property`
150
+ ))) : assertOrder("import", "require", keys) || logger.warn(
151
+ `exports["${expPath}"]: the \`import\` property should come before the \`require\` property`
152
+ ), assertLast("default", keys) || (shouldError = !0, logger.error(
153
+ `exports["${expPath}"]: the \`default\` property should be the last property`
154
+ ));
155
+ }
156
+ }
157
+ return shouldError && process.exit(1), pkg;
158
+ } catch (err) {
159
+ if (err instanceof ZodError)
160
+ for (const issue of err.issues) {
161
+ if (issue.code === "invalid_type") {
162
+ logger.error(
163
+ [
164
+ `\`${formatPath(issue.path)}\` `,
165
+ `in \`./package.json\` must be of type ${chalk.magenta(issue.expected)} `,
166
+ `(received ${chalk.magenta(issue.received)})`
167
+ ].join("")
168
+ );
169
+ continue;
170
+ }
171
+ logger.error(issue);
172
+ }
173
+ else
174
+ logger.error(err);
175
+ process.exit(1);
176
+ }
177
+ }
178
+ function formatPath(segments) {
179
+ return segments.map((s, idx) => idx === 0 ? s : typeof s == "number" ? `[${s}]` : s.startsWith(".") ? `["${s}"]` : `.${s}`).join("");
180
+ }
181
+ function browserslistToEsbuild(browserslistConfig, options = {}) {
182
+ if (!browserslistConfig) {
183
+ const path2 = process.cwd();
184
+ browserslistConfig = browserslist.loadConfig({ path: path2, ...options });
185
+ }
186
+ const SUPPORTED_ESBUILD_TARGETS = [
187
+ "es",
188
+ "chrome",
189
+ "edge",
190
+ "firefox",
191
+ "ios",
192
+ "node",
193
+ "safari",
194
+ "opera",
195
+ "ie"
196
+ ], UNSUPPORTED = ["android 4"], replaces = {
197
+ ios_saf: "ios",
198
+ android: "chrome"
199
+ }, separator = " ";
200
+ return browserslist(browserslistConfig, options).filter((b) => !UNSUPPORTED.some((u) => b.startsWith(u))).map((b) => b === "safari TP" ? browserslist("last 1 safari version")[0] : b).map((b) => b.split(separator)).map((b) => (replaces[b[0]] && (b[0] = replaces[b[0]]), b)).map((b) => (b[1].includes("-") && (b[1] = b[1].slice(0, b[1].indexOf("-"))), b)).map((b) => (b[1].endsWith(".0") && (b[1] = b[1].slice(0, -2)), b)).filter((b) => /^\d+(\.\d+)*$/.test(b[1])).filter((b) => SUPPORTED_ESBUILD_TARGETS.includes(b[0])).reduce((acc, b) => {
201
+ const existingIndex = acc.findIndex((br) => br[0] === b[0]);
202
+ return existingIndex !== -1 ? acc[existingIndex][1] = b[1] : acc.push(b), acc;
203
+ }, []).map((b) => b.join(""));
204
+ }
205
+ function resolveConfigProperty(prop, initialValue) {
206
+ return prop ? typeof prop == "function" ? prop(initialValue) : prop : initialValue;
207
+ }
208
+ const DEFAULT_BROWSERSLIST_QUERY = config;
209
+ function pathContains(containerPath, itemPath) {
210
+ return !path.relative(containerPath, itemPath).startsWith("..");
211
+ }
212
+ function findCommonDirPath(filePaths) {
213
+ let ret;
214
+ for (const filePath of filePaths) {
215
+ let dirPath = path.dirname(filePath);
216
+ if (!ret) {
217
+ ret = dirPath;
218
+ continue;
219
+ }
220
+ for (; dirPath !== ret && (dirPath = path.dirname(dirPath), dirPath !== ret); ) {
221
+ if (pathContains(dirPath, ret)) {
222
+ ret = dirPath;
223
+ break;
224
+ }
225
+ if (dirPath === ".") return;
226
+ }
227
+ }
228
+ return ret;
229
+ }
230
+ const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", defaultEnding = ".js", mjsEnding = ".mjs", cjsEnding = ".cjs", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
231
+ function getTargetPaths(_type, expOrBundle) {
232
+ const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
233
+ 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(
234
+ expOrBundle.browser.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
235
+ ), expOrBundle.browser?.require && set.add(
236
+ expOrBundle.browser.require.replace(
237
+ fileEnding,
238
+ type === "commonjs" ? dtsEnding : ctsEnding
239
+ )
240
+ )), expOrBundle.node?.source || (expOrBundle.node?.import && set.add(
241
+ expOrBundle.node.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
242
+ ), expOrBundle.node?.require && set.add(
243
+ expOrBundle.node.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)
244
+ ))), Array.from(set);
245
+ }
246
+ function isPkgExport$1(exp) {
247
+ return exp?.browser || exp?.node || exp?.default;
248
+ }
249
+ const pkgExtMap = {
250
+ // pkg.type: "commonjs"
251
+ commonjs: {
252
+ commonjs: defaultEnding,
253
+ esm: mjsEnding
254
+ },
255
+ // pkg.type: "module"
256
+ module: {
257
+ commonjs: cjsEnding,
258
+ esm: defaultEnding
259
+ }
260
+ };
261
+ function validateExports(_exports, options) {
262
+ const { pkg } = options, type = pkg.type || "commonjs", ext = pkgExtMap[type], errors = [];
263
+ for (const exp of _exports)
264
+ exp.require && !exp.require.endsWith(ext.commonjs) && errors.push(
265
+ `package.json with \`type: "${type}"\` - \`exports["${exp._path}"].require\` must end with "${ext.commonjs}"`
266
+ ), exp.import && !exp.import.endsWith(ext.esm) && errors.push(
267
+ `package.json with \`type: "${type}"\` - \`exports["${exp._path}"].import\` must end with "${ext.esm}"`
268
+ );
269
+ return errors;
270
+ }
271
+ function parseExports(options) {
272
+ const { cwd, pkg, strict, strictOptions: strictOptions2, logger } = options, type = pkg.type || "commonjs", errors = [], report = (kind, message) => {
273
+ kind === "warn" ? logger.warn(message) : errors.push(message);
274
+ };
275
+ 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(
276
+ strictOptions2.alwaysPackageJsonFiles,
277
+ "package.json: `files` should be used over `.npmignore`"
278
+ ), pkg.source) {
279
+ if (strict && pkg.exports?.["."] && typeof pkg.exports["."] == "object" && "source" in pkg.exports["."] && pkg.exports["."].source === pkg.source)
280
+ errors.push(
281
+ 'package.json: the "source" property can be removed, as it is equal to exports["."].source.'
282
+ );
283
+ else if (!pkg.exports && pkg.main) {
284
+ 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 = [];
285
+ if (pkg.browser) {
286
+ const browserConditions = [];
287
+ pkg.module && pkg.browser?.[pkg.module] ? browserConditions.push(
288
+ ` "import": ${JSON.stringify(pkg.browser[pkg.module].replace(fileEnding, extMap.esm))}`
289
+ ) : pkg.browser?.[pkg.main] && browserConditions.push(
290
+ ` "import": ${JSON.stringify(pkg.browser?.[pkg.main].replace(fileEnding, extMap.esm))}`
291
+ ), pkg.browser?.[pkg.main] && browserConditions.push(
292
+ ` "require": ${JSON.stringify(pkg.browser[pkg.main].replace(fileEnding, extMap.commonjs))}`
293
+ ), browserConditions.length && maybeBrowserCondition.push(
294
+ ' "browser": {',
295
+ ` "source": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,
296
+ ...browserConditions,
297
+ " }"
298
+ );
299
+ }
300
+ errors.push(
301
+ ...[
302
+ "package.json: `exports` are missing, it should be:",
303
+ '"exports": {',
304
+ ' ".": {',
305
+ ` "source": ${JSON.stringify(pkg.source)},`,
306
+ // If browser conditions are detected then add them to the suggestion
307
+ ...maybeBrowserCondition.length > 0 ? maybeBrowserCondition : [],
308
+ type === "commonjs" && ` "import": ${JSON.stringify(importExport)},`,
309
+ type === "module" && ` "require": ${JSON.stringify(requireExport)},`,
310
+ ` "default": ${JSON.stringify(defaultExport)}`,
311
+ " },",
312
+ ' "./package.json": "./package.json"',
313
+ "}"
314
+ ].filter(Boolean)
315
+ );
316
+ }
317
+ }
318
+ if (errors.length)
319
+ throw new Error(`
320
+ - ` + errors.join(`
321
+ - `));
322
+ if (!pkg.exports)
323
+ throw new Error(
324
+ `
325
+ - ` + [
326
+ "package.json: `exports` are missing, please set a minimal configuration, for example:",
327
+ '"exports": {',
328
+ ' ".": {',
329
+ ' "source": "./src/index.js",',
330
+ ' "default": "./dist/index.js"',
331
+ " },",
332
+ ' "./package.json": "./package.json"',
333
+ "}"
334
+ ].join(`
335
+ - `)
336
+ );
337
+ const _exports = [];
338
+ 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(
339
+ strictOptions2.alwaysPackageJsonTypes,
340
+ "package.json: `types` must be declared for the npm listing to show as a TypeScript module."
341
+ ), strict && !pkg.exports["./package.json"] && errors.push('package.json: `exports["./package.json"] must be declared.');
342
+ for (const [exportPath, exportEntry] of Object.entries(pkg.exports))
343
+ if (exportPath.endsWith(".json") || typeof exportEntry == "string" && exportEntry.endsWith(".json"))
344
+ exportPath === "./package.json" && exportEntry !== "./package.json" && errors.push('package.json: `exports["./package.json"]` must be "./package.json".');
345
+ else if (exportPath.endsWith(".css"))
346
+ typeof exportEntry == "string" && !existsSync(resolve(cwd, exportEntry)) ? errors.push(
347
+ `package.json: \`exports[${JSON.stringify(exportPath)}]\`: file does not exist.`
348
+ ) : typeof exportEntry != "string" && errors.push(
349
+ `package.json: \`exports[${JSON.stringify(exportPath)}]\`: export conditions not supported for CSS files.`
350
+ );
351
+ else if (!(isRecord(exportEntry) && "svelte" in exportEntry))
352
+ if (isPkgExport(exportEntry)) {
353
+ const exp = {
354
+ _exported: !0,
355
+ _path: exportPath,
356
+ ...exportEntry
357
+ };
358
+ if (!exp.default) {
359
+ const fallback = type === "module" ? exp.import : exp.require;
360
+ fallback && (exp.default = fallback);
361
+ }
362
+ !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(
363
+ 'package.json: mismatch between "main" and "exports.require". These must be equal.'
364
+ ), exportEntry.import && pkg.module && exportEntry.import !== pkg.module && errors.push(
365
+ 'package.json: mismatch between "module" and "exports.import" These must be equal.'
366
+ )), _exports.push(exp);
367
+ } else isRecord(exportEntry) || errors.push("package.json: exports must be an object");
368
+ if (errors.push(...validateExports(_exports, { pkg })), errors.length)
369
+ throw new Error(`
370
+ - ` + errors.join(`
371
+ - `));
372
+ return _exports;
373
+ }
374
+ function isPkgExport(value) {
375
+ return isRecord(value) && "source" in value && typeof value.source == "string";
376
+ }
377
+ async function loadTSConfig(options) {
378
+ const { cwd, tsconfigPath } = options, configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
379
+ if (!configPath)
380
+ return;
381
+ const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
382
+ return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
383
+ }
384
+ function resolveBrowserTarget(versions) {
385
+ const target = versions.filter(
386
+ (version) => version.startsWith("chrome") || version.startsWith("edge") || version.startsWith("firefox") || version.startsWith("ios") || version.startsWith("safari") || version.startsWith("opera")
387
+ );
388
+ if (target.length !== 0)
389
+ return target;
390
+ }
391
+ function resolveNodeTarget(versions) {
392
+ const target = versions.filter((version) => version.startsWith("node"));
393
+ if (target.length !== 0)
394
+ return target;
395
+ }
396
+ const toggle = z.union([z.literal("error"), z.literal("warn"), z.literal("off")]), strictOptions = z.object({
397
+ noPackageJsonTypings: toggle.default("error"),
398
+ noImplicitSideEffects: toggle.default("warn"),
399
+ noImplicitBrowsersList: toggle.default("warn"),
400
+ alwaysPackageJsonTypes: toggle.default("error"),
401
+ alwaysPackageJsonMain: toggle.default("error"),
402
+ alwaysPackageJsonFiles: toggle.default("error")
403
+ }).strict(), validationSchema = z.object({
404
+ strictOptions: strictOptions.default({})
405
+ });
406
+ function parseStrictOptions(input) {
407
+ return validationSchema.parse({ strictOptions: input }, { errorMap }).strictOptions;
408
+ }
409
+ async function resolveBuildContext(options) {
410
+ const {
411
+ config: config2,
412
+ cwd,
413
+ emitDeclarationOnly = !1,
414
+ logger,
415
+ pkg,
416
+ strict,
417
+ tsconfig: tsconfigPath
418
+ } = options, tsconfig = await loadTSConfig({ cwd, tsconfigPath }), strictOptions2 = parseStrictOptions(config2?.strictOptions ?? {});
419
+ let browserslist2 = pkg.browserslist;
420
+ if (!browserslist2) {
421
+ if (strict && strictOptions2.noImplicitBrowsersList !== "off") {
422
+ if (strictOptions2.noImplicitBrowsersList === "error")
423
+ throw new Error(
424
+ '\n- package.json: "browserslist" is missing, set it to `"browserslist": "extends @sanity/browserslist-config"`'
425
+ );
426
+ logger.warn(
427
+ 'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `"browserslist": "extends @sanity/browserslist-config"` to silence this warning.'
428
+ );
429
+ }
430
+ browserslist2 = DEFAULT_BROWSERSLIST_QUERY;
431
+ }
432
+ const targetVersions = browserslistToEsbuild(browserslist2);
433
+ if (strict && strictOptions2.noImplicitSideEffects !== "off" && typeof pkg.sideEffects > "u") {
434
+ 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`";
435
+ if (strictOptions2.noImplicitSideEffects === "error")
436
+ throw new Error(msg);
437
+ logger.warn(msg);
438
+ }
439
+ const nodeTarget = resolveNodeTarget(targetVersions), webTarget = resolveBrowserTarget(targetVersions);
440
+ if (!nodeTarget)
441
+ throw new Error("no matching `node` target");
442
+ if (!webTarget)
443
+ throw new Error("no matching `web` target");
444
+ const target = {
445
+ "*": webTarget.concat(nodeTarget),
446
+ browser: webTarget,
447
+ node: nodeTarget
448
+ }, parsedExports = parseExports({
449
+ cwd,
450
+ pkg,
451
+ strict,
452
+ strictOptions: strictOptions2,
453
+ logger
454
+ }).reduce(
455
+ (acc, { _path: exportPath, ...exportEntry }) => Object.assign(acc, { [exportPath]: exportEntry }),
456
+ {}
457
+ ), exports = resolveConfigProperty(config2?.exports, parsedExports), parsedExternal = [
458
+ ...pkg.dependencies ? Object.keys(pkg.dependencies) : [],
459
+ ...pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []
460
+ ], 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(
461
+ // Do not bundle anything that is marked as external
462
+ (_) => !externalWithTypes.has(_)
463
+ ), bundledPackages = config2 && Array.isArray(config2.extract?.bundledPackages) ? [...bundledDependencies, ...config2.extract.bundledPackages] : resolveConfigProperty(config2?.extract?.bundledPackages, bundledDependencies), outputPaths = Object.values(exports).flatMap((exportEntry) => [
464
+ exportEntry.import,
465
+ exportEntry.require,
466
+ exportEntry.browser?.import,
467
+ exportEntry.browser?.require,
468
+ exportEntry.node?.source && exportEntry.node.import,
469
+ exportEntry.node?.source && exportEntry.node.require
470
+ ].filter(Boolean)).map((p) => path.resolve(cwd, p)), commonDistPath = findCommonDirPath(outputPaths);
471
+ if (commonDistPath === cwd)
472
+ throw new Error(
473
+ "all output files must share a common parent directory which is not the root package directory"
474
+ );
475
+ if (commonDistPath && !pathContains(cwd, commonDistPath))
476
+ throw new Error("all output files must be located within the package");
477
+ const configDistPath = config2?.dist ? path.resolve(cwd, config2.dist) : void 0;
478
+ if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath))
479
+ throw logger.log(`did you mean to configure \`dist: './${path.relative(cwd, commonDistPath)}'\`?`), new Error("all output files must be located with the configured `dist` path");
480
+ const distPath = configDistPath || commonDistPath;
481
+ if (!distPath)
482
+ throw new Error("could not detect `dist` path");
483
+ return {
484
+ config: config2,
485
+ cwd,
486
+ distPath,
487
+ emitDeclarationOnly,
488
+ exports,
489
+ external,
490
+ bundledPackages,
491
+ files: [],
492
+ logger,
493
+ pkg,
494
+ runtime: config2?.runtime ?? "*",
495
+ strict,
496
+ target,
497
+ ts: {
498
+ config: tsconfig,
499
+ configPath: tsconfigPath
500
+ },
501
+ dts: config2?.dts === "rolldown" ? "rolldown" : "api-extractor"
502
+ };
503
+ }
504
+ function transformPackageName(packageName) {
505
+ if (packageName.startsWith("@types/"))
506
+ return packageName;
507
+ if (packageName.startsWith("@")) {
508
+ const [scope, name] = packageName.split("/");
509
+ return `@types/${scope.slice(1)}__${name}`;
510
+ } else
511
+ return `@types/${packageName}`;
512
+ }
513
+ function createConsoleSpy(options) {
514
+ const { onRestored } = options || {}, original = {
515
+ log: console.log,
516
+ warn: console.warn,
517
+ error: console.error
518
+ }, messages = [];
519
+ 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 }), {
520
+ messages,
521
+ restore: () => {
522
+ console.log = original.log, console.warn = original.warn, console.error = original.error, onRestored?.(messages);
523
+ }
524
+ };
525
+ }
526
+ export {
527
+ DEFAULT_BROWSERSLIST_QUERY,
528
+ createConsoleSpy,
529
+ getTargetPaths,
530
+ loadConfig,
531
+ loadPkg,
532
+ loadPkgWithReporting,
533
+ parseExports,
534
+ parseStrictOptions,
535
+ pkgExtMap,
536
+ resolveBuildContext,
537
+ resolveConfigProperty,
538
+ strictOptions,
539
+ toggle
540
+ };
541
+ //# sourceMappingURL=consoleSpy.js.map