@sanity/pkg-utils 7.4.0-canary.2 → 7.4.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 (70) hide show
  1. package/dist/_chunks-cjs/findConfigFile.cjs +24 -0
  2. package/dist/_chunks-cjs/findConfigFile.cjs.map +1 -0
  3. package/dist/_chunks-cjs/index.cjs +231 -1910
  4. package/dist/_chunks-cjs/index.cjs.map +1 -1
  5. package/dist/_chunks-cjs/index2.cjs +781 -0
  6. package/dist/_chunks-cjs/index2.cjs.map +1 -0
  7. package/dist/_chunks-cjs/index3.cjs +50 -0
  8. package/dist/_chunks-cjs/index3.cjs.map +1 -0
  9. package/dist/_chunks-cjs/printPackageTree.cjs +42 -0
  10. package/dist/_chunks-cjs/printPackageTree.cjs.map +1 -0
  11. package/dist/_chunks-cjs/resolveBuildContext.cjs +176 -0
  12. package/dist/_chunks-cjs/resolveBuildContext.cjs.map +1 -0
  13. package/dist/_chunks-cjs/resolveBuildTasks.cjs +111 -0
  14. package/dist/_chunks-cjs/resolveBuildTasks.cjs.map +1 -0
  15. package/dist/_chunks-cjs/resolveConfigProperty.cjs +6 -0
  16. package/dist/_chunks-cjs/resolveConfigProperty.cjs.map +1 -0
  17. package/dist/_chunks-cjs/resolveWatchTasks.cjs +79 -0
  18. package/dist/_chunks-cjs/resolveWatchTasks.cjs.map +1 -0
  19. package/dist/_chunks-cjs/template.cjs +446 -0
  20. package/dist/_chunks-cjs/template.cjs.map +1 -0
  21. package/dist/_chunks-cjs/validatePkg.cjs +71 -0
  22. package/dist/_chunks-cjs/validatePkg.cjs.map +1 -0
  23. package/dist/_chunks-cjs/watchConfigFiles.cjs +59 -0
  24. package/dist/_chunks-cjs/watchConfigFiles.cjs.map +1 -0
  25. package/dist/_chunks-es/build.js +7 -107
  26. package/dist/_chunks-es/build.js.map +1 -1
  27. package/dist/_chunks-es/check.js +23 -44
  28. package/dist/_chunks-es/check.js.map +1 -1
  29. package/dist/_chunks-es/fileExists.js +12 -0
  30. package/dist/_chunks-es/fileExists.js.map +1 -0
  31. package/dist/_chunks-es/findConfigFile.js +23 -0
  32. package/dist/_chunks-es/findConfigFile.js.map +1 -0
  33. package/dist/_chunks-es/index.js +180 -754
  34. package/dist/_chunks-es/index.js.map +1 -1
  35. package/dist/_chunks-es/index2.js +769 -0
  36. package/dist/_chunks-es/index2.js.map +1 -0
  37. package/dist/_chunks-es/index3.js +51 -0
  38. package/dist/_chunks-es/index3.js.map +1 -0
  39. package/dist/_chunks-es/init.js +9 -493
  40. package/dist/_chunks-es/init.js.map +1 -1
  41. package/dist/_chunks-es/loadPkgWithReporting.js +100 -0
  42. package/dist/_chunks-es/loadPkgWithReporting.js.map +1 -0
  43. package/dist/_chunks-es/{isRecord.js → logger.js} +2 -15
  44. package/dist/_chunks-es/logger.js.map +1 -0
  45. package/dist/_chunks-es/printPackageTree.js +44 -0
  46. package/dist/_chunks-es/printPackageTree.js.map +1 -0
  47. package/dist/_chunks-es/resolveBuildContext.js +177 -0
  48. package/dist/_chunks-es/resolveBuildContext.js.map +1 -0
  49. package/dist/_chunks-es/resolveBuildTasks.js +109 -0
  50. package/dist/_chunks-es/resolveBuildTasks.js.map +1 -0
  51. package/dist/_chunks-es/resolveConfigProperty.js +7 -0
  52. package/dist/_chunks-es/resolveConfigProperty.js.map +1 -0
  53. package/dist/_chunks-es/resolveRolldownConfig.js +1 -1
  54. package/dist/_chunks-es/resolveWatchTasks.js +77 -0
  55. package/dist/_chunks-es/resolveWatchTasks.js.map +1 -0
  56. package/dist/_chunks-es/template.js +449 -0
  57. package/dist/_chunks-es/template.js.map +1 -0
  58. package/dist/_chunks-es/validatePkg.js +72 -0
  59. package/dist/_chunks-es/validatePkg.js.map +1 -0
  60. package/dist/_chunks-es/watch.js +9 -115
  61. package/dist/_chunks-es/watch.js.map +1 -1
  62. package/dist/_chunks-es/watchConfigFiles.js +45 -0
  63. package/dist/_chunks-es/watchConfigFiles.js.map +1 -0
  64. package/dist/cli.js +1 -1
  65. package/dist/index.js +4 -7
  66. package/dist/index.js.map +1 -1
  67. package/package.json +2 -2
  68. package/dist/_chunks-es/consoleSpy.js +0 -541
  69. package/dist/_chunks-es/consoleSpy.js.map +0 -1
  70. package/dist/_chunks-es/isRecord.js.map +0 -1
@@ -0,0 +1,769 @@
1
+ import chalk from "chalk";
2
+ import { Observable, from } from "rxjs";
3
+ import path from "node:path";
4
+ import * as rimraf from "rimraf";
5
+ import { rimraf as rimraf$1 } from "rimraf";
6
+ import ts from "typescript";
7
+ import fs, { readFile } from "node:fs/promises";
8
+ import { ExtractorConfig, Extractor } from "@microsoft/api-extractor";
9
+ import { mkdirp } from "mkdirp";
10
+ import * as prettier from "prettier";
11
+ import { createRequire } from "node:module";
12
+ import { TSDocConfigFile } from "@microsoft/tsdoc-config";
13
+ import { parse } from "jsonc-parser";
14
+ import { parse as parse$1, print } from "recast";
15
+ import typeScriptParser from "recast/parsers/typescript.js";
16
+ import { getExtractMessagesConfig, pkgExtMap } from "./index.js";
17
+ import { createConsoleSpy } from "./check.js";
18
+ import { rollup, watch } from "rollup";
19
+ import { optimizeLodashImports } from "@optimize-lodash/rollup-plugin";
20
+ import alias from "@rollup/plugin-alias";
21
+ import { babel, getBabelOutputPlugin } from "@rollup/plugin-babel";
22
+ import commonjs from "@rollup/plugin-commonjs";
23
+ import json from "@rollup/plugin-json";
24
+ import { nodeResolve } from "@rollup/plugin-node-resolve";
25
+ import replace from "@rollup/plugin-replace";
26
+ import terser from "@rollup/plugin-terser";
27
+ import esbuild from "rollup-plugin-esbuild";
28
+ import { resolveConfigProperty } from "./resolveConfigProperty.js";
29
+ function printExtractMessages(ctx, messages) {
30
+ const { cwd, logger } = ctx, warnings = messages.filter((msg) => msg.logLevel === "warning");
31
+ warnings.length && logger.log();
32
+ for (const msg of warnings) {
33
+ const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
34
+ msg.messageId !== "TS6307" && logger.log(
35
+ [
36
+ `${chalk.cyan(sourceFilePath || "?")}`,
37
+ `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,
38
+ ` - ${chalk.yellow("warning")} ${chalk.gray(msg.messageId)}
39
+ `,
40
+ msg.text,
41
+ `
42
+ `
43
+ ].join("")
44
+ );
45
+ }
46
+ const errors = messages.filter((msg) => msg.logLevel === "error");
47
+ !warnings.length && errors.length && logger.log("");
48
+ for (const msg of errors) {
49
+ const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
50
+ logger.log(
51
+ [
52
+ `${chalk.cyan(sourceFilePath || "?")}`,
53
+ `:${chalk.yellow(msg.sourceFileLine)}:${chalk.yellow(msg.sourceFileColumn)}`,
54
+ ` - ${chalk.red("error")} ${chalk.gray(msg.messageId)}
55
+ `,
56
+ msg.text,
57
+ `
58
+ `
59
+ ].join("")
60
+ );
61
+ }
62
+ errors.length && process.exit(1);
63
+ }
64
+ function printDiagnostic(options) {
65
+ const { cwd, logger, diagnostic } = options;
66
+ if (diagnostic.file && diagnostic.start) {
67
+ const { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), message = ts.flattenDiagnosticMessageText(diagnostic.messageText, `
68
+ `), file = path.relative(cwd, diagnostic.file.fileName), output = [
69
+ `${chalk.yellow(file)}:${chalk.blue(line + 1)}:${chalk.blue(character + 1)} - `,
70
+ `${chalk.gray(`TS${diagnostic.code}:`)} ${message}`
71
+ ].join("");
72
+ diagnostic.category === ts.DiagnosticCategory.Error && logger.error(output), diagnostic.category === ts.DiagnosticCategory.Warning && logger.warn(output), diagnostic.category === ts.DiagnosticCategory.Message && logger.log(output), diagnostic.category === ts.DiagnosticCategory.Suggestion && logger.log(output);
73
+ } else
74
+ logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
75
+ `));
76
+ }
77
+ async function buildTypes(options) {
78
+ const { cwd, logger, outDir, tsconfig, strict = !1 } = options, compilerOptions = {
79
+ ...tsconfig.options,
80
+ declaration: !0,
81
+ declarationDir: outDir,
82
+ emitDeclarationOnly: !0,
83
+ noEmit: !1,
84
+ noEmitOnError: strict ? !0 : tsconfig.options.noEmitOnError ?? !0,
85
+ outDir
86
+ }, program = ts.createProgram(tsconfig.fileNames, compilerOptions), emitResult = program.emit(), allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
87
+ for (const diagnostic of allDiagnostics)
88
+ printDiagnostic({ cwd, logger, diagnostic });
89
+ if (emitResult.emitSkipped && allDiagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error).length)
90
+ throw new Error("failed to compile TypeScript definitions");
91
+ }
92
+ class DtsError extends Error {
93
+ messages;
94
+ constructor(message, messages) {
95
+ super(message), this.messages = messages;
96
+ }
97
+ }
98
+ function createApiExtractorConfig(options) {
99
+ const {
100
+ bundledPackages,
101
+ distPath,
102
+ exportPath,
103
+ filePath,
104
+ messages,
105
+ projectFolder,
106
+ mainEntryPointFilePath,
107
+ tsconfig,
108
+ tsconfigPath,
109
+ dtsRollupEnabled
110
+ } = options;
111
+ return {
112
+ apiReport: {
113
+ enabled: !1,
114
+ reportFileName: "<unscopedPackageName>.api.md"
115
+ },
116
+ bundledPackages,
117
+ // 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`),
118
+ compiler: tsconfig.options.paths ? {
119
+ overrideTsconfig: {
120
+ extends: tsconfigPath,
121
+ compilerOptions: {
122
+ // An empty object replaces whatever is in the original tsconfig file
123
+ paths: {}
124
+ }
125
+ }
126
+ } : { tsconfigFilePath: tsconfigPath },
127
+ docModel: {
128
+ enabled: !1,
129
+ apiJsonFilePath: path.resolve(distPath, `${exportPath}.api.json`)
130
+ },
131
+ dtsRollup: {
132
+ enabled: dtsRollupEnabled,
133
+ untrimmedFilePath: path.resolve(distPath, filePath)
134
+ // betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
135
+ // publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
136
+ },
137
+ tsdocMetadata: {
138
+ enabled: !1
139
+ },
140
+ messages,
141
+ mainEntryPointFilePath,
142
+ projectFolder
143
+ };
144
+ }
145
+ const require2 = createRequire(import.meta.url);
146
+ async function createTSDocConfig(opts) {
147
+ const { customTags } = opts;
148
+ if (customTags.length === 0)
149
+ return;
150
+ const tsDocBaseBuf = await readFile(
151
+ require2.resolve("@microsoft/api-extractor/extends/tsdoc-base.json")
152
+ ), tsDocBaseConfig = parse(tsDocBaseBuf.toString()), tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(
153
+ customTags.map((t) => ({
154
+ tagName: `@${t.name}`,
155
+ syntaxKind: t.syntaxKind,
156
+ allowMultiple: t.allowMultiple
157
+ }))
158
+ ), supportForTags = { ...tsDocBaseConfig.supportForTags };
159
+ for (const customTag of customTags)
160
+ supportForTags[`@${customTag.name}`] = !0;
161
+ return TSDocConfigFile.loadFromObject({
162
+ ...tsDocBaseConfig,
163
+ noStandardTags: !1,
164
+ tagDefinitions,
165
+ supportForTags
166
+ });
167
+ }
168
+ async function extractModuleBlocksFromTypes({
169
+ tsOutDir,
170
+ extractResult
171
+ }) {
172
+ const program = extractResult.compilerState.program, moduleBlocks = [], sourceFiles = [...program.getSourceFiles()].filter((sourceFile) => sourceFile.fileName.includes(tsOutDir));
173
+ for (const sourceFile of sourceFiles)
174
+ sourceFile.text.includes("declare module") && moduleBlocks.push(...extractModuleBlocks(sourceFile.text));
175
+ return moduleBlocks;
176
+ }
177
+ function extractModuleBlocks(fileContent) {
178
+ return parse$1(fileContent, {
179
+ parser: typeScriptParser
180
+ }).program.body.filter((node) => node.type === "TSModuleDeclaration").map((node) => print(node).code);
181
+ }
182
+ async function extractTypes(options) {
183
+ const {
184
+ bundledPackages,
185
+ customTags,
186
+ distPath,
187
+ exportPath,
188
+ files,
189
+ filePaths,
190
+ projectPath,
191
+ rules,
192
+ sourceTypesPath,
193
+ tmpPath,
194
+ tsconfig,
195
+ tsconfigPath,
196
+ extractorDisabled
197
+ } = options, tsdocConfigFile = await createTSDocConfig({
198
+ customTags: customTags || []
199
+ }), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = ExtractorConfig.prepare({
200
+ configObject: createApiExtractorConfig({
201
+ bundledPackages,
202
+ distPath,
203
+ exportPath,
204
+ filePath,
205
+ messages: getExtractMessagesConfig({ rules, disabled: extractorDisabled }),
206
+ projectFolder: projectPath,
207
+ mainEntryPointFilePath: sourceTypesPath,
208
+ tsconfig,
209
+ tsconfigPath,
210
+ dtsRollupEnabled: !0
211
+ }),
212
+ configObjectFullPath: void 0,
213
+ tsdocConfigFile,
214
+ packageJsonFullPath: path.resolve(projectPath, "package.json")
215
+ }), messages = [], extractorResult = Extractor.invoke(extractorConfig, {
216
+ // Equivalent to the "--local" command-line parameter
217
+ localBuild: !0,
218
+ // Equivalent to the "--verbose" command-line parameter
219
+ showVerboseMessages: !0,
220
+ // handle messages
221
+ messageCallback(message) {
222
+ messages.push(message), message.handled = !0;
223
+ }
224
+ }), typesPath = path.resolve(distPath, filePath), typesBuf = await fs.readFile(typesPath), prettierConfig = await prettier.resolveConfig(typesPath);
225
+ await mkdirp(path.dirname(typesPath));
226
+ const moduleBlocks = await extractModuleBlocksFromTypes({
227
+ extractResult: extractorResult,
228
+ tsOutDir: tmpPath
229
+ }), code = [typesBuf.toString(), ...moduleBlocks].join(`
230
+
231
+ `), prettyCode = await prettier.format(code, {
232
+ ...prettierConfig,
233
+ filepath: typesPath
234
+ });
235
+ for (const expFilePath of filePaths) {
236
+ const expTypesPath = path.resolve(distPath, expFilePath);
237
+ await fs.writeFile(expTypesPath, prettyCode), files.push({
238
+ type: "types",
239
+ path: expTypesPath
240
+ });
241
+ }
242
+ return shouldCleanUpDts && await fs.unlink(typesPath), { extractorResult, messages };
243
+ }
244
+ async function doExtract(ctx, task) {
245
+ const { config, cwd, files, logger, strict, ts: ts2, bundledPackages } = ctx;
246
+ if (!ts2.config || !ts2.configPath)
247
+ return { type: "dts", messages: [], results: [] };
248
+ const { outDir, rootDir = cwd } = ts2.config.options;
249
+ if (!outDir)
250
+ throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
251
+ const tmpPath = path.resolve(outDir, "__tmp__");
252
+ await buildTypes({ cwd, logger, outDir: tmpPath, strict, tsconfig: ts2.config });
253
+ const messages = [], results = [];
254
+ for (const entry of task.entries) {
255
+ const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path.resolve(
256
+ tmpPath,
257
+ path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
258
+ ), targetPaths = entry.targetPaths.map((targetPath) => path.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path.relative(outDir, targetPath)), result = await extractTypes({
259
+ bundledPackages: bundledPackages || [],
260
+ customTags: config?.extract?.customTags,
261
+ distPath: outDir,
262
+ exportPath,
263
+ files,
264
+ filePaths,
265
+ projectPath: cwd,
266
+ rules: config?.extract?.rules,
267
+ sourceTypesPath,
268
+ tsconfig: ts2.config,
269
+ tmpPath,
270
+ tsconfigPath: path.resolve(cwd, ts2.configPath || "tsconfig.json"),
271
+ extractorDisabled: config?.extract?.enabled === !1
272
+ });
273
+ messages.push(...result.messages);
274
+ const errors = result.messages.filter((msg) => msg.logLevel === "error");
275
+ if (errors.length > 0)
276
+ throw await rimraf$1(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
277
+ results.push({ sourcePath: path.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
278
+ }
279
+ return await rimraf$1(tmpPath), { type: "dts", messages, results };
280
+ }
281
+ const dtsTask = {
282
+ name: (ctx, task) => [
283
+ `Build type definitions with ${chalk.bold(ctx.dts)}...`,
284
+ " entries:",
285
+ ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
286
+ ` - ${chalk.cyan(entry.importId)}: `,
287
+ `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
288
+ ].join("")).join(`
289
+ `))
290
+ ].join(`
291
+ `),
292
+ exec: (ctx, task) => new Observable((observer) => {
293
+ doExtract(ctx, task).then((result) => {
294
+ observer.next(result), observer.complete();
295
+ }).catch((err) => {
296
+ observer.error(err);
297
+ });
298
+ }),
299
+ complete: (ctx, _task, result) => {
300
+ printExtractMessages(ctx, result.messages);
301
+ },
302
+ error: (ctx, _task, err) => {
303
+ const { logger } = ctx;
304
+ err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
305
+ }
306
+ }, dtsWatchTask = {
307
+ name: (_ctx, task) => [
308
+ "build type definitions",
309
+ ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
310
+ ` - ${chalk.cyan(entry.importId)}: `,
311
+ `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
312
+ ].join("")))
313
+ ].join(`
314
+ `),
315
+ exec: (ctx, task) => {
316
+ const { config, cwd, files, logger, strict, ts: tsContext, bundledPackages } = ctx;
317
+ return new Observable((observer) => {
318
+ if (!tsContext.config || !tsContext.configPath) {
319
+ observer.next({ type: "dts", messages: [], results: [] }), observer.complete();
320
+ return;
321
+ }
322
+ const { outDir, rootDir = cwd } = tsContext.config.options;
323
+ if (!outDir) {
324
+ observer.error(new Error("tsconfig.json is missing `compilerOptions.outDir`"));
325
+ return;
326
+ }
327
+ const tmpPath = path.resolve(outDir, "__tmp__");
328
+ buildTypes({
329
+ cwd,
330
+ logger,
331
+ outDir: tmpPath,
332
+ tsconfig: tsContext.config,
333
+ strict
334
+ }).catch((err) => {
335
+ observer.error(err);
336
+ });
337
+ const host = ts.createWatchCompilerHost(
338
+ tsContext.configPath,
339
+ {
340
+ ...tsContext.config.options,
341
+ declaration: !0,
342
+ declarationDir: tmpPath,
343
+ emitDeclarationOnly: !0,
344
+ noEmit: !1,
345
+ noEmitOnError: strict ? !0 : tsContext.config.options.noEmitOnError ?? !0,
346
+ outDir: tmpPath
347
+ },
348
+ ts.sys,
349
+ ts.createEmitAndSemanticDiagnosticsBuilderProgram,
350
+ (diagnostic) => {
351
+ logger.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
352
+ `));
353
+ },
354
+ (diagnostic) => {
355
+ logger.info(ts.flattenDiagnosticMessageText(diagnostic.messageText, `
356
+ `));
357
+ }
358
+ ), origPostProgramCreate = host.afterProgramCreate;
359
+ host.afterProgramCreate = async (program) => {
360
+ origPostProgramCreate?.(program);
361
+ const messages = [], results = [];
362
+ for (const entry of task.entries) {
363
+ const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path.resolve(
364
+ tmpPath,
365
+ path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
366
+ ), targetPaths = entry.targetPaths.map((targetPath) => path.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path.relative(outDir, targetPath));
367
+ try {
368
+ const result = await extractTypes({
369
+ bundledPackages: bundledPackages || [],
370
+ customTags: config?.extract?.customTags,
371
+ cwd,
372
+ distPath: outDir,
373
+ exportPath,
374
+ files,
375
+ filePaths,
376
+ projectPath: cwd,
377
+ rules: config?.extract?.rules,
378
+ sourceTypesPath,
379
+ tsconfig: tsContext.config,
380
+ tmpPath,
381
+ tsconfigPath: path.resolve(cwd, tsContext.configPath || "tsconfig.json"),
382
+ extractorDisabled: config?.extract?.enabled === !1
383
+ });
384
+ messages.push(...result.messages), results.push({ sourcePath: path.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
385
+ } catch (err) {
386
+ if (err instanceof DtsError)
387
+ messages.push(...err.messages);
388
+ else {
389
+ observer.error(err);
390
+ return;
391
+ }
392
+ }
393
+ }
394
+ observer.next({ type: "dts", messages, results });
395
+ };
396
+ const watchProgram = ts.createWatchProgram(host);
397
+ return () => {
398
+ watchProgram.close(), rimraf.sync(tmpPath);
399
+ };
400
+ });
401
+ },
402
+ complete: (ctx, task, result) => {
403
+ const { logger } = ctx;
404
+ printExtractMessages(ctx, result.messages), logger.success(
405
+ `build type definitions
406
+ ${task.entries.map(
407
+ (entry) => ` - ${chalk.cyan(entry.importId)}: ${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(entry.targetPaths.join(", "))}`
408
+ ).join(`
409
+ `)}`
410
+ ), logger.log("");
411
+ },
412
+ error: (ctx, _task, err) => {
413
+ const { logger } = ctx;
414
+ err instanceof DtsError ? printExtractMessages(ctx, err.messages) : err instanceof Error && logger.error(err);
415
+ }
416
+ }, rolldownDtsTask = {
417
+ name: (ctx, task) => {
418
+ const bundleEntries = task.entries.filter((e) => e.path.includes("__$$bundle_")), entries = task.entries.filter((e) => !e.path.includes("__$$bundle_")), targetLines = task.target.length ? [" target:", ...task.target.map((t) => ` - ${chalk.yellow(t)}`)] : [], bundlesLines = bundleEntries.length ? [
419
+ " bundles:",
420
+ ...bundleEntries.map(
421
+ (e) => [
422
+ " - ",
423
+ `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(replaceFileEnding(e.output))}`
424
+ ].join("")
425
+ )
426
+ ] : [], entriesLines = entries.length ? [
427
+ " entries:",
428
+ ...entries.map(
429
+ (e) => [
430
+ " - ",
431
+ `${chalk.cyan(path.join(ctx.pkg.name, e.path))}: `,
432
+ `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(replaceFileEnding(e.output))}`
433
+ ].join("")
434
+ )
435
+ ] : [];
436
+ return [
437
+ `Build type definitions with ${chalk.bold("rolldown")}...`,
438
+ ` format: ${chalk.yellow(task.format)}`,
439
+ ...targetLines,
440
+ ...bundlesLines,
441
+ ...entriesLines
442
+ ].join(`
443
+ `);
444
+ },
445
+ exec: (ctx, task) => from(execPromise$1(ctx, task)),
446
+ complete: () => {
447
+ },
448
+ error: (_ctx, _task, err) => {
449
+ console.error(err);
450
+ }
451
+ };
452
+ async function execPromise$1(ctx, task) {
453
+ const [{ rolldown }, { resolveRolldownConfig }] = await Promise.all([
454
+ import("rolldown"),
455
+ import("./resolveRolldownConfig.js")
456
+ ]), { distPath, files, logger } = ctx, outDir = path.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
457
+ onRestored: (messages) => {
458
+ for (const msg of messages) {
459
+ const text = String(msg.args[0]);
460
+ 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)));
461
+ }
462
+ }
463
+ });
464
+ try {
465
+ const { inputOptions, outputOptions } = resolveRolldownConfig(ctx, task), bundle = await rolldown({
466
+ ...inputOptions,
467
+ onwarn(warning) {
468
+ consoleSpy.messages.push({
469
+ type: "warn",
470
+ code: warning.code,
471
+ args: [warning.message]
472
+ });
473
+ }
474
+ }), { output } = await bundle.generate(outputOptions);
475
+ for (const chunkOrAsset of output)
476
+ chunkOrAsset.type === "asset" ? files.push({
477
+ type: "asset",
478
+ path: path.resolve(outDir, chunkOrAsset.fileName)
479
+ }) : files.push({
480
+ type: "chunk",
481
+ path: path.resolve(outDir, chunkOrAsset.fileName)
482
+ });
483
+ await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
484
+ } catch (err) {
485
+ throw consoleSpy.restore(), err;
486
+ }
487
+ }
488
+ function replaceFileEnding(path2) {
489
+ switch (!0) {
490
+ case path2.endsWith(".mjs"):
491
+ return path2.replace(/\.mjs$/, ".d.mts");
492
+ case path2.endsWith(".cjs"):
493
+ return path2.replace(/\.cjs$/, ".d.cts");
494
+ default:
495
+ return path2.replace(/\.js$/, ".d.ts");
496
+ }
497
+ }
498
+ function resolveRollupConfig(ctx, buildTask) {
499
+ const { format, runtime, target } = buildTask, { config, cwd, exports: _exports, external, distPath, logger, pkg, ts: ts2 } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format], minify = config?.minify ?? !1, outDir = path.relative(cwd, distPath), pathAliases = Object.fromEntries(
500
+ Object.entries(ts2.config?.options.paths || {}).map(([key, val]) => [key, path.resolve(cwd, ts2.config?.options.baseUrl || ".", val[0])])
501
+ ), entries = buildTask.entries.map((entry) => ({
502
+ ...entry,
503
+ name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
504
+ }), {}), exportIds = _exports && Object.keys(_exports).map((exportPath) => path.join(pkg.name, exportPath)), sourcePaths = _exports && Object.values(_exports).map((e) => path.resolve(cwd, e.source)), replacements = Object.fromEntries(
505
+ Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
506
+ ), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config?.rollup || {}, defaultPlugins = [
507
+ replace({
508
+ preventAssignment: !0,
509
+ values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
510
+ "process.env.PKG_FILE_PATH": (arg) => {
511
+ const sourcePath = `./${path.relative(cwd, arg)}`, entry = entries.find((e) => e.source === sourcePath);
512
+ return entry ? JSON.stringify(
513
+ path.relative(cwd, path.resolve(outDir, entry.name + outputExt))
514
+ ) : (console.error(`could not find source entry: ${sourcePath}`), "null");
515
+ },
516
+ "process.env.PKG_FORMAT": JSON.stringify(format),
517
+ "process.env.PKG_RUNTIME": JSON.stringify(runtime),
518
+ "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
519
+ ...replacements
520
+ }
521
+ }),
522
+ alias({
523
+ entries: { ...pathAliases }
524
+ }),
525
+ nodeResolve({
526
+ browser: runtime === "browser",
527
+ extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
528
+ preferBuiltins: !0
529
+ }),
530
+ commonjs(),
531
+ json(),
532
+ (config?.babel?.reactCompiler || config?.babel?.styledComponents) && babel({
533
+ babelrc: !1,
534
+ presets: ["@babel/preset-typescript"],
535
+ babelHelpers: "bundled",
536
+ extensions: [".ts", ".tsx", ".js", ".jsx"],
537
+ plugins: [
538
+ // The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
539
+ config?.babel?.styledComponents && [
540
+ "babel-plugin-styled-components",
541
+ {
542
+ // 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``"
543
+ fileName: !1,
544
+ // Native template literals take less space than this transpilation
545
+ transpileTemplateLiterals: !1,
546
+ // Massively helps dead code elimination and tree-shaking
547
+ pure: !0,
548
+ // disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
549
+ cssProp: !1,
550
+ ...typeof config.babel.styledComponents == "object" ? config.babel.styledComponents : {}
551
+ }
552
+ ],
553
+ config?.babel?.reactCompiler && [
554
+ "babel-plugin-react-compiler",
555
+ config?.reactCompilerOptions || {}
556
+ ]
557
+ ].filter(Boolean)
558
+ }),
559
+ esbuild({
560
+ jsx: config?.jsx ?? "automatic",
561
+ jsxFactory: config?.jsxFactory ?? "createElement",
562
+ jsxFragment: config?.jsxFragment ?? "Fragment",
563
+ jsxImportSource: config?.jsxImportSource ?? "react",
564
+ target,
565
+ tsconfig: ctx.ts.configPath || "tsconfig.json",
566
+ treeShaking: !0,
567
+ minifySyntax: config?.minify !== !1,
568
+ supported: {
569
+ "template-literal": !0
570
+ }
571
+ }),
572
+ Array.isArray(config?.babel?.plugins) && getBabelOutputPlugin({
573
+ babelrc: !1,
574
+ plugins: config.babel.plugins
575
+ }),
576
+ enableOptimizeLodash && optimizeLodashImports({
577
+ useLodashEs: format === "esm" && hasDependency(pkg, "lodash-es") ? !0 : void 0,
578
+ ...typeof config?.rollup?.optimizeLodash == "boolean" ? {} : config?.rollup?.optimizeLodash
579
+ }),
580
+ minify && terser({
581
+ compress: { directives: !1, passes: 10 },
582
+ ecma: 2020,
583
+ output: {
584
+ comments: (_node, comment) => {
585
+ const text = comment.value;
586
+ return comment.type === "comment2" ? /@preserve|@license|@cc_on/i.test(text) : !1;
587
+ },
588
+ preserve_annotations: !0
589
+ }
590
+ })
591
+ ].filter(Boolean), userPlugins = config?.rollup?.plugins, plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty(config?.rollup?.plugins, defaultPlugins), hashChunkFileNames = config?.rollup?.hashChunkFileNames ?? !1, chunkFileNames = `${hashChunkFileNames ? "_chunks" : "_chunks-[format]"}/${hashChunkFileNames ? "[name]-[hash]" : "[name]"}${outputExt}`, entryFileNames = `[name]${outputExt}`;
592
+ return {
593
+ inputOptions: {
594
+ context: cwd,
595
+ external: (id, importer) => {
596
+ if (exportIds?.includes(id))
597
+ return !0;
598
+ if (importer && (id.startsWith(".") || id.startsWith("/"))) {
599
+ const idPath = path.resolve(path.dirname(importer), id);
600
+ if (sourcePaths?.includes(idPath))
601
+ return logger.warn(
602
+ `detected self-referencing import \u2013 treating as external: ${path.relative(
603
+ cwd,
604
+ idPath
605
+ )}`
606
+ ), !0;
607
+ }
608
+ const idParts = id.split("/"), name = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0];
609
+ return !!(name && external.includes(name));
610
+ },
611
+ input: entries.reduce(
612
+ (acc, entry) => Object.assign(acc, { [entry.name]: entry.source }),
613
+ {}
614
+ ),
615
+ watch: {
616
+ chokidar: {
617
+ usePolling: !0
618
+ }
619
+ },
620
+ plugins,
621
+ treeshake: {
622
+ preset: "recommended",
623
+ propertyReadSideEffects: !1,
624
+ moduleSideEffects: "no-external",
625
+ ...config?.rollup?.treeshake
626
+ },
627
+ experimentalLogSideEffects: config?.rollup?.experimentalLogSideEffects
628
+ },
629
+ outputOptions: {
630
+ chunkFileNames,
631
+ compact: minify,
632
+ dir: outDir,
633
+ entryFileNames,
634
+ esModule: !0,
635
+ format,
636
+ interop: "compat",
637
+ sourcemap: config?.sourcemap ?? !0,
638
+ hoistTransitiveImports: !1,
639
+ minifyInternalExports: minify,
640
+ ...config?.rollup?.output
641
+ }
642
+ };
643
+ }
644
+ function hasDependency(pkg, packageName) {
645
+ return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
646
+ }
647
+ const rollupTask = {
648
+ name: (ctx, task) => {
649
+ const bundleEntries = task.entries.filter((e) => e.path.includes("__$$bundle_")), entries = task.entries.filter((e) => !e.path.includes("__$$bundle_")), targetLines = task.target.length ? [" target:", ...task.target.map((t) => ` - ${chalk.yellow(t)}`)] : [], bundlesLines = bundleEntries.length ? [
650
+ " bundles:",
651
+ ...bundleEntries.map(
652
+ (e) => [
653
+ " - ",
654
+ `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
655
+ ].join("")
656
+ )
657
+ ] : [], entriesLines = entries.length ? [
658
+ " entries:",
659
+ ...entries.map(
660
+ (e) => [
661
+ " - ",
662
+ `${chalk.cyan(path.join(ctx.pkg.name, e.path))}: `,
663
+ `${chalk.yellow(e.source)} ${chalk.gray("\u2192")} ${chalk.yellow(e.output)}`
664
+ ].join("")
665
+ )
666
+ ] : [];
667
+ return [
668
+ "Build javascript files...",
669
+ ` format: ${chalk.yellow(task.format)}`,
670
+ ...targetLines,
671
+ ...bundlesLines,
672
+ ...entriesLines
673
+ ].join(`
674
+ `);
675
+ },
676
+ exec: (ctx, task) => new Observable((observer) => {
677
+ execPromise(ctx, task).then((result) => {
678
+ observer.next(result), observer.complete();
679
+ }).catch((err) => observer.error(err));
680
+ }),
681
+ complete: () => {
682
+ },
683
+ error: (_ctx, _task, err) => {
684
+ console.error(err);
685
+ }
686
+ };
687
+ async function execPromise(ctx, task) {
688
+ const { distPath, files, logger } = ctx, outDir = path.relative(ctx.cwd, distPath), consoleSpy = createConsoleSpy({
689
+ onRestored: (messages) => {
690
+ for (const msg of messages) {
691
+ const text = String(msg.args[0]);
692
+ 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)));
693
+ }
694
+ }
695
+ });
696
+ try {
697
+ const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task), bundle = await rollup({
698
+ ...inputOptions,
699
+ onwarn(warning) {
700
+ consoleSpy.messages.push({
701
+ type: "warn",
702
+ code: warning.code,
703
+ args: [warning.message]
704
+ });
705
+ }
706
+ }), { output } = await bundle.generate(outputOptions);
707
+ for (const chunkOrAsset of output)
708
+ chunkOrAsset.type === "asset" ? files.push({
709
+ type: "asset",
710
+ path: path.resolve(outDir, chunkOrAsset.fileName)
711
+ }) : files.push({
712
+ type: "chunk",
713
+ path: path.resolve(outDir, chunkOrAsset.fileName)
714
+ });
715
+ await bundle.write(outputOptions), await bundle.close(), consoleSpy.restore();
716
+ } catch (err) {
717
+ throw consoleSpy.restore(), err;
718
+ }
719
+ }
720
+ const rollupWatchTask = {
721
+ name: (ctx, task) => `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
722
+ ${task.entries.map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
723
+ `)}`,
724
+ exec: (ctx, task) => {
725
+ const { inputOptions, outputOptions } = resolveRollupConfig(ctx, task);
726
+ return new Observable((observer) => {
727
+ const watchOptions = {
728
+ ...inputOptions,
729
+ output: outputOptions
730
+ }, watcher = watch(watchOptions);
731
+ return watcher.on("event", (event) => {
732
+ observer.next(event);
733
+ }), () => {
734
+ watcher.close();
735
+ };
736
+ });
737
+ },
738
+ complete: (ctx, task, event) => {
739
+ const { logger } = ctx;
740
+ if (event.code === "BUNDLE_END") {
741
+ logger.success(
742
+ `build javascript files (target ${task.target.join(" + ")}, format ${task.format})
743
+ ${task.entries.map((e) => `${chalk.blue(path.join(ctx.pkg.name, e.path))}: ${e.source} -> ${e.output}`).join(`
744
+ `)}`
745
+ ), logger.log("");
746
+ return;
747
+ }
748
+ if (event.code !== "BUNDLE_START" && event.code !== "END" && event.code === "ERROR") {
749
+ logger.error(event.code, event);
750
+ return;
751
+ }
752
+ },
753
+ error: (ctx, _task, err) => {
754
+ const { logger } = ctx;
755
+ err instanceof Error && logger.log(err);
756
+ }
757
+ }, buildTaskHandlers = {
758
+ "build:dts": dtsTask,
759
+ "build:js": rollupTask,
760
+ "rolldown:dts": rolldownDtsTask
761
+ }, watchTaskHandlers = {
762
+ "watch:dts": dtsWatchTask,
763
+ "watch:js": rollupWatchTask
764
+ };
765
+ export {
766
+ buildTaskHandlers,
767
+ watchTaskHandlers
768
+ };
769
+ //# sourceMappingURL=index2.js.map