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