@sanity/pkg-utils 1.4.1 → 1.6.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 (53) hide show
  1. package/dist/{__printPackageTree-793a302b.cjs → __printPackageTree-3ff3ecd3.cjs} +5 -4
  2. package/dist/__printPackageTree-3ff3ecd3.cjs.map +1 -0
  3. package/dist/{__resolveBuildContext-1b29cff2.cjs → __resolveBuildContext-bc09bff3.cjs} +4 -2
  4. package/dist/__resolveBuildContext-bc09bff3.cjs.map +1 -0
  5. package/dist/{_build-08236974.cjs → _build-89aeaf6a.cjs} +10 -9
  6. package/dist/_build-89aeaf6a.cjs.map +1 -0
  7. package/dist/{_buildAction-586dfb5f.cjs → _buildAction-8855cb5a.cjs} +7 -6
  8. package/dist/{_buildAction-586dfb5f.cjs.map → _buildAction-8855cb5a.cjs.map} +1 -1
  9. package/dist/_check-0ebe9af4.cjs +118 -0
  10. package/dist/_check-0ebe9af4.cjs.map +1 -0
  11. package/dist/{_statusAction-385b72dd.cjs → _checkAction-a96c4021.cjs} +9 -7
  12. package/dist/_checkAction-a96c4021.cjs.map +1 -0
  13. package/dist/{_index-c5bd1bc8.cjs → _index-0e8b664d.cjs} +63 -21
  14. package/dist/_index-0e8b664d.cjs.map +1 -0
  15. package/dist/{_watch-003a06b2.cjs → _watch-cf0df170.cjs} +7 -6
  16. package/dist/_watch-cf0df170.cjs.map +1 -0
  17. package/dist/{_watchAction-c7cf282d.cjs → _watchAction-bd901b01.cjs} +5 -4
  18. package/dist/{_watchAction-c7cf282d.cjs.map → _watchAction-bd901b01.cjs.map} +1 -1
  19. package/dist/cli.cjs +5 -5
  20. package/dist/cli.cjs.map +1 -1
  21. package/dist/index.cjs +8 -6
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.ts +25 -5
  24. package/dist/index.js +171 -33
  25. package/dist/index.js.map +1 -1
  26. package/package.json +14 -3
  27. package/src/cli/checkAction.ts +9 -0
  28. package/src/cli/index.ts +3 -2
  29. package/src/node/_core/config/types.ts +16 -0
  30. package/src/node/_core/pkg/_loadPkg.ts +1 -0
  31. package/src/node/_printPackageTree.ts +3 -3
  32. package/src/node/_resolveBuildTasks.ts +6 -4
  33. package/src/node/_resolveEsTarget.ts +39 -0
  34. package/src/node/_resolveWatchTasks.ts +5 -4
  35. package/src/node/_tasks/dts/_buildTypes.ts +11 -1
  36. package/src/node/_tasks/dts/_doExtract.ts +16 -5
  37. package/src/node/_tasks/dts/_dtsTask.ts +4 -2
  38. package/src/node/_tasks/dts/_dtsWatchTask.ts +2 -2
  39. package/src/node/_tasks/dts/_extractTypes.ts +5 -2
  40. package/src/node/_tasks/dts/_types.ts +4 -4
  41. package/src/node/_tasks/rollup/_resolveRollupConfig.ts +5 -4
  42. package/src/node/_tasks/rollup/_rollupTask.ts +6 -4
  43. package/src/node/build.ts +3 -1
  44. package/src/node/check.ts +125 -3
  45. package/dist/__printPackageTree-793a302b.cjs.map +0 -1
  46. package/dist/__resolveBuildContext-1b29cff2.cjs.map +0 -1
  47. package/dist/_build-08236974.cjs.map +0 -1
  48. package/dist/_check-9d180462.cjs +0 -16
  49. package/dist/_check-9d180462.cjs.map +0 -1
  50. package/dist/_index-c5bd1bc8.cjs.map +0 -1
  51. package/dist/_statusAction-385b72dd.cjs.map +0 -1
  52. package/dist/_watch-003a06b2.cjs.map +0 -1
  53. package/src/cli/statusAction.ts +0 -8
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { Observable, switchMap } from 'rxjs';
11
11
  import { promisify } from 'util';
12
12
  import rimrafCallback from 'rimraf';
13
13
  import { ExtractorConfig, Extractor } from '@microsoft/api-extractor';
14
+ import mkdirp from 'mkdirp';
14
15
  import prettier from 'prettier';
15
16
  import { TSDocConfigFile } from '@microsoft/tsdoc-config';
16
17
  import { parse } from 'jsonc-parser';
@@ -25,6 +26,7 @@ import treeify from 'treeify';
25
26
  import prettyBytes from 'pretty-bytes';
26
27
  import browserslist from 'browserslist';
27
28
  import ora from 'ora';
29
+ import esbuild$1 from 'esbuild';
28
30
  import { scan, startWith, distinctUntilChanged } from 'rxjs/operators';
29
31
  import globby from 'globby';
30
32
  import chokidar from 'chokidar';
@@ -96,6 +98,7 @@ const pkgSchema = z.object({
96
98
  main: z.optional(z.string()),
97
99
  browser: z.optional(z.record(z.string())),
98
100
  module: z.optional(z.string()),
101
+ types: z.optional(z.string()),
99
102
  exports: z.optional(
100
103
  z.record(
101
104
  z.object({
@@ -196,9 +199,31 @@ async function _loadTSConfig(options) {
196
199
  return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
197
200
  }
198
201
 
202
+ const TS_TARGETS = {
203
+ 0: "es3",
204
+ 1: "es5",
205
+ 2: "es2015",
206
+ 3: "es2016",
207
+ 4: "es2017",
208
+ 5: "es2018",
209
+ 6: "es2019",
210
+ 7: "es2020",
211
+ 8: "es2021",
212
+ 9: "es2022",
213
+ 99: "esnext",
214
+ 100: "esnext"
215
+ };
216
+ function _resolveEsTarget(ctx) {
217
+ var _a;
218
+ const { ts } = ctx;
219
+ const tsTarget = ((_a = ts.config) == null ? void 0 : _a.options.target) || 99;
220
+ return TS_TARGETS[tsTarget] || "esnext";
221
+ }
222
+
199
223
  function _resolveBuildTasks(ctx) {
200
224
  var _a, _b, _c, _d, _e;
201
225
  const { cwd, pkg, target } = ctx;
226
+ const esTarget = _resolveEsTarget(ctx);
202
227
  const tasks = [];
203
228
  const exports = Object.entries(ctx.exports || {}).map(
204
229
  ([_path, exp]) => ({ _path, ...exp })
@@ -214,7 +239,7 @@ function _resolveBuildTasks(ctx) {
214
239
  entries: [entry],
215
240
  runtime,
216
241
  format,
217
- target: target[runtime]
242
+ target: [esTarget].concat(target[runtime])
218
243
  };
219
244
  } else {
220
245
  rollupTasks[buildId].entries.push(entry);
@@ -228,8 +253,8 @@ function _resolveBuildTasks(ctx) {
228
253
  type: "build:dts",
229
254
  importId,
230
255
  exportPath: exp._path,
231
- source: exp.source,
232
- output: exp.types
256
+ sourcePath: exp.source,
257
+ targetPath: exp.types
233
258
  };
234
259
  }
235
260
  }
@@ -285,7 +310,6 @@ function _resolveBuildTasks(ctx) {
285
310
  [
286
311
  `// AUTO-GENERATED \u2013 DO NOT EDIT`,
287
312
  ``,
288
- `export {default} from '${relativeTargetPath}'`,
289
313
  `export * from '${relativeTargetPath}'`,
290
314
  ``
291
315
  ].join("\n")
@@ -355,6 +379,10 @@ async function _buildTypes(options) {
355
379
  noEmit: false,
356
380
  outDir
357
381
  };
382
+ const rootDir = path.relative(
383
+ cwd,
384
+ compilerOptions.rootDir ? path.resolve(cwd, compilerOptions.rootDir) : path.dirname(path.resolve(cwd, sourcePath))
385
+ ) || ".";
358
386
  const program = ts.createProgram(tsconfig.fileNames, compilerOptions);
359
387
  const sourceFiles = program.getSourceFiles();
360
388
  const sourceFile = sourceFiles.find((f) => f.fileName === path.resolve(cwd, sourcePath));
@@ -380,7 +408,7 @@ ${message}`);
380
408
  throw new Error("failed to compile");
381
409
  }
382
410
  }
383
- const typesPath = path.resolve(outDir, sourcePath.replace(/\.ts$/, ".d.ts"));
411
+ const typesPath = path.resolve(outDir, path.relative(rootDir, path.resolve(cwd, sourcePath))).replace(/\.[jt]sx?$/, ".d.ts");
384
412
  return { path: typesPath };
385
413
  }
386
414
 
@@ -523,9 +551,10 @@ async function _extractTypes(options) {
523
551
  message.handled = true;
524
552
  }
525
553
  });
526
- const typesPath = path.resolve(distPath, `${exportPath}.d.ts`);
554
+ const typesPath = path.resolve(distPath, filePath);
527
555
  const typesBuf = await fs.readFile(typesPath);
528
556
  const prettierConfig = await prettier.resolveConfig(typesPath);
557
+ await mkdirp(path.dirname(typesPath));
529
558
  await fs.writeFile(
530
559
  typesPath,
531
560
  prettier.format(typesBuf.toString(), {
@@ -542,27 +571,37 @@ async function _extractTypes(options) {
542
571
 
543
572
  const rimraf = promisify(rimrafCallback);
544
573
  async function _doExtract(ctx, task) {
545
- var _a, _b;
574
+ var _a;
546
575
  const { config, cwd, dist, files, ts } = ctx;
547
576
  if (!ts.config || !ts.configPath)
548
577
  return { type: "dts", messages: [] };
549
- const sourcePath = task.source;
578
+ const sourcePath = task.sourcePath;
550
579
  const exportPath = task.exportPath === "." ? "./index" : task.exportPath;
551
580
  const distPath = path.resolve(cwd, dist);
552
- const outDir = ((_a = ts.config) == null ? void 0 : _a.options.outDir) || path.resolve(cwd, dist);
553
- const types = await _buildTypes({ cwd, outDir, sourcePath, tsconfig: ts.config });
581
+ const filePath = path.relative(distPath, path.resolve(cwd, task.targetPath));
582
+ const tmpDirPath = path.resolve(distPath, "__dts__");
583
+ const tmpDir = {
584
+ path: tmpDirPath,
585
+ removeCallback: () => rimraf(tmpDirPath)
586
+ };
587
+ const types = await _buildTypes({
588
+ cwd,
589
+ outDir: tmpDir.path,
590
+ sourcePath,
591
+ tsconfig: ts.config
592
+ });
554
593
  const { messages } = await _extractTypes({
555
594
  cwd,
556
595
  exportPath,
557
596
  files,
558
- filePath: path.relative(distPath, path.resolve(cwd, task.output)),
597
+ filePath,
559
598
  projectPath: cwd,
560
- rules: (_b = config == null ? void 0 : config.extract) == null ? void 0 : _b.rules,
599
+ rules: (_a = config == null ? void 0 : config.extract) == null ? void 0 : _a.rules,
561
600
  sourcePath: types.path,
562
601
  tsconfigPath: path.resolve(cwd, ts.configPath),
563
602
  distPath
564
603
  });
565
- await rimraf(outDir);
604
+ await tmpDir.removeCallback();
566
605
  if (messages.some((msg) => msg.logLevel === "error")) {
567
606
  throw new _DtsError("encountered errors when extracting types", messages);
568
607
  }
@@ -572,14 +611,16 @@ async function _doExtract(ctx, task) {
572
611
  const _dtsTask = {
573
612
  name: (_ctx, task) => [
574
613
  `build type definitions`,
575
- ` ${chalk.blue(task.importId)}: ${task.source} -> ${task.output}`
614
+ ` ${chalk.blue(task.importId)}: ${task.sourcePath} -> ${task.targetPath}`
576
615
  ].join("\n"),
577
616
  exec: (ctx, task) => {
578
617
  return new Observable((observer) => {
579
618
  _doExtract(ctx, task).then((result) => {
580
619
  observer.next(result);
581
620
  observer.complete();
582
- }).catch(observer.error);
621
+ }).catch((err) => {
622
+ observer.error(err);
623
+ });
583
624
  });
584
625
  },
585
626
  complete: (ctx, _task, result) => {
@@ -598,14 +639,14 @@ const _dtsTask = {
598
639
  const _dtsWatchTask = {
599
640
  name: (_ctx, task) => [
600
641
  `build type definitions`,
601
- ` ${chalk.blue(task.importId)}: ${task.source} -> ${task.output}`
642
+ ` ${chalk.blue(task.importId)}: ${task.sourcePath} -> ${task.targetPath}`
602
643
  ].join("\n"),
603
644
  exec: (ctx, task) => {
604
645
  return new Observable((observer) => {
605
646
  _doExtract(ctx, task).then((result) => {
606
647
  observer.next(result);
607
648
  observer.complete();
608
- }).catch(observer.error);
649
+ }).catch((err) => observer.error(err));
609
650
  });
610
651
  },
611
652
  complete: (ctx, _task, result) => {
@@ -625,7 +666,7 @@ const _dtsWatchTask = {
625
666
  };
626
667
 
627
668
  function _resolveRollupConfig(ctx, buildTask) {
628
- var _a;
669
+ var _a, _b, _c, _d, _e, _f, _g;
629
670
  const { format, runtime, target } = buildTask;
630
671
  const { config, cwd, external, dist: outDir, pkg, ts } = ctx;
631
672
  const outputExt = format === "commonjs" ? ".cjs" : pkg.type === "module" ? ".mjs" : ".js";
@@ -695,10 +736,11 @@ function _resolveRollupConfig(ctx, buildTask) {
695
736
  }),
696
737
  json(),
697
738
  esbuild({
698
- minify: (config == null ? void 0 : config.minify) ?? true,
699
- jsx: "transform",
700
- jsxFactory: "React.createElement",
701
- jsxFragment: "React.Fragment",
739
+ minify: (_b = config == null ? void 0 : config.minify) != null ? _b : true,
740
+ jsx: (_c = config == null ? void 0 : config.jsx) != null ? _c : "automatic",
741
+ jsxFactory: (_d = config == null ? void 0 : config.jsxFactory) != null ? _d : "createElement",
742
+ jsxFragment: (_e = config == null ? void 0 : config.jsxFragment) != null ? _e : "Fragment",
743
+ jsxImportSource: (_f = config == null ? void 0 : config.jsxImportSource) != null ? _f : "react",
702
744
  target,
703
745
  tsconfig: ctx.ts.configPath || "tsconfig.json"
704
746
  })
@@ -713,7 +755,7 @@ function _resolveRollupConfig(ctx, buildTask) {
713
755
  entryFileNames: () => `[name]${outputExt}`,
714
756
  format,
715
757
  exports: "auto",
716
- sourcemap: (config == null ? void 0 : config.sourcemap) ?? true
758
+ sourcemap: (_g = config == null ? void 0 : config.sourcemap) != null ? _g : true
717
759
  }
718
760
  };
719
761
  }
@@ -726,7 +768,7 @@ const _rollupTask = {
726
768
  _execPromise(ctx, task).then((result) => {
727
769
  observer.next(result);
728
770
  observer.complete();
729
- }, observer.error);
771
+ }).catch((err) => observer.error(err));
730
772
  });
731
773
  },
732
774
  complete: () => {
@@ -824,7 +866,7 @@ function _getFilesize(file) {
824
866
  return prettyBytes(stats.size);
825
867
  }
826
868
 
827
- function _getFileExists(file) {
869
+ function _fileExists(file) {
828
870
  try {
829
871
  fs$1.accessSync(file);
830
872
  return true;
@@ -834,7 +876,7 @@ function _getFileExists(file) {
834
876
  }
835
877
  function _getFileInfo(cwd, filePath) {
836
878
  const p = path.resolve(cwd, filePath);
837
- const exists = _getFileExists(p);
879
+ const exists = _fileExists(p);
838
880
  const size = exists ? _getFilesize(p) : void 0;
839
881
  return { exists, size };
840
882
  }
@@ -850,7 +892,7 @@ function _printPackageTree(ctx) {
850
892
  function _fileInfo(file) {
851
893
  const info = _getFileInfo(cwd, file);
852
894
  if (!info.size) {
853
- return chalk.gray(file);
895
+ return `${chalk.gray(file)} ${chalk.red("does not exist")}`;
854
896
  }
855
897
  return `${file} ${chalk.gray(info.size)}`;
856
898
  }
@@ -953,6 +995,7 @@ function _resolveNodeTarget(versions) {
953
995
  }
954
996
 
955
997
  async function _resolveBuildContext(options) {
998
+ var _a;
956
999
  const { config, cwd, pkg, tsconfig: tsconfigPath } = options;
957
1000
  const tsconfig = await _loadTSConfig({ cwd, tsconfigPath });
958
1001
  const targetVersions = _resolveBrowserslistVersions(pkg.browserslist || _DEFAULTS.browserslist);
@@ -1007,7 +1050,7 @@ async function _resolveBuildContext(options) {
1007
1050
  },
1008
1051
  pkg,
1009
1052
  src: path.relative(cwd, srcPath),
1010
- runtime: (config == null ? void 0 : config.runtime) ?? "*",
1053
+ runtime: (_a = config == null ? void 0 : config.runtime) != null ? _a : "*",
1011
1054
  target,
1012
1055
  ts: {
1013
1056
  config: tsconfig,
@@ -1055,7 +1098,8 @@ async function build(options) {
1055
1098
  } catch (err) {
1056
1099
  spinner.error();
1057
1100
  if (err instanceof Error) {
1058
- ctx.logger.error(err.message.replaceAll(cwd, "."));
1101
+ const RE_CWD = new RegExp(`${cwd}`, "g");
1102
+ ctx.logger.error(err.message.replace(RE_CWD, "."));
1059
1103
  ctx.logger.log();
1060
1104
  }
1061
1105
  handler.error(ctx, task, err);
@@ -1066,16 +1110,110 @@ async function build(options) {
1066
1110
  }
1067
1111
 
1068
1112
  async function check(options) {
1069
- const { cwd, tsconfig = "tsconfig.json" } = options;
1113
+ const { cwd, strict, tsconfig = "tsconfig.json" } = options;
1070
1114
  const pkg = await _loadPkgWithReporting({ cwd });
1071
1115
  const config = await _loadConfig({ cwd });
1072
1116
  const ctx = await _resolveBuildContext({ config, cwd, pkg, tsconfig });
1073
1117
  _printPackageTree(ctx);
1118
+ if (strict) {
1119
+ const missingFiles = [];
1120
+ for (const [, exp] of Object.entries(ctx.exports || {})) {
1121
+ if (exp.source && !_fileExists(path.resolve(cwd, exp.source))) {
1122
+ missingFiles.push(exp.source);
1123
+ }
1124
+ if (exp.require && !_fileExists(path.resolve(cwd, exp.require))) {
1125
+ missingFiles.push(exp.require);
1126
+ }
1127
+ if (exp.import && !_fileExists(path.resolve(cwd, exp.import))) {
1128
+ missingFiles.push(exp.import);
1129
+ }
1130
+ if (exp.types && !_fileExists(path.resolve(cwd, exp.types))) {
1131
+ missingFiles.push(exp.types);
1132
+ }
1133
+ }
1134
+ if (missingFiles.length) {
1135
+ throw new Error("missing files");
1136
+ }
1137
+ const _paths = {
1138
+ require: [],
1139
+ import: []
1140
+ };
1141
+ for (const [exportPath, exp] of Object.entries(ctx.exports || {})) {
1142
+ if (!exp._exported)
1143
+ continue;
1144
+ if (exp.require)
1145
+ _paths.require.push(exportPath);
1146
+ if (exp.import)
1147
+ _paths.import.push(exportPath);
1148
+ }
1149
+ const external = Object.keys(pkg.dependencies || {}).concat(
1150
+ Object.keys(pkg.devDependencies || {})
1151
+ );
1152
+ if (_paths.import.length) {
1153
+ const code = _paths.import.map((id) => `import('${id}')`).join("\n");
1154
+ try {
1155
+ const esbuildResult = await esbuild$1.build({
1156
+ external,
1157
+ stdin: {
1158
+ contents: code,
1159
+ loader: "js",
1160
+ resolveDir: cwd
1161
+ },
1162
+ format: "esm",
1163
+ bundle: true,
1164
+ logLevel: "silent",
1165
+ outfile: "/dev/null",
1166
+ platform: "node"
1167
+ });
1168
+ if (esbuildResult.warnings.length > 0) {
1169
+ console.warn(...esbuildResult.warnings);
1170
+ }
1171
+ } catch (err) {
1172
+ const { errors } = err;
1173
+ for (const _err of errors) {
1174
+ if (_err.location) {
1175
+ console.log(chalk.red("error"), _err.detail || _err.text);
1176
+ console.log(`${_err.location.line} | ${_err.location.lineText}`);
1177
+ console.log(
1178
+ "in",
1179
+ `./${_err.location.file}:${_err.location.line}:${_err.location.column}`
1180
+ );
1181
+ } else {
1182
+ console.log(_err.detail || _err.text);
1183
+ }
1184
+ console.log();
1185
+ }
1186
+ process.exit(1);
1187
+ }
1188
+ }
1189
+ if (_paths.require.length) {
1190
+ const code = _paths.require.map((id) => `require('${id}')`).join("\n");
1191
+ const esbuildResult = await esbuild$1.build({
1192
+ external,
1193
+ stdin: {
1194
+ contents: code,
1195
+ loader: "js",
1196
+ resolveDir: cwd
1197
+ },
1198
+ format: "cjs",
1199
+ bundle: true,
1200
+ outfile: "/dev/null",
1201
+ platform: "node"
1202
+ });
1203
+ if (esbuildResult.errors.length > 0) {
1204
+ throw new Error(esbuildResult.errors.join(", "));
1205
+ }
1206
+ if (esbuildResult.warnings.length > 0) {
1207
+ console.warn(...esbuildResult.warnings);
1208
+ }
1209
+ }
1210
+ }
1074
1211
  }
1075
1212
 
1076
1213
  function _resolveWatchTasks(ctx) {
1077
1214
  var _a, _b, _c, _d, _e;
1078
1215
  const { cwd, pkg, target } = ctx;
1216
+ const esTarget = _resolveEsTarget(ctx);
1079
1217
  const tasks = [];
1080
1218
  const exports = Object.entries(ctx.exports || {}).map(
1081
1219
  ([_path, exp]) => ({ _path, ...exp })
@@ -1091,7 +1229,7 @@ function _resolveWatchTasks(ctx) {
1091
1229
  entries: [entry],
1092
1230
  runtime,
1093
1231
  format,
1094
- target: target[runtime]
1232
+ target: [esTarget].concat(target[runtime])
1095
1233
  };
1096
1234
  } else {
1097
1235
  rollupTasks[buildId].entries.push(entry);
@@ -1105,8 +1243,8 @@ function _resolveWatchTasks(ctx) {
1105
1243
  type: "watch:dts",
1106
1244
  importId,
1107
1245
  exportPath: exp._path,
1108
- source: exp.source,
1109
- output: exp.types
1246
+ sourcePath: exp.source,
1247
+ targetPath: exp.types
1110
1248
  };
1111
1249
  }
1112
1250
  }