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