@sanity/pkg-utils 1.4.0 → 1.5.1

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 (52) 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-3822350b.cjs} +10 -9
  6. package/dist/_build-3822350b.cjs.map +1 -0
  7. package/dist/{_buildAction-586dfb5f.cjs → _buildAction-38ca33eb.cjs} +7 -6
  8. package/dist/{_buildAction-586dfb5f.cjs.map → _buildAction-38ca33eb.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-a8139a06.cjs} +59 -18
  14. package/dist/_index-a8139a06.cjs.map +1 -0
  15. package/dist/{_watch-0623c005.cjs → _watch-4068cb96.cjs} +9 -7
  16. package/dist/_watch-4068cb96.cjs.map +1 -0
  17. package/dist/{_watchAction-4b8d7301.cjs → _watchAction-818342dd.cjs} +5 -4
  18. package/dist/{_watchAction-4b8d7301.cjs.map → _watchAction-818342dd.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 +9 -5
  24. package/dist/index.js +168 -31
  25. package/dist/index.js.map +1 -1
  26. package/package.json +16 -4
  27. package/src/cli/checkAction.ts +9 -0
  28. package/src/cli/index.ts +3 -2
  29. package/src/node/_core/pkg/_loadPkg.ts +1 -0
  30. package/src/node/_globFiles.ts +1 -1
  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/_rollupTask.ts +6 -4
  42. package/src/node/build.ts +3 -1
  43. package/src/node/check.ts +125 -3
  44. package/dist/__printPackageTree-793a302b.cjs.map +0 -1
  45. package/dist/__resolveBuildContext-1b29cff2.cjs.map +0 -1
  46. package/dist/_build-08236974.cjs.map +0 -1
  47. package/dist/_check-9d180462.cjs +0 -16
  48. package/dist/_check-9d180462.cjs.map +0 -1
  49. package/dist/_index-c5bd1bc8.cjs.map +0 -1
  50. package/dist/_statusAction-385b72dd.cjs.map +0 -1
  51. package/dist/_watch-0623c005.cjs.map +0 -1
  52. 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,8 +26,9 @@ 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
- import { globby } from 'globby';
31
+ import globby from 'globby';
30
32
  import chokidar from 'chokidar';
31
33
 
32
34
  const _DEFAULTS = {
@@ -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;
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,7 +736,7 @@ function _resolveRollupConfig(ctx, buildTask) {
695
736
  }),
696
737
  json(),
697
738
  esbuild({
698
- minify: (config == null ? void 0 : config.minify) ?? true,
739
+ minify: (_b = config == null ? void 0 : config.minify) != null ? _b : true,
699
740
  jsx: "transform",
700
741
  jsxFactory: "React.createElement",
701
742
  jsxFragment: "React.Fragment",
@@ -713,7 +754,7 @@ function _resolveRollupConfig(ctx, buildTask) {
713
754
  entryFileNames: () => `[name]${outputExt}`,
714
755
  format,
715
756
  exports: "auto",
716
- sourcemap: (config == null ? void 0 : config.sourcemap) ?? true
757
+ sourcemap: (_c = config == null ? void 0 : config.sourcemap) != null ? _c : true
717
758
  }
718
759
  };
719
760
  }
@@ -726,7 +767,7 @@ const _rollupTask = {
726
767
  _execPromise(ctx, task).then((result) => {
727
768
  observer.next(result);
728
769
  observer.complete();
729
- }, observer.error);
770
+ }).catch((err) => observer.error(err));
730
771
  });
731
772
  },
732
773
  complete: () => {
@@ -824,7 +865,7 @@ function _getFilesize(file) {
824
865
  return prettyBytes(stats.size);
825
866
  }
826
867
 
827
- function _getFileExists(file) {
868
+ function _fileExists(file) {
828
869
  try {
829
870
  fs$1.accessSync(file);
830
871
  return true;
@@ -834,7 +875,7 @@ function _getFileExists(file) {
834
875
  }
835
876
  function _getFileInfo(cwd, filePath) {
836
877
  const p = path.resolve(cwd, filePath);
837
- const exists = _getFileExists(p);
878
+ const exists = _fileExists(p);
838
879
  const size = exists ? _getFilesize(p) : void 0;
839
880
  return { exists, size };
840
881
  }
@@ -850,7 +891,7 @@ function _printPackageTree(ctx) {
850
891
  function _fileInfo(file) {
851
892
  const info = _getFileInfo(cwd, file);
852
893
  if (!info.size) {
853
- return chalk.gray(file);
894
+ return `${chalk.gray(file)} ${chalk.red("does not exist")}`;
854
895
  }
855
896
  return `${file} ${chalk.gray(info.size)}`;
856
897
  }
@@ -953,6 +994,7 @@ function _resolveNodeTarget(versions) {
953
994
  }
954
995
 
955
996
  async function _resolveBuildContext(options) {
997
+ var _a;
956
998
  const { config, cwd, pkg, tsconfig: tsconfigPath } = options;
957
999
  const tsconfig = await _loadTSConfig({ cwd, tsconfigPath });
958
1000
  const targetVersions = _resolveBrowserslistVersions(pkg.browserslist || _DEFAULTS.browserslist);
@@ -1007,7 +1049,7 @@ async function _resolveBuildContext(options) {
1007
1049
  },
1008
1050
  pkg,
1009
1051
  src: path.relative(cwd, srcPath),
1010
- runtime: (config == null ? void 0 : config.runtime) ?? "*",
1052
+ runtime: (_a = config == null ? void 0 : config.runtime) != null ? _a : "*",
1011
1053
  target,
1012
1054
  ts: {
1013
1055
  config: tsconfig,
@@ -1055,7 +1097,8 @@ async function build(options) {
1055
1097
  } catch (err) {
1056
1098
  spinner.error();
1057
1099
  if (err instanceof Error) {
1058
- ctx.logger.error(err.message.replaceAll(cwd, "."));
1100
+ const RE_CWD = new RegExp(`${cwd}`, "g");
1101
+ ctx.logger.error(err.message.replace(RE_CWD, "."));
1059
1102
  ctx.logger.log();
1060
1103
  }
1061
1104
  handler.error(ctx, task, err);
@@ -1066,16 +1109,110 @@ async function build(options) {
1066
1109
  }
1067
1110
 
1068
1111
  async function check(options) {
1069
- const { cwd, tsconfig = "tsconfig.json" } = options;
1112
+ const { cwd, strict, tsconfig = "tsconfig.json" } = options;
1070
1113
  const pkg = await _loadPkgWithReporting({ cwd });
1071
1114
  const config = await _loadConfig({ cwd });
1072
1115
  const ctx = await _resolveBuildContext({ config, cwd, pkg, tsconfig });
1073
1116
  _printPackageTree(ctx);
1117
+ if (strict) {
1118
+ const missingFiles = [];
1119
+ for (const [, exp] of Object.entries(ctx.exports || {})) {
1120
+ if (exp.source && !_fileExists(path.resolve(cwd, exp.source))) {
1121
+ missingFiles.push(exp.source);
1122
+ }
1123
+ if (exp.require && !_fileExists(path.resolve(cwd, exp.require))) {
1124
+ missingFiles.push(exp.require);
1125
+ }
1126
+ if (exp.import && !_fileExists(path.resolve(cwd, exp.import))) {
1127
+ missingFiles.push(exp.import);
1128
+ }
1129
+ if (exp.types && !_fileExists(path.resolve(cwd, exp.types))) {
1130
+ missingFiles.push(exp.types);
1131
+ }
1132
+ }
1133
+ if (missingFiles.length) {
1134
+ throw new Error("missing files");
1135
+ }
1136
+ const _paths = {
1137
+ require: [],
1138
+ import: []
1139
+ };
1140
+ for (const [exportPath, exp] of Object.entries(ctx.exports || {})) {
1141
+ if (!exp._exported)
1142
+ continue;
1143
+ if (exp.require)
1144
+ _paths.require.push(exportPath);
1145
+ if (exp.import)
1146
+ _paths.import.push(exportPath);
1147
+ }
1148
+ const external = Object.keys(pkg.dependencies || {}).concat(
1149
+ Object.keys(pkg.devDependencies || {})
1150
+ );
1151
+ if (_paths.import.length) {
1152
+ const code = _paths.import.map((id) => `import('${id}')`).join("\n");
1153
+ try {
1154
+ const esbuildResult = await esbuild$1.build({
1155
+ external,
1156
+ stdin: {
1157
+ contents: code,
1158
+ loader: "js",
1159
+ resolveDir: cwd
1160
+ },
1161
+ format: "esm",
1162
+ bundle: true,
1163
+ logLevel: "silent",
1164
+ outfile: "/dev/null",
1165
+ platform: "node"
1166
+ });
1167
+ if (esbuildResult.warnings.length > 0) {
1168
+ console.warn(...esbuildResult.warnings);
1169
+ }
1170
+ } catch (err) {
1171
+ const { errors } = err;
1172
+ for (const _err of errors) {
1173
+ if (_err.location) {
1174
+ console.log(chalk.red("error"), _err.detail || _err.text);
1175
+ console.log(`${_err.location.line} | ${_err.location.lineText}`);
1176
+ console.log(
1177
+ "in",
1178
+ `./${_err.location.file}:${_err.location.line}:${_err.location.column}`
1179
+ );
1180
+ } else {
1181
+ console.log(_err.detail || _err.text);
1182
+ }
1183
+ console.log();
1184
+ }
1185
+ process.exit(1);
1186
+ }
1187
+ }
1188
+ if (_paths.require.length) {
1189
+ const code = _paths.require.map((id) => `require('${id}')`).join("\n");
1190
+ const esbuildResult = await esbuild$1.build({
1191
+ external,
1192
+ stdin: {
1193
+ contents: code,
1194
+ loader: "js",
1195
+ resolveDir: cwd
1196
+ },
1197
+ format: "cjs",
1198
+ bundle: true,
1199
+ outfile: "/dev/null",
1200
+ platform: "node"
1201
+ });
1202
+ if (esbuildResult.errors.length > 0) {
1203
+ throw new Error(esbuildResult.errors.join(", "));
1204
+ }
1205
+ if (esbuildResult.warnings.length > 0) {
1206
+ console.warn(...esbuildResult.warnings);
1207
+ }
1208
+ }
1209
+ }
1074
1210
  }
1075
1211
 
1076
1212
  function _resolveWatchTasks(ctx) {
1077
1213
  var _a, _b, _c, _d, _e;
1078
1214
  const { cwd, pkg, target } = ctx;
1215
+ const esTarget = _resolveEsTarget(ctx);
1079
1216
  const tasks = [];
1080
1217
  const exports = Object.entries(ctx.exports || {}).map(
1081
1218
  ([_path, exp]) => ({ _path, ...exp })
@@ -1091,7 +1228,7 @@ function _resolveWatchTasks(ctx) {
1091
1228
  entries: [entry],
1092
1229
  runtime,
1093
1230
  format,
1094
- target: target[runtime]
1231
+ target: [esTarget].concat(target[runtime])
1095
1232
  };
1096
1233
  } else {
1097
1234
  rollupTasks[buildId].entries.push(entry);
@@ -1105,8 +1242,8 @@ function _resolveWatchTasks(ctx) {
1105
1242
  type: "watch:dts",
1106
1243
  importId,
1107
1244
  exportPath: exp._path,
1108
- source: exp.source,
1109
- output: exp.types
1245
+ sourcePath: exp.source,
1246
+ targetPath: exp.types
1110
1247
  };
1111
1248
  }
1112
1249
  }