@sanity/pkg-utils 5.1.0 → 5.1.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.
package/dist/index.js CHANGED
@@ -142,10 +142,6 @@ async function loadPkg(options2) {
142
142
  const buf = await fs.readFile(pkgPath), raw = JSON.parse(buf.toString());
143
143
  return validatePkg(raw), raw;
144
144
  }
145
- function assertFirst(a, arr) {
146
- const aIdx = arr.indexOf(a);
147
- return aIdx === -1 ? !0 : aIdx === 0;
148
- }
149
145
  function assertLast(a, arr) {
150
146
  const aIdx = arr.indexOf(a);
151
147
  return aIdx === -1 ? !0 : aIdx === arr.length - 1;
@@ -165,7 +161,9 @@ async function loadPkgWithReporting(options2) {
165
161
  if (typeof exp == "string" || "svelte" in exp)
166
162
  continue;
167
163
  const keys = Object.keys(exp);
168
- assertFirst("types", keys) || (shouldError = !0, logger.error(`exports["${expPath}"]: the \`types\` property should be the first property`)), exp.module && (shouldError = !0, logger.error(
164
+ exp.types && (shouldError = !0, logger.error(
165
+ `exports["${expPath}"]: the \`types\` condition shouldn't be used as dts files are generated in such a way that both CJS and ESM is supported`
166
+ )), exp.module && (shouldError = !0, logger.error(
169
167
  `exports["${expPath}"]: the \`module\` condition shouldn't be used as it's not well supported in all bundlers.`
170
168
  )), exp.node ? (exp.import && exp.node.import && !assertOrder("node", "import", keys) && (shouldError = !0, logger.error(
171
169
  `exports["${expPath}"]: the \`node\` property should come before the \`import\` property`
@@ -222,7 +220,6 @@ function parseExports(options2) {
222
220
  const { extMap, pkg, strict } = options2, rootExport = {
223
221
  _exported: !0,
224
222
  _path: ".",
225
- types: pkg.types,
226
223
  source: pkg.source || "",
227
224
  browser: pkg.browser && {
228
225
  source: pkg.source || "",
@@ -233,7 +230,9 @@ function parseExports(options2) {
233
230
  import: pkg.module,
234
231
  default: pkg.module || pkg.main || ""
235
232
  }, extraExports = [], errors = [];
236
- if (pkg.exports) {
233
+ if (strict && !pkg.types && pkg.source?.endsWith(".ts") && errors.push(
234
+ "package.json: `types` must be declared for the npm listing to show as a TypeScript module."
235
+ ), strict && "typings" in pkg && errors.push("package.json: `typings` should be `types`"), pkg.exports) {
237
236
  strict && !pkg.exports["./package.json"] && errors.push('package.json: `exports["./package.json"] must be declared.');
238
237
  for (const [exportPath, exportEntry] of Object.entries(pkg.exports))
239
238
  if (exportPath.endsWith(".json"))
@@ -245,8 +244,6 @@ function parseExports(options2) {
245
244
  'package.json: mismatch between "main" and "exports.require". These must be equal.'
246
245
  ), exportEntry.import && rootExport.import && exportEntry.import !== rootExport.import && errors.push(
247
246
  'package.json: mismatch between "module" and "exports.import" These must be equal.'
248
- ), exportEntry.types && rootExport.types && exportEntry.types !== rootExport.types && errors.push(
249
- 'package.json: mismatch between "types" and "exports.types". These must be equal.'
250
247
  ), exportEntry.source && rootExport.source && exportEntry.source !== rootExport.source && errors.push(
251
248
  'package.json: mismatch between "source" and "exports.source". These must be equal.'
252
249
  ), Object.assign(rootExport, exportEntry);
@@ -491,6 +488,25 @@ async function resolveBuildContext(options2) {
491
488
  }
492
489
  };
493
490
  }
491
+ const fileEnding = /\.[mc]?js$/, dtsEnding = ".d.ts", mtsEnding = ".d.mts", ctsEnding = ".d.cts";
492
+ function getTargetPaths(_type, expOrBundle) {
493
+ const type = _type === "module" ? "module" : "commonjs", set = /* @__PURE__ */ new Set();
494
+ 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(expOrBundle) && (expOrBundle.browser?.source || (expOrBundle.browser?.import && set.add(
495
+ expOrBundle.browser.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
496
+ ), expOrBundle.browser?.require && set.add(
497
+ expOrBundle.browser.require.replace(
498
+ fileEnding,
499
+ type === "commonjs" ? dtsEnding : ctsEnding
500
+ )
501
+ )), expOrBundle.node?.source || (expOrBundle.node?.import && set.add(
502
+ expOrBundle.node.import.replace(fileEnding, type === "module" ? dtsEnding : mtsEnding)
503
+ ), expOrBundle.node?.require && set.add(
504
+ expOrBundle.node.require.replace(fileEnding, type === "commonjs" ? dtsEnding : ctsEnding)
505
+ ))), Array.from(set);
506
+ }
507
+ function isPkgExport(exp) {
508
+ return exp?.browser || exp?.node || exp?.default;
509
+ }
494
510
  function resolveBuildTasks(ctx) {
495
511
  const { config: config2, cwd, pkg, target } = ctx, bundles = config2?.bundles || [], tasks = [], exports = Object.entries(ctx.exports || {}).map(
496
512
  ([_path, exp]) => ({ _path, ...exp })
@@ -511,11 +527,30 @@ function resolveBuildTasks(ctx) {
511
527
  }
512
528
  for (const exp of exports) {
513
529
  const importId = path$1.join(pkg.name, exp._path);
514
- exp.types && dtsTask2.entries.push({
530
+ exp.source?.endsWith(".ts") && dtsTask2.entries.push({
515
531
  importId,
516
532
  exportPath: exp._path,
517
533
  sourcePath: exp.source,
518
- targetPath: exp.types
534
+ targetPaths: getTargetPaths(pkg.type, exp)
535
+ }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
536
+ importId,
537
+ exportPath: exp._path,
538
+ sourcePath: exp.browser.source,
539
+ targetPaths: getTargetPaths(pkg.type, exp.browser)
540
+ }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
541
+ importId,
542
+ exportPath: exp._path,
543
+ sourcePath: exp.node.source,
544
+ targetPaths: getTargetPaths(pkg.type, exp.node)
545
+ });
546
+ }
547
+ for (const bundle of bundles) {
548
+ const exportPath = (bundle.import || bundle.require).replace(/\.[mc]?js$/, ""), importId = path$1.join(pkg.name, exportPath);
549
+ dtsTask2.entries.push({
550
+ importId,
551
+ exportPath,
552
+ sourcePath: bundle.source,
553
+ targetPaths: getTargetPaths(pkg.type, bundle)
519
554
  });
520
555
  }
521
556
  if (dtsTask2.entries.length && tasks.push(dtsTask2), !ctx.emitDeclarationOnly) {
@@ -20180,7 +20215,7 @@ async function extractTypes(options2) {
20180
20215
  distPath,
20181
20216
  exportPath,
20182
20217
  files,
20183
- filePath,
20218
+ filePaths,
20184
20219
  projectPath,
20185
20220
  rules,
20186
20221
  sourceTypesPath,
@@ -20189,7 +20224,7 @@ async function extractTypes(options2) {
20189
20224
  tsconfigPath
20190
20225
  } = options2, tsdocConfigFile = await createTSDocConfig({
20191
20226
  customTags: customTags || []
20192
- }), extractorConfig = ExtractorConfig.prepare({
20227
+ }), filePath = filePaths[0].replace(/\.d\.[mc]ts$/, ".d.ts"), shouldCleanUpDts = !filePaths.includes(filePath), extractorConfig = ExtractorConfig.prepare({
20193
20228
  configObject: createApiExtractorConfig({
20194
20229
  bundledPackages,
20195
20230
  distPath,
@@ -20220,17 +20255,18 @@ async function extractTypes(options2) {
20220
20255
  tsOutDir: tmpPath
20221
20256
  }), code = [typesBuf.toString(), ...moduleBlocks].join(`
20222
20257
 
20223
- `);
20224
- return await fs.writeFile(
20225
- typesPath,
20226
- await prettier.format(code, {
20227
- ...prettierConfig,
20228
- filepath: typesPath
20229
- })
20230
- ), files.push({
20231
- type: "types",
20232
- path: typesPath
20233
- }), { extractorResult, messages };
20258
+ `), prettyCode = await prettier.format(code, {
20259
+ ...prettierConfig,
20260
+ filepath: typesPath
20261
+ });
20262
+ for (const expFilePath of filePaths) {
20263
+ const expTypesPath = path$1.resolve(distPath, expFilePath);
20264
+ await fs.writeFile(expTypesPath, prettyCode), files.push({
20265
+ type: "types",
20266
+ path: expTypesPath
20267
+ });
20268
+ }
20269
+ return shouldCleanUpDts && (console.warn("Cleaning up .d.ts file", typesPath), await fs.unlink(typesPath)), { extractorResult, messages };
20234
20270
  }
20235
20271
  async function doExtract(ctx, task) {
20236
20272
  const { config: config2, cwd, files, logger, strict, ts: ts2 } = ctx;
@@ -20246,14 +20282,14 @@ async function doExtract(ctx, task) {
20246
20282
  const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath, sourceTypesPath = path$1.resolve(
20247
20283
  tmpPath,
20248
20284
  path$1.relative(rootDir, path$1.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts")
20249
- ), targetPath = path$1.resolve(cwd, entry.targetPath), filePath = path$1.relative(outDir, targetPath), result = await extractTypes({
20285
+ ), targetPaths = entry.targetPaths.map((targetPath) => path$1.resolve(cwd, targetPath)), filePaths = targetPaths.map((targetPath) => path$1.relative(outDir, targetPath)), result = await extractTypes({
20250
20286
  bundledPackages: config2?.extract?.bundledPackages || [],
20251
20287
  customTags: config2?.extract?.customTags,
20252
20288
  cwd,
20253
20289
  distPath: outDir,
20254
20290
  exportPath,
20255
20291
  files,
20256
- filePath,
20292
+ filePaths,
20257
20293
  projectPath: cwd,
20258
20294
  rules: config2?.extract?.rules,
20259
20295
  sourceTypesPath,
@@ -20265,7 +20301,7 @@ async function doExtract(ctx, task) {
20265
20301
  const errors = result.messages.filter((msg) => msg.logLevel === "error");
20266
20302
  if (errors.length > 0)
20267
20303
  throw await rimraf(tmpPath), new DtsError(`encountered ${errors.length} errors when extracting types`, errors);
20268
- results.push({ sourcePath: path$1.resolve(cwd, entry.sourcePath), filePath: targetPath });
20304
+ results.push({ sourcePath: path$1.resolve(cwd, entry.sourcePath), filePaths: targetPaths });
20269
20305
  }
20270
20306
  return await rimraf(tmpPath), { type: "dts", messages, results };
20271
20307
  }
@@ -20273,12 +20309,11 @@ const dtsTask = {
20273
20309
  name: (_ctx, task) => [
20274
20310
  "Build type definitions...",
20275
20311
  " entries:",
20276
- ...task.entries.map(
20277
- (entry) => [
20278
- ` - ${chalk.cyan(entry.importId)}: `,
20279
- `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(entry.targetPath)}`
20280
- ].join("")
20281
- )
20312
+ ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
20313
+ ` - ${chalk.cyan(entry.importId)}: `,
20314
+ `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
20315
+ ].join("")).join(`
20316
+ `))
20282
20317
  ].join(`
20283
20318
  `),
20284
20319
  exec: (ctx, task) => new Observable((observer) => {
@@ -20298,9 +20333,10 @@ const dtsTask = {
20298
20333
  }, dtsWatchTask = {
20299
20334
  name: (_ctx, task) => [
20300
20335
  "build type definitions",
20301
- ...task.entries.map(
20302
- (entry) => ` ${chalk.blue(entry.importId)}: ${entry.sourcePath} -> ${entry.targetPath}`
20303
- )
20336
+ ...task.entries.map((entry) => entry.targetPaths.map((targetPath) => [
20337
+ ` - ${chalk.cyan(entry.importId)}: `,
20338
+ `${chalk.yellow(entry.sourcePath)} ${chalk.gray("\u2192")} ${chalk.yellow(targetPath)}`
20339
+ ].join("")))
20304
20340
  ].join(`
20305
20341
  `),
20306
20342
  exec: (ctx, task) => new Observable((observer) => {
@@ -20615,7 +20651,6 @@ function printPackageTree(ctx) {
20615
20651
  tree.exports = Object.fromEntries(
20616
20652
  Object.entries(exports).filter(([, entry]) => entry._exported).map(([exportPath, entry]) => {
20617
20653
  const exp = {
20618
- types: void 0,
20619
20654
  source: fileInfo(entry.source),
20620
20655
  browser: void 0,
20621
20656
  require: void 0,
@@ -20623,7 +20658,7 @@ function printPackageTree(ctx) {
20623
20658
  import: void 0,
20624
20659
  default: fileInfo(entry.default)
20625
20660
  };
20626
- return entry.types ? exp.types = fileInfo(entry.types) : delete exp.types, entry.browser ? (exp.browser = { source: fileInfo(entry.browser.source) }, entry.browser.import && (exp.browser.import = fileInfo(entry.browser.import)), entry.browser.require && (exp.browser.require = fileInfo(entry.browser.require))) : delete exp.browser, entry.require ? exp.require = fileInfo(entry.require) : delete exp.require, entry.node ? (exp.node = {}, entry.node.source && (exp.node.source = fileInfo(entry.node.source)), entry.node.import && (exp.node.import = fileInfo(entry.node.import)), entry.node.require && (exp.node.require = fileInfo(entry.node.require))) : delete exp.node, entry.import ? exp.import = fileInfo(entry.import) : delete exp.import, [chalk.cyan(path$1.join(pkg.name, exportPath)), exp];
20661
+ return entry.browser ? (exp.browser = { source: fileInfo(entry.browser.source) }, entry.browser.import && (exp.browser.import = fileInfo(entry.browser.import)), entry.browser.require && (exp.browser.require = fileInfo(entry.browser.require))) : delete exp.browser, entry.require ? exp.require = fileInfo(entry.require) : delete exp.require, entry.node ? (exp.node = {}, entry.node.source && (exp.node.source = fileInfo(entry.node.source)), entry.node.import && (exp.node.import = fileInfo(entry.node.import)), entry.node.require && (exp.node.require = fileInfo(entry.node.require))) : delete exp.node, entry.import ? exp.import = fileInfo(entry.import) : delete exp.import, [chalk.cyan(path$1.join(pkg.name, exportPath)), exp];
20627
20662
  })
20628
20663
  ), logger.log(treeify.asTree(tree, !0, !0));
20629
20664
  }
@@ -20632,8 +20667,8 @@ async function check(options2) {
20632
20667
  if (printPackageTree(ctx), strict) {
20633
20668
  const missingFiles = [];
20634
20669
  for (const [, exp] of Object.entries(ctx.exports || {}))
20635
- exp.source && !fileExists(path$1.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !fileExists(path$1.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !fileExists(path$1.resolve(cwd, exp.import)) && missingFiles.push(exp.import), exp.types && !fileExists(path$1.resolve(cwd, exp.types)) && missingFiles.push(exp.types);
20636
- missingFiles.length && (logger.error("missing files"), process.exit(1));
20670
+ exp.source && !fileExists(path$1.resolve(cwd, exp.source)) && missingFiles.push(exp.source), exp.require && !fileExists(path$1.resolve(cwd, exp.require)) && missingFiles.push(exp.require), exp.import && !fileExists(path$1.resolve(cwd, exp.import)) && missingFiles.push(exp.import);
20671
+ ctx.pkg.types && !fileExists(path$1.resolve(cwd, ctx.pkg.types)) && missingFiles.push(ctx.pkg.types), missingFiles.length && (logger.error(`missing files: ${missingFiles.join(", ")}`), process.exit(1));
20637
20672
  const exportPaths = {
20638
20673
  require: [],
20639
20674
  import: []
@@ -20899,9 +20934,7 @@ const RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/
20899
20934
  }, pkgJson.bugs = {
20900
20935
  url: `https://${repo.source}/${repo.owner}/${repo.name}/issues`
20901
20936
  }, pkgJson.homepage = `https://${repo.source}/${repo.owner}/${repo.name}#readme`), features.typescript) {
20902
- pkgJson.types = "./dist/index.d.ts";
20903
- const mainExport = pkgJson.exports?.["."];
20904
- isRecord(mainExport) && (mainExport.types = "./dist/index.d.ts"), pkgJson.scripts = {
20937
+ pkgJson.types = "./dist/index.d.ts", pkgJson.scripts = {
20905
20938
  ...pkgJson.scripts,
20906
20939
  "ts:check": "tsc --build"
20907
20940
  };
@@ -21213,11 +21246,21 @@ function resolveWatchTasks(ctx) {
21213
21246
  }
21214
21247
  for (const exp of exports) {
21215
21248
  const importId = path$1.join(pkg.name, exp._path);
21216
- exp.types && dtsTask2.entries.push({
21249
+ exp.source?.endsWith(".ts") && dtsTask2.entries.push({
21217
21250
  importId,
21218
21251
  exportPath: exp._path,
21219
21252
  sourcePath: exp.source,
21220
- targetPath: exp.types
21253
+ targetPaths: getTargetPaths(pkg.type, exp)
21254
+ }), exp.browser?.source?.endsWith(".ts") && dtsTask2.entries.push({
21255
+ importId,
21256
+ exportPath: exp._path,
21257
+ sourcePath: exp.browser.source,
21258
+ targetPaths: getTargetPaths(pkg.type, exp.browser)
21259
+ }), exp.node?.source?.endsWith(".ts") && dtsTask2.entries.push({
21260
+ importId,
21261
+ exportPath: exp._path,
21262
+ sourcePath: exp.node.source,
21263
+ targetPaths: getTargetPaths(pkg.type, exp.node)
21221
21264
  });
21222
21265
  }
21223
21266
  for (const exp of exports) {