@sanity/pkg-utils 1.17.2 → 1.18.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 (30) hide show
  1. package/dist/_chunks/_handleError-869dec25.js +0 -5
  2. package/dist/_chunks/_handleError-869dec25.js.map +1 -1
  3. package/dist/_chunks/_resolveBuildContext-7ca7e64e.js +3 -122
  4. package/dist/_chunks/_resolveBuildContext-7ca7e64e.js.map +1 -1
  5. package/dist/_chunks/{build-072e58ec.js → build-f39a3550.js} +2 -46
  6. package/dist/_chunks/{build-072e58ec.js.map → build-f39a3550.js.map} +1 -1
  7. package/dist/_chunks/{buildAction-35aab706.js → buildAction-8f449d1d.js} +5 -35
  8. package/dist/_chunks/{buildAction-35aab706.js.map → buildAction-8f449d1d.js.map} +1 -1
  9. package/dist/_chunks/check-87cbb6cc.js +0 -55
  10. package/dist/_chunks/check-87cbb6cc.js.map +1 -1
  11. package/dist/_chunks/checkAction-e7e455d4.js +0 -17
  12. package/dist/_chunks/checkAction-e7e455d4.js.map +1 -1
  13. package/dist/_chunks/{index-68bcc7e2.js → index-7a851efa.js} +47 -223
  14. package/dist/_chunks/index-7a851efa.js.map +1 -0
  15. package/dist/_chunks/{watch-e09a4a66.js → watch-f6cf9246.js} +2 -57
  16. package/dist/_chunks/{watch-e09a4a66.js.map → watch-f6cf9246.js.map} +1 -1
  17. package/dist/_chunks/{watchAction-c64a95c7.js → watchAction-4cf253a0.js} +5 -38
  18. package/dist/_chunks/{watchAction-c64a95c7.js.map → watchAction-4cf253a0.js.map} +1 -1
  19. package/dist/cli.js +3 -6
  20. package/dist/cli.js.map +1 -1
  21. package/dist/index.esm.js +56 -396
  22. package/dist/index.esm.js.map +1 -1
  23. package/dist/index.js +5 -43
  24. package/dist/index.js.map +1 -1
  25. package/package.json +3 -1
  26. package/src/node/_tasks/dts/_doExtract.ts +2 -8
  27. package/src/node/_tasks/dts/_extractModuleBlocks.ts +45 -0
  28. package/src/node/_tasks/dts/_extractTypes.ts +11 -1
  29. package/dist/_chunks/index-68bcc7e2.js.map +0 -1
  30. package/src/node/_tasks/dts/_declareModuleFix.ts +0 -98
package/dist/index.esm.js CHANGED
@@ -1,15 +1,9 @@
1
1
  const _excluded = ["_path"];
2
-
3
2
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
4
-
5
3
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
6
-
7
4
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
8
-
9
5
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
10
-
11
6
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
-
13
7
  import path from 'path';
14
8
  import { register } from 'esbuild-register/dist/node';
15
9
  import pkgUp from 'pkg-up';
@@ -27,6 +21,8 @@ import mkdirp from 'mkdirp';
27
21
  import prettier from 'prettier';
28
22
  import { TSDocConfigFile } from '@microsoft/tsdoc-config';
29
23
  import { parse } from 'jsonc-parser';
24
+ import { parse as parse$1, print } from 'recast';
25
+ import typeScriptParser from 'recast/parsers/typescript';
30
26
  import { rollup, watch as watch$1 } from 'rollup';
31
27
  import alias from '@rollup/plugin-alias';
32
28
  import { getBabelOutputPlugin } from '@rollup/plugin-babel';
@@ -56,32 +52,25 @@ const _MODULE_EXT = {
56
52
  const _DEFAULTS = {
57
53
  browserslist: ["> 0.2% and supports es6-module and supports es6-module-dynamic-import", "not dead", "not IE 11", "maintained node versions"]
58
54
  };
59
-
60
55
  function _isRecord(value) {
61
56
  return Boolean(value) && !Array.isArray(value) && typeof value === "object";
62
57
  }
63
-
64
58
  const CONFIG_FILE_NAMES = ["package.config.ts", "package.config.js", "package.config.cjs", "package.config.mjs"];
65
-
66
59
  async function _findConfigFile(cwd) {
67
60
  const pkgJsonPath = findConfig("package.json", {
68
61
  cwd
69
62
  });
70
63
  if (!pkgJsonPath) return void 0;
71
64
  const pkgPath = path.dirname(pkgJsonPath);
72
-
73
65
  for (const fileName of CONFIG_FILE_NAMES) {
74
66
  const configPath = path.resolve(pkgPath, fileName);
75
67
  const exists = await _fileExists$1(configPath);
76
-
77
68
  if (exists) {
78
69
  return configPath;
79
70
  }
80
71
  }
81
-
82
72
  return void 0;
83
73
  }
84
-
85
74
  async function _fileExists$1(filePath) {
86
75
  try {
87
76
  await stat(filePath);
@@ -90,7 +79,6 @@ async function _fileExists$1(filePath) {
90
79
  return false;
91
80
  }
92
81
  }
93
-
94
82
  async function _loadConfig(options) {
95
83
  const {
96
84
  cwd
@@ -101,45 +89,35 @@ async function _loadConfig(options) {
101
89
  if (!pkgPath) return void 0;
102
90
  const root = path.dirname(pkgPath);
103
91
  const configFile = await _findConfigFile(root);
104
-
105
92
  if (!configFile) {
106
93
  return void 0;
107
94
  }
108
-
109
95
  if (!configFile.startsWith(cwd)) {
110
96
  return void 0;
111
97
  }
112
-
113
98
  try {
114
99
  const {
115
100
  unregister
116
101
  } = register({
117
102
  extensions: [".js", ".mjs", ".ts"]
118
103
  });
119
-
120
104
  const mod = require(configFile);
121
-
122
105
  unregister();
123
106
  return (mod == null ? void 0 : mod.default) || mod || void 0;
124
107
  } catch (_) {
125
108
  return void 0;
126
109
  }
127
110
  }
128
-
129
111
  function _resolveConfigProperty(prop, initialValue) {
130
112
  if (!prop) return initialValue;
131
-
132
113
  if (typeof prop === "function") {
133
114
  return prop(initialValue);
134
115
  }
135
-
136
116
  return prop;
137
117
  }
138
-
139
118
  function defineConfig(configOptions) {
140
119
  return configOptions;
141
120
  }
142
-
143
121
  const pkgSchema = z.object({
144
122
  type: z.optional(z.enum(["commonjs", "module"])),
145
123
  name: z.string(),
@@ -173,14 +151,12 @@ const pkgSchema = z.object({
173
151
  })]))),
174
152
  browserslist: z.optional(z.array(z.string()))
175
153
  });
176
-
177
154
  function _validatePkg(input) {
178
155
  const pkg = pkgSchema.parse(input);
179
156
  return _objectSpread(_objectSpread({}, pkg), {}, {
180
157
  type: pkg.type || "commonjs"
181
158
  });
182
159
  }
183
-
184
160
  async function _loadPkg(options) {
185
161
  const {
186
162
  cwd
@@ -192,7 +168,6 @@ async function _loadPkg(options) {
192
168
  const buf = await fs.readFile(pkgPath);
193
169
  return _validatePkg(JSON.parse(buf.toString()));
194
170
  }
195
-
196
171
  async function _loadPkgWithReporting(options) {
197
172
  try {
198
173
  return await _loadPkg(options);
@@ -206,47 +181,37 @@ async function _loadPkgWithReporting(options) {
206
181
  } else {
207
182
  console.error(err);
208
183
  }
209
-
210
184
  process.exit(1);
211
185
  }
212
186
  }
213
-
214
187
  function _formatPath(segments) {
215
188
  return segments.map((s, idx) => {
216
189
  if (idx === 0) return s;
217
-
218
190
  if (typeof s === "number") {
219
191
  return "[".concat(s, "]");
220
192
  }
221
-
222
193
  if (s.startsWith(".")) {
223
194
  return "[\"".concat(s, "\"]");
224
195
  }
225
-
226
196
  return ".".concat(s);
227
197
  }).join("");
228
198
  }
229
-
230
199
  function _validateExports(_exports, options) {
231
200
  const {
232
201
  pkg
233
202
  } = options;
234
203
  const ext = _MODULE_EXT[pkg.type];
235
204
  const errors = [];
236
-
237
205
  for (const exp of _exports) {
238
206
  if (exp.require && !exp.require.endsWith(ext.commonjs)) {
239
207
  errors.push("package.json with `type: \"".concat(pkg.type, "\"` - `exports[\"").concat(exp._path, "\"].require` must end with \"").concat(ext.commonjs, "\""));
240
208
  }
241
-
242
209
  if (exp.import && !exp.import.endsWith(ext.esm)) {
243
210
  errors.push("package.json with `type: \"".concat(pkg.type, "\"` - `exports[\"").concat(exp._path, "\"].import` must end with \"").concat(ext.esm, "\""));
244
211
  }
245
212
  }
246
-
247
213
  return errors;
248
214
  }
249
-
250
215
  function _parseExports(options) {
251
216
  const {
252
217
  pkg,
@@ -268,12 +233,10 @@ function _parseExports(options) {
268
233
  };
269
234
  const extraExports = [];
270
235
  const errors = [];
271
-
272
236
  if (pkg.exports) {
273
237
  if (strict && !pkg.exports["./package.json"]) {
274
238
  errors.push('package.json: `exports["./package.json"] must be declared.');
275
239
  }
276
-
277
240
  for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {
278
241
  if (exportPath.endsWith(".json")) {
279
242
  if (exportPath === "./package.json") {
@@ -286,26 +249,21 @@ function _parseExports(options) {
286
249
  if (exportEntry.require && rootExport.require && exportEntry.require !== rootExport.require) {
287
250
  errors.push('package.json: mismatch between "main" and "exports.require". These must be equal.');
288
251
  }
289
-
290
252
  if (exportEntry.import && rootExport.import && exportEntry.import !== rootExport.import) {
291
253
  errors.push('package.json: mismatch between "module" and "exports.import" These must be equal.');
292
254
  }
293
-
294
255
  if (exportEntry.types && rootExport.types && exportEntry.types !== rootExport.types) {
295
256
  errors.push('package.json: mismatch between "types" and "exports.types". These must be equal.');
296
257
  }
297
-
298
258
  if (exportEntry.source && rootExport.source && exportEntry.source !== rootExport.source) {
299
259
  errors.push('package.json: mismatch between "source" and "exports.source". These must be equal.');
300
260
  }
301
-
302
261
  Object.assign(rootExport, exportEntry);
303
262
  } else {
304
263
  const extraExport = _objectSpread({
305
264
  _exported: true,
306
265
  _path: exportPath
307
266
  }, exportEntry);
308
-
309
267
  extraExports.push(extraExport);
310
268
  }
311
269
  } else {
@@ -313,37 +271,29 @@ function _parseExports(options) {
313
271
  }
314
272
  }
315
273
  }
316
-
317
274
  const _exports = [rootExport, ...extraExports];
318
275
  errors.push(..._validateExports(_exports, {
319
276
  pkg
320
277
  }));
321
-
322
278
  if (errors.length) {
323
279
  throw new Error("\n- " + errors.join("\n- "));
324
280
  }
325
-
326
281
  return _exports;
327
282
  }
328
-
329
283
  async function _loadTSConfig(options) {
330
284
  const {
331
285
  cwd,
332
286
  tsconfigPath
333
287
  } = options;
334
288
  const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
335
-
336
289
  if (!configPath) {
337
290
  throw new Error("could not find a valid '".concat(tsconfigPath, "'"));
338
291
  }
339
-
340
292
  const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
341
293
  return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
342
294
  }
343
-
344
295
  function _resolveBuildTasks(ctx) {
345
296
  var _a, _b, _c, _d, _e;
346
-
347
297
  const {
348
298
  config,
349
299
  cwd,
@@ -363,10 +313,8 @@ function _resolveBuildTasks(ctx) {
363
313
  entries: []
364
314
  };
365
315
  const rollupTasks = {};
366
-
367
316
  function _addRollupTaskEntry(format, runtime, entry) {
368
317
  const buildId = "".concat(format, ":").concat(runtime);
369
-
370
318
  if (rollupTasks[buildId]) {
371
319
  rollupTasks[buildId].entries.push(entry);
372
320
  } else {
@@ -380,10 +328,8 @@ function _resolveBuildTasks(ctx) {
380
328
  };
381
329
  }
382
330
  }
383
-
384
331
  for (const exp of exports) {
385
332
  const importId = path.join(pkg.name, exp._path);
386
-
387
333
  if (exp.types) {
388
334
  dtsTask.entries.push({
389
335
  importId,
@@ -393,56 +339,46 @@ function _resolveBuildTasks(ctx) {
393
339
  });
394
340
  }
395
341
  }
396
-
397
342
  if (dtsTask.entries.length) {
398
343
  tasks.push(dtsTask);
399
344
  }
400
-
401
345
  if (!ctx.emitDeclarationOnly) {
402
346
  for (const exp of exports) {
403
347
  const output = exp.require;
404
348
  if (!output) continue;
405
-
406
349
  _addRollupTaskEntry("commonjs", ctx.runtime, {
407
350
  path: exp._path,
408
351
  source: exp.source,
409
352
  output
410
353
  });
411
354
  }
412
-
413
355
  for (const exp of exports) {
414
356
  const output = exp.import;
415
357
  if (!output) continue;
416
-
417
358
  _addRollupTaskEntry("esm", ctx.runtime, {
418
359
  path: exp._path,
419
360
  source: exp.source,
420
361
  output
421
362
  });
422
363
  }
423
-
424
364
  for (const exp of exports) {
425
365
  const output = (_a = exp.browser) == null ? void 0 : _a.require;
426
366
  if (!output) continue;
427
-
428
367
  _addRollupTaskEntry("commonjs", "browser", {
429
368
  path: exp._path,
430
369
  source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
431
370
  output
432
371
  });
433
372
  }
434
-
435
373
  for (const exp of exports) {
436
374
  const output = (_c = exp.browser) == null ? void 0 : _c.import;
437
375
  if (!output) continue;
438
-
439
376
  _addRollupTaskEntry("esm", "browser", {
440
377
  path: exp._path,
441
378
  source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
442
379
  output
443
380
  });
444
381
  }
445
-
446
382
  for (const bundle of bundles) {
447
383
  if (bundle.require) {
448
384
  _addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
@@ -451,7 +387,6 @@ function _resolveBuildTasks(ctx) {
451
387
  output: bundle.require
452
388
  });
453
389
  }
454
-
455
390
  if (bundle.import) {
456
391
  _addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
457
392
  path: "__bundle__",
@@ -460,14 +395,11 @@ function _resolveBuildTasks(ctx) {
460
395
  });
461
396
  }
462
397
  }
463
-
464
398
  tasks.push(...Object.values(rollupTasks));
465
-
466
399
  if (config == null ? void 0 : config.legacyExports) {
467
400
  for (const exp of exports) {
468
401
  if (exp._exported && exp._path !== ".") {
469
402
  const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
470
-
471
403
  if (relativeTargetPath) {
472
404
  fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
473
405
  }
@@ -475,60 +407,47 @@ function _resolveBuildTasks(ctx) {
475
407
  }
476
408
  }
477
409
  }
478
-
479
410
  return tasks;
480
411
  }
481
-
482
412
  function _printExtractMessages(ctx, messages) {
483
413
  const {
484
414
  cwd,
485
415
  logger
486
416
  } = ctx;
487
417
  const warnings = messages.filter(msg => msg.logLevel === "warning");
488
-
489
418
  if (warnings.length) {
490
419
  logger.log();
491
420
  }
492
-
493
421
  for (const msg of warnings) {
494
422
  const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
495
-
496
423
  if (msg.messageId === "TS6307") {
497
424
  continue;
498
425
  }
499
-
500
426
  logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.yellow("warning"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
501
427
  }
502
-
503
428
  const errors = messages.filter(msg => msg.logLevel === "error");
504
-
505
429
  if (!warnings.length && errors.length) {
506
430
  logger.log("");
507
431
  }
508
-
509
432
  for (const msg of errors) {
510
433
  const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
511
434
  logger.log(["".concat(chalk.cyan(sourceFilePath || "?")), ":".concat(chalk.yellow(msg.sourceFileLine), ":").concat(chalk.yellow(msg.sourceFileColumn)), " - ".concat(chalk.red("error"), " ").concat(chalk.gray(msg.messageId), "\n"), msg.text, "\n"].join(""));
512
435
  }
513
-
514
436
  if (errors.length) {
515
437
  process.exit(1);
516
438
  }
517
439
  }
518
-
519
440
  const formatHost = {
520
441
  getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
521
442
  getNewLine: () => ts.sys.newLine,
522
443
  getCanonicalFileName: ts.sys.useCaseSensitiveFileNames ? f => f : f => f.toLowerCase()
523
444
  };
524
-
525
445
  async function _buildTypes(options) {
526
446
  const {
527
447
  outDir,
528
448
  tsconfig,
529
449
  strict = false
530
450
  } = options;
531
-
532
451
  const compilerOptions = _objectSpread(_objectSpread({}, tsconfig.options), {}, {
533
452
  declaration: true,
534
453
  declarationDir: outDir,
@@ -536,7 +455,6 @@ async function _buildTypes(options) {
536
455
  noEmit: false,
537
456
  outDir
538
457
  });
539
-
540
458
  const program = ts.createProgram(tsconfig.fileNames, compilerOptions);
541
459
  const emitResult = program.emit();
542
460
  const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
@@ -552,108 +470,22 @@ async function _buildTypes(options) {
552
470
  console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
553
471
  }
554
472
  });
555
-
556
473
  if (emitResult.emitSkipped) {
557
474
  const errors = allDiagnostics.filter(diag => diag.category === ts.DiagnosticCategory.Error);
558
-
559
475
  if (errors.length) {
560
476
  console.error(ts.formatDiagnostics(errors, formatHost));
561
-
562
477
  if (strict) {
563
478
  throw new Error("failed to compile TypeScript definitions");
564
479
  }
565
480
  }
566
481
  }
567
482
  }
568
-
569
- async function _appendModuleBlocks(_ref2) {
570
- let {
571
- tsOutDir,
572
- extractResult,
573
- extractTypesOutFile
574
- } = _ref2;
575
- const moduleBlocks = await _extractModuleBlocksFromTypes({
576
- tsOutDir,
577
- extractResult
578
- });
579
-
580
- if (moduleBlocks.length) {
581
- await fs.appendFile(extractTypesOutFile, "\n" + moduleBlocks.join("\n\n"));
582
- }
583
- }
584
-
585
- async function _extractModuleBlocksFromTypes(_ref3) {
586
- let {
587
- tsOutDir,
588
- extractResult
589
- } = _ref3;
590
- const moduleBlocks = [];
591
- const program = extractResult.compilerState.program;
592
- const allProgramFiles = [...program.getSourceFiles()];
593
- const sourceFiles = allProgramFiles.filter(sourceFile => sourceFile.fileName.includes(tsOutDir));
594
-
595
- for (const sourceFile of sourceFiles) {
596
- if (sourceFile.text.includes("declare module")) {
597
- moduleBlocks.push(..._extractModuleBlocks(sourceFile.text));
598
- }
599
- }
600
-
601
- return moduleBlocks;
602
- }
603
-
604
- function _extractModuleBlocks(fileContent) {
605
- var _a;
606
-
607
- const moduleBlocks = [];
608
- let moduleIndentLevel = 0;
609
- let insideComment = false;
610
- let moduleLines = [];
611
- const lines = fileContent.split("\n");
612
-
613
- for (const line of lines) {
614
- if (insideComment && line.includes("*/")) {
615
- insideComment = false;
616
- } else if (!insideComment && line.includes("/*") && line.includes("*/")) {
617
- continue;
618
- } else if (!insideComment && line.includes("/*")) {
619
- insideComment = true;
620
- }
621
-
622
- if (insideComment) {
623
- continue;
624
- }
625
-
626
- if (!moduleLines.length) {
627
- const isModuleDeclaration = (_a = line.match(/^\s*declare module.+$/)) == null ? void 0 : _a.length;
628
- const moduleIndex = line.indexOf("declare module");
629
- const isModuleStart = isModuleDeclaration && moduleIndex > -1;
630
-
631
- if (isModuleStart) {
632
- moduleIndentLevel = moduleIndex;
633
- moduleLines = [line];
634
- }
635
- } else {
636
- moduleLines.push(line);
637
- const blockEndIndex = line.indexOf("}");
638
-
639
- if (blockEndIndex === moduleIndentLevel) {
640
- moduleBlocks.push(moduleLines.map(l => l.substring(moduleIndentLevel, l.length)).join("\n"));
641
- moduleLines = [];
642
- }
643
- }
644
- }
645
-
646
- return moduleBlocks;
647
- }
648
-
649
483
  class _DtsError extends Error {
650
484
  constructor(message, messages) {
651
485
  super(message);
652
486
  this.messages = messages;
653
487
  }
654
-
655
488
  }
656
-
657
489
  function _createApiExtractorConfig(options) {
658
490
  const {
659
491
  distPath,
@@ -688,16 +520,13 @@ function _createApiExtractorConfig(options) {
688
520
  projectFolder
689
521
  };
690
522
  }
691
-
692
523
  async function _createTSDocConfig(opts) {
693
524
  const {
694
525
  customTags
695
526
  } = opts;
696
-
697
527
  if (customTags.length === 0) {
698
528
  return void 0;
699
529
  }
700
-
701
530
  const tsDocBaseBuf = await readFile(require.resolve("@microsoft/api-extractor/extends/tsdoc-base.json"));
702
531
  const tsDocBaseConfig = parse(tsDocBaseBuf.toString());
703
532
  const tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(customTags.map(t => ({
@@ -705,37 +534,52 @@ async function _createTSDocConfig(opts) {
705
534
  syntaxKind: t.syntaxKind,
706
535
  allowMultiple: t.allowMultiple
707
536
  })));
708
-
709
537
  const supportForTags = _objectSpread({}, tsDocBaseConfig.supportForTags);
710
-
711
538
  for (const customTag of customTags) {
712
539
  supportForTags["@".concat(customTag.name)] = true;
713
540
  }
714
-
715
541
  return TSDocConfigFile.loadFromObject(_objectSpread(_objectSpread({}, tsDocBaseConfig), {}, {
716
542
  noStandardTags: false,
717
543
  tagDefinitions,
718
544
  supportForTags
719
545
  }));
720
546
  }
721
-
547
+ async function _extractModuleBlocksFromTypes(_ref2) {
548
+ let {
549
+ tsOutDir,
550
+ extractResult
551
+ } = _ref2;
552
+ const program = extractResult.compilerState.program;
553
+ const moduleBlocks = [];
554
+ const allProgramFiles = [...program.getSourceFiles()];
555
+ const sourceFiles = allProgramFiles.filter(sourceFile => sourceFile.fileName.includes(tsOutDir));
556
+ for (const sourceFile of sourceFiles) {
557
+ if (sourceFile.text.includes("declare module")) {
558
+ moduleBlocks.push(..._extractModuleBlocks(sourceFile.text));
559
+ }
560
+ }
561
+ return moduleBlocks;
562
+ }
563
+ function _extractModuleBlocks(fileContent) {
564
+ const ast = parse$1(fileContent, {
565
+ parser: typeScriptParser
566
+ });
567
+ return ast.program.body.filter(node => node.type === "TSModuleDeclaration").map(node => print(node).code);
568
+ }
722
569
  const _LOG_LEVELS = {
723
570
  error: "error",
724
571
  info: "info",
725
572
  off: "none",
726
573
  warn: "warning"
727
574
  };
728
-
729
575
  function _getExtractMessagesConfig(options) {
730
576
  const {
731
577
  rules
732
578
  } = options;
733
-
734
579
  function _ruleToLogLevel(key, defaultLevel) {
735
580
  const r = rules == null ? void 0 : rules[key];
736
581
  return r ? _LOG_LEVELS[r] : defaultLevel || "warning";
737
582
  }
738
-
739
583
  return {
740
584
  compilerMessageReporting: {
741
585
  default: {
@@ -788,7 +632,6 @@ function _getExtractMessagesConfig(options) {
788
632
  }
789
633
  };
790
634
  }
791
-
792
635
  async function _extractTypes(options) {
793
636
  const {
794
637
  customTags,
@@ -799,6 +642,7 @@ async function _extractTypes(options) {
799
642
  projectPath,
800
643
  rules,
801
644
  sourceTypesPath,
645
+ tmpPath,
802
646
  tsconfigPath
803
647
  } = options;
804
648
  const tsdocConfigFile = await _createTSDocConfig({
@@ -824,18 +668,21 @@ async function _extractTypes(options) {
824
668
  const extractorResult = Extractor.invoke(extractorConfig, {
825
669
  localBuild: true,
826
670
  showVerboseMessages: true,
827
-
828
671
  messageCallback(message) {
829
672
  messages.push(message);
830
673
  message.handled = true;
831
674
  }
832
-
833
675
  });
834
676
  const typesPath = path.resolve(distPath, filePath);
835
677
  const typesBuf = await fs.readFile(typesPath);
836
678
  const prettierConfig = await prettier.resolveConfig(typesPath);
837
679
  await mkdirp(path.dirname(typesPath));
838
- await fs.writeFile(typesPath, prettier.format(typesBuf.toString(), _objectSpread(_objectSpread({}, prettierConfig), {}, {
680
+ const moduleBlocks = await _extractModuleBlocksFromTypes({
681
+ extractResult: extractorResult,
682
+ tsOutDir: tmpPath
683
+ });
684
+ const code = [typesBuf.toString(), ...moduleBlocks].join("\n\n");
685
+ await fs.writeFile(typesPath, prettier.format(code, _objectSpread(_objectSpread({}, prettierConfig), {}, {
839
686
  filepath: typesPath
840
687
  })));
841
688
  files.push({
@@ -847,12 +694,9 @@ async function _extractTypes(options) {
847
694
  messages
848
695
  };
849
696
  }
850
-
851
697
  const rimraf = promisify(rimrafCallback);
852
-
853
698
  async function _doExtract(ctx, task) {
854
699
  var _a, _b;
855
-
856
700
  const {
857
701
  config,
858
702
  cwd,
@@ -860,7 +704,6 @@ async function _doExtract(ctx, task) {
860
704
  strict,
861
705
  ts
862
706
  } = ctx;
863
-
864
707
  if (!ts.config || !ts.configPath) {
865
708
  return {
866
709
  type: "dts",
@@ -868,16 +711,13 @@ async function _doExtract(ctx, task) {
868
711
  results: []
869
712
  };
870
713
  }
871
-
872
714
  const {
873
715
  outDir,
874
716
  rootDir = cwd
875
717
  } = ts.config.options;
876
-
877
718
  if (!outDir) {
878
719
  throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
879
720
  }
880
-
881
721
  const tmpPath = path.resolve(outDir, "__tmp__");
882
722
  await _buildTypes({
883
723
  cwd,
@@ -887,7 +727,6 @@ async function _doExtract(ctx, task) {
887
727
  });
888
728
  const messages = [];
889
729
  const results = [];
890
-
891
730
  for (const entry of task.entries) {
892
731
  const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath;
893
732
  const sourceTypesPath = path.resolve(tmpPath, path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts"));
@@ -896,33 +735,26 @@ async function _doExtract(ctx, task) {
896
735
  const result = await _extractTypes({
897
736
  customTags: (_a = config == null ? void 0 : config.extract) == null ? void 0 : _a.customTags,
898
737
  cwd,
738
+ distPath: outDir,
899
739
  exportPath,
900
740
  files,
901
741
  filePath,
902
742
  projectPath: cwd,
903
743
  rules: (_b = config == null ? void 0 : config.extract) == null ? void 0 : _b.rules,
904
744
  sourceTypesPath,
905
- tsconfigPath: path.resolve(cwd, ts.configPath || "tsconfig.json"),
906
- distPath: outDir
907
- });
908
- await _appendModuleBlocks({
909
- tsOutDir: tmpPath,
910
- extractResult: result.extractorResult,
911
- extractTypesOutFile: path.resolve(outDir, targetPath)
745
+ tmpPath,
746
+ tsconfigPath: path.resolve(cwd, ts.configPath || "tsconfig.json")
912
747
  });
913
748
  messages.push(...result.messages);
914
-
915
749
  if (result.messages.some(msg => msg.logLevel === "error")) {
916
750
  await rimraf(tmpPath);
917
751
  throw new _DtsError("encountered errors when extracting types", result.messages);
918
752
  }
919
-
920
753
  results.push({
921
754
  sourcePath: path.resolve(cwd, entry.sourcePath),
922
755
  filePath: targetPath
923
756
  });
924
757
  }
925
-
926
758
  await rimraf(tmpPath);
927
759
  return {
928
760
  type: "dts",
@@ -930,7 +762,6 @@ async function _doExtract(ctx, task) {
930
762
  results
931
763
  };
932
764
  }
933
-
934
765
  const _dtsTask = {
935
766
  name: (_ctx, task) => ["build type definitions", ...task.entries.map(entry => " ".concat(chalk.blue(entry.importId), ": ").concat(entry.sourcePath, " -> ").concat(entry.targetPath))].join("\n"),
936
767
  exec: (ctx, task) => {
@@ -950,7 +781,6 @@ const _dtsTask = {
950
781
  const {
951
782
  logger
952
783
  } = ctx;
953
-
954
784
  if (err instanceof _DtsError) {
955
785
  _printExtractMessages(ctx, err.messages);
956
786
  } else if (err instanceof Error) {
@@ -972,9 +802,7 @@ const _dtsWatchTask = {
972
802
  const {
973
803
  logger
974
804
  } = ctx;
975
-
976
805
  _printExtractMessages(ctx, result.messages);
977
-
978
806
  logger.warn("watching typescript definitions is currently not supported");
979
807
  logger.log();
980
808
  },
@@ -982,7 +810,6 @@ const _dtsWatchTask = {
982
810
  const {
983
811
  logger
984
812
  } = ctx;
985
-
986
813
  if (err instanceof _DtsError) {
987
814
  _printExtractMessages(ctx, err.messages);
988
815
  } else if (err instanceof Error) {
@@ -990,12 +817,9 @@ const _dtsWatchTask = {
990
817
  }
991
818
  }
992
819
  };
993
-
994
820
  function _resolveRollupConfig(ctx, buildTask) {
995
- var _ref4, _ref7, _ref8, _ref9, _ref10, _ref11;
996
-
821
+ var _ref3, _ref6, _ref7, _ref8, _ref9, _ref10;
997
822
  var _a, _b, _c;
998
-
999
823
  const {
1000
824
  format,
1001
825
  runtime,
@@ -1012,13 +836,11 @@ function _resolveRollupConfig(ctx, buildTask) {
1012
836
  ts
1013
837
  } = ctx;
1014
838
  const outputExt = _MODULE_EXT[pkg.type][format];
1015
- const minify = (_ref4 = config == null ? void 0 : config.minify) !== null && _ref4 !== void 0 ? _ref4 : true;
839
+ const minify = (_ref3 = config == null ? void 0 : config.minify) !== null && _ref3 !== void 0 ? _ref3 : true;
1016
840
  const outDir = path.relative(cwd, distPath);
1017
- const pathAliases = Object.fromEntries(Object.entries(((_a = ts.config) == null ? void 0 : _a.options.paths) || {}).map(_ref5 => {
1018
- let [key, val] = _ref5;
1019
-
841
+ const pathAliases = Object.fromEntries(Object.entries(((_a = ts.config) == null ? void 0 : _a.options.paths) || {}).map(_ref4 => {
842
+ let [key, val] = _ref4;
1020
843
  var _a2;
1021
-
1022
844
  return [key, path.resolve(cwd, ((_a2 = ts.config) == null ? void 0 : _a2.options.baseUrl) || ".", val[0])];
1023
845
  }));
1024
846
  const entries = buildTask.entries.map(entry => {
@@ -1026,13 +848,10 @@ function _resolveRollupConfig(ctx, buildTask) {
1026
848
  name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
1027
849
  });
1028
850
  }, {});
1029
-
1030
851
  const exportIds = _exports && Object.keys(_exports).map(exportPath => path.join(pkg.name, exportPath));
1031
-
1032
852
  const sourcePaths = _exports && Object.values(_exports).map(e => path.resolve(cwd, e.source));
1033
-
1034
- const replacements = Object.fromEntries(Object.entries((config == null ? void 0 : config.define) || {}).map(_ref6 => {
1035
- let [key, val] = _ref6;
853
+ const replacements = Object.fromEntries(Object.entries((config == null ? void 0 : config.define) || {}).map(_ref5 => {
854
+ let [key, val] = _ref5;
1036
855
  return [key, JSON.stringify(val)];
1037
856
  }));
1038
857
  const defaultPlugins = [replace({
@@ -1041,12 +860,10 @@ function _resolveRollupConfig(ctx, buildTask) {
1041
860
  "process.env.PKG_FILE_PATH": arg => {
1042
861
  const sourcePath = "./" + path.relative(cwd, arg);
1043
862
  const entry = entries.find(e => e.source === sourcePath);
1044
-
1045
863
  if (!entry) {
1046
864
  console.error("could not find source entry: ".concat(sourcePath));
1047
865
  return "null";
1048
866
  }
1049
-
1050
867
  return JSON.stringify(path.relative(cwd, path.resolve(outDir, entry.name + outputExt)));
1051
868
  },
1052
869
  "process.env.PKG_FORMAT": JSON.stringify(format),
@@ -1063,10 +880,10 @@ function _resolveRollupConfig(ctx, buildTask) {
1063
880
  esmExternals: false,
1064
881
  extensions: [".js"]
1065
882
  }), json(), esbuild({
1066
- jsx: (_ref7 = config == null ? void 0 : config.jsx) !== null && _ref7 !== void 0 ? _ref7 : "automatic",
1067
- jsxFactory: (_ref8 = config == null ? void 0 : config.jsxFactory) !== null && _ref8 !== void 0 ? _ref8 : "createElement",
1068
- jsxFragment: (_ref9 = config == null ? void 0 : config.jsxFragment) !== null && _ref9 !== void 0 ? _ref9 : "Fragment",
1069
- jsxImportSource: (_ref10 = config == null ? void 0 : config.jsxImportSource) !== null && _ref10 !== void 0 ? _ref10 : "react",
883
+ jsx: (_ref6 = config == null ? void 0 : config.jsx) !== null && _ref6 !== void 0 ? _ref6 : "automatic",
884
+ jsxFactory: (_ref7 = config == null ? void 0 : config.jsxFactory) !== null && _ref7 !== void 0 ? _ref7 : "createElement",
885
+ jsxFragment: (_ref8 = config == null ? void 0 : config.jsxFragment) !== null && _ref8 !== void 0 ? _ref8 : "Fragment",
886
+ jsxImportSource: (_ref9 = config == null ? void 0 : config.jsxImportSource) !== null && _ref9 !== void 0 ? _ref9 : "react",
1070
887
  target,
1071
888
  tsconfig: ctx.ts.configPath || "tsconfig.json"
1072
889
  }), getBabelOutputPlugin({
@@ -1080,11 +897,9 @@ function _resolveRollupConfig(ctx, buildTask) {
1080
897
  comments: (_node, comment) => {
1081
898
  const text = comment.value;
1082
899
  const type = comment.type;
1083
-
1084
900
  if (type == "comment2") {
1085
901
  return /@preserve|@license|@cc_on/i.test(text);
1086
902
  }
1087
-
1088
903
  return false;
1089
904
  }
1090
905
  }
@@ -1098,23 +913,18 @@ function _resolveRollupConfig(ctx, buildTask) {
1098
913
  if (exportIds == null ? void 0 : exportIds.includes(id)) {
1099
914
  return true;
1100
915
  }
1101
-
1102
916
  if (importer && (id.startsWith(".") || id.startsWith("/"))) {
1103
917
  const idPath = path.resolve(path.dirname(importer), id);
1104
-
1105
918
  if (sourcePaths == null ? void 0 : sourcePaths.includes(idPath)) {
1106
919
  logger.warn("detected self-referencing import \u2013 treating as external: ".concat(path.relative(cwd, idPath)));
1107
920
  return true;
1108
921
  }
1109
922
  }
1110
-
1111
923
  const idParts = id.split("/");
1112
924
  const name = idParts[0].startsWith("@") ? "".concat(idParts[0], "/").concat(idParts[1]) : idParts[0];
1113
-
1114
925
  if (name && external.includes(name)) {
1115
926
  return true;
1116
927
  }
1117
-
1118
928
  return false;
1119
929
  },
1120
930
  input: entries.reduce((acc, entry) => {
@@ -1122,13 +932,11 @@ function _resolveRollupConfig(ctx, buildTask) {
1122
932
  [entry.name]: entry.source
1123
933
  });
1124
934
  }, {}),
1125
-
1126
935
  onwarn(warning, rollupWarn) {
1127
936
  if (!warning.code || !["CIRCULAR_DEPENDENCY"].includes(warning.code)) {
1128
937
  rollupWarn(warning);
1129
938
  }
1130
939
  },
1131
-
1132
940
  plugins,
1133
941
  treeshake: {
1134
942
  propertyReadSideEffects: false
@@ -1140,11 +948,10 @@ function _resolveRollupConfig(ctx, buildTask) {
1140
948
  entryFileNames: () => outputExt === ".esm.js" ? "[name].js" : "[name]".concat(outputExt),
1141
949
  format,
1142
950
  exports: "auto",
1143
- sourcemap: (_ref11 = config == null ? void 0 : config.sourcemap) !== null && _ref11 !== void 0 ? _ref11 : true
951
+ sourcemap: (_ref10 = config == null ? void 0 : config.sourcemap) !== null && _ref10 !== void 0 ? _ref10 : true
1144
952
  }
1145
953
  };
1146
954
  }
1147
-
1148
955
  const _rollupTask = {
1149
956
  name: (ctx, task) => "build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")),
1150
957
  exec: (ctx, task) => {
@@ -1162,24 +969,20 @@ const _rollupTask = {
1162
969
  }
1163
970
  }
1164
971
  };
1165
-
1166
972
  async function _execPromise(ctx, task) {
1167
973
  const {
1168
974
  files,
1169
975
  distPath
1170
976
  } = ctx;
1171
977
  const outDir = path.relative(ctx.cwd, distPath);
1172
-
1173
978
  const {
1174
979
  inputOptions,
1175
980
  outputOptions
1176
981
  } = _resolveRollupConfig(ctx, task);
1177
-
1178
982
  const bundle = await rollup(inputOptions);
1179
983
  const {
1180
984
  output
1181
985
  } = await bundle.generate(outputOptions);
1182
-
1183
986
  for (const chunkOrAsset of output) {
1184
987
  if (chunkOrAsset.type === "asset") {
1185
988
  files.push({
@@ -1193,11 +996,9 @@ async function _execPromise(ctx, task) {
1193
996
  });
1194
997
  }
1195
998
  }
1196
-
1197
999
  await bundle.write(outputOptions);
1198
1000
  await bundle.close();
1199
1001
  }
1200
-
1201
1002
  const _rollupWatchTask = {
1202
1003
  name: (ctx, task) => "build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")),
1203
1004
  exec: (ctx, task) => {
@@ -1205,12 +1006,10 @@ const _rollupWatchTask = {
1205
1006
  inputOptions,
1206
1007
  outputOptions
1207
1008
  } = _resolveRollupConfig(ctx, task);
1208
-
1209
1009
  return new Observable(observer => {
1210
1010
  const watchOptions = _objectSpread(_objectSpread({}, inputOptions), {}, {
1211
1011
  output: outputOptions
1212
1012
  });
1213
-
1214
1013
  const watcher = watch$1(watchOptions);
1215
1014
  watcher.on("event", event => {
1216
1015
  observer.next(event);
@@ -1224,26 +1023,21 @@ const _rollupWatchTask = {
1224
1023
  const {
1225
1024
  logger
1226
1025
  } = ctx;
1227
-
1228
1026
  if (event.code === "BUNDLE_END") {
1229
1027
  logger.success("build javascript files (target ".concat(task.target.join(" + "), ", format ").concat(task.format, ")\n ").concat(task.entries.map(e => "".concat(chalk.blue(path.join(ctx.pkg.name, e.path)), ": ").concat(e.source, " -> ").concat(e.output)).join("\n ")));
1230
1028
  logger.log("");
1231
1029
  return;
1232
1030
  }
1233
-
1234
1031
  if (event.code === "BUNDLE_START") {
1235
1032
  return;
1236
1033
  }
1237
-
1238
1034
  if (event.code === "END") {
1239
1035
  return;
1240
1036
  }
1241
-
1242
1037
  if (event.code === "ERROR") {
1243
1038
  logger.error(event.code, event);
1244
1039
  return;
1245
1040
  }
1246
-
1247
1041
  if (event.code === "START") {
1248
1042
  return;
1249
1043
  }
@@ -1252,7 +1046,6 @@ const _rollupWatchTask = {
1252
1046
  const {
1253
1047
  logger
1254
1048
  } = ctx;
1255
-
1256
1049
  if (err instanceof Error) {
1257
1050
  logger.log(err);
1258
1051
  }
@@ -1266,47 +1059,36 @@ const _watchTaskHandlers = {
1266
1059
  "watch:dts": _dtsWatchTask,
1267
1060
  "watch:js": _rollupWatchTask
1268
1061
  };
1269
-
1270
1062
  function _pathContains(containerPath, itemPath) {
1271
1063
  return !path.relative(containerPath, itemPath).startsWith("..");
1272
1064
  }
1273
-
1274
1065
  function _findCommonDirPath(filePaths) {
1275
1066
  let ret = void 0;
1276
-
1277
1067
  for (const filePath of filePaths) {
1278
1068
  let dirPath = path.dirname(filePath);
1279
-
1280
1069
  if (!ret) {
1281
1070
  ret = dirPath;
1282
1071
  continue;
1283
1072
  }
1284
-
1285
1073
  while (dirPath !== ret) {
1286
1074
  dirPath = path.dirname(dirPath);
1287
-
1288
1075
  if (dirPath === ret) {
1289
1076
  break;
1290
1077
  }
1291
-
1292
1078
  if (_pathContains(dirPath, ret)) {
1293
1079
  ret = dirPath;
1294
1080
  break;
1295
1081
  }
1296
-
1297
1082
  if (dirPath === ".") return void 0;
1298
1083
  }
1299
1084
  }
1300
-
1301
1085
  return ret;
1302
1086
  }
1303
-
1304
1087
  function _sortAsNumber(a, b) {
1305
1088
  const aVersion = Number(a);
1306
1089
  const bVersion = Number(b);
1307
1090
  return aVersion - bVersion;
1308
1091
  }
1309
-
1310
1092
  function _resolveBrowserslistVersions(query) {
1311
1093
  const result = browserslist(query);
1312
1094
  const entries = result.map(key => {
@@ -1343,55 +1125,41 @@ function _resolveBrowserslistVersions(query) {
1343
1125
  versions.node.sort(_sortAsNumber);
1344
1126
  return versions;
1345
1127
  }
1346
-
1347
1128
  function _resolveBrowserTarget(versions) {
1348
1129
  const target = [];
1349
-
1350
1130
  if (versions.chrome.length) {
1351
1131
  target.push("chrome".concat(versions.chrome[0]));
1352
1132
  }
1353
-
1354
1133
  if (versions.ff.length) {
1355
1134
  target.push("firefox".concat(versions.ff[0]));
1356
1135
  }
1357
-
1358
1136
  if (versions.edge.length) {
1359
1137
  target.push("edge".concat(versions.edge[0]));
1360
1138
  }
1361
-
1362
1139
  if (versions.iosSaf.length) {
1363
1140
  target.push("ios".concat(versions.iosSaf[0]));
1364
1141
  }
1365
-
1366
1142
  if (versions.saf.length) {
1367
1143
  target.push("safari".concat(versions.saf[0]));
1368
1144
  }
1369
-
1370
1145
  if (versions.opera.length) {
1371
1146
  target.push("opera".concat(versions.opera[0]));
1372
1147
  }
1373
-
1374
1148
  if (target.length === 0) {
1375
1149
  return void 0;
1376
1150
  }
1377
-
1378
1151
  return target;
1379
1152
  }
1380
-
1381
1153
  function _resolveNodeTarget(versions) {
1382
1154
  const target = [];
1383
-
1384
1155
  if (versions.node.length) {
1385
1156
  target.push("node".concat(versions.node[0]));
1386
1157
  }
1387
-
1388
1158
  if (target.length === 0) {
1389
1159
  return void 0;
1390
1160
  }
1391
-
1392
1161
  return target;
1393
1162
  }
1394
-
1395
1163
  function _createLogger() {
1396
1164
  return {
1397
1165
  log: function () {
@@ -1401,36 +1169,30 @@ function _createLogger() {
1401
1169
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1402
1170
  args[_key] = arguments[_key];
1403
1171
  }
1404
-
1405
1172
  console.log(chalk.blue(" info"), ...args);
1406
1173
  },
1407
1174
  warn: function () {
1408
1175
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
1409
1176
  args[_key2] = arguments[_key2];
1410
1177
  }
1411
-
1412
1178
  console.log(chalk.yellow(" warn"), ...args);
1413
1179
  },
1414
1180
  error: function () {
1415
1181
  for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
1416
1182
  args[_key3] = arguments[_key3];
1417
1183
  }
1418
-
1419
1184
  console.log(chalk.red(" fail"), ...args);
1420
1185
  },
1421
1186
  success: function () {
1422
1187
  for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
1423
1188
  args[_key4] = arguments[_key4];
1424
1189
  }
1425
-
1426
1190
  console.log(chalk.green(" ok "), ...args);
1427
1191
  }
1428
1192
  };
1429
1193
  }
1430
-
1431
1194
  async function _resolveBuildContext(options) {
1432
- var _ref12;
1433
-
1195
+ var _ref11;
1434
1196
  const {
1435
1197
  config,
1436
1198
  cwd,
@@ -1439,81 +1201,60 @@ async function _resolveBuildContext(options) {
1439
1201
  strict,
1440
1202
  tsconfig: tsconfigPath
1441
1203
  } = options;
1442
-
1443
1204
  const logger = _createLogger();
1444
-
1445
1205
  const tsconfig = await _loadTSConfig({
1446
1206
  cwd,
1447
1207
  tsconfigPath
1448
1208
  });
1449
-
1450
1209
  const targetVersions = _resolveBrowserslistVersions(pkg.browserslist || _DEFAULTS.browserslist);
1451
-
1452
1210
  const nodeTarget = _resolveNodeTarget(targetVersions);
1453
-
1454
1211
  const webTarget = _resolveBrowserTarget(targetVersions);
1455
-
1456
1212
  if (!nodeTarget) {
1457
1213
  throw new Error("no matching `node` target");
1458
1214
  }
1459
-
1460
1215
  if (!webTarget) {
1461
1216
  throw new Error("no matching `web` target");
1462
1217
  }
1463
-
1464
1218
  const target = {
1465
1219
  "*": webTarget.concat(nodeTarget),
1466
1220
  browser: webTarget,
1467
1221
  node: nodeTarget
1468
1222
  };
1469
-
1470
1223
  const parsedExports = _parseExports({
1471
1224
  pkg,
1472
1225
  strict
1473
1226
  }).reduce((acc, x) => {
1474
1227
  const {
1475
- _path: exportPath
1476
- } = x,
1477
- exportEntry = _objectWithoutProperties(x, _excluded);
1478
-
1228
+ _path: exportPath
1229
+ } = x,
1230
+ exportEntry = _objectWithoutProperties(x, _excluded);
1479
1231
  return _objectSpread(_objectSpread({}, acc), {}, {
1480
1232
  [exportPath]: exportEntry
1481
1233
  });
1482
1234
  }, {});
1483
-
1484
1235
  const exports = _resolveConfigProperty(config == null ? void 0 : config.exports, parsedExports);
1485
-
1486
1236
  const parsedExternal = [...(pkg.dependencies ? Object.keys(pkg.dependencies) : []), ...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : [])];
1487
1237
  const external = config && Array.isArray(config.external) ? [...parsedExternal, ...config.external] : _resolveConfigProperty(config == null ? void 0 : config.external, parsedExternal);
1488
1238
  const outputPaths = Object.values(exports).flatMap(exportEntry => {
1489
1239
  var _a, _b, _c, _d;
1490
-
1491
1240
  return [exportEntry.import, exportEntry.require, (_a = exportEntry.browser) == null ? void 0 : _a.import, (_b = exportEntry.browser) == null ? void 0 : _b.require, (_c = exportEntry.node) == null ? void 0 : _c.import, (_d = exportEntry.node) == null ? void 0 : _d.require].filter(Boolean);
1492
1241
  }).map(p => path.resolve(cwd, p));
1493
-
1494
1242
  const commonDistPath = _findCommonDirPath(outputPaths);
1495
-
1496
1243
  if (commonDistPath === cwd) {
1497
1244
  throw new Error("all output files must share a common parent directory which is not the root package directory");
1498
1245
  }
1499
-
1500
1246
  if (commonDistPath && !_pathContains(cwd, commonDistPath)) {
1501
1247
  throw new Error("all output files must be located within the package");
1502
1248
  }
1503
-
1504
1249
  const configDistPath = (config == null ? void 0 : config.dist) ? path.resolve(cwd, config.dist) : void 0;
1505
-
1506
1250
  if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !_pathContains(configDistPath, commonDistPath)) {
1507
1251
  logger.log("did you mean to configure `dist: './".concat(path.relative(cwd, commonDistPath), "'`?"));
1508
1252
  throw new Error("all output files must be located with the configured `dist` path");
1509
1253
  }
1510
-
1511
1254
  const distPath = configDistPath || commonDistPath;
1512
-
1513
1255
  if (!distPath) {
1514
1256
  throw new Error("could not detect `dist` path");
1515
1257
  }
1516
-
1517
1258
  const ctx = {
1518
1259
  config,
1519
1260
  cwd,
@@ -1524,7 +1265,7 @@ async function _resolveBuildContext(options) {
1524
1265
  files: [],
1525
1266
  logger,
1526
1267
  pkg,
1527
- runtime: (_ref12 = config == null ? void 0 : config.runtime) !== null && _ref12 !== void 0 ? _ref12 : "*",
1268
+ runtime: (_ref11 = config == null ? void 0 : config.runtime) !== null && _ref11 !== void 0 ? _ref11 : "*",
1528
1269
  strict,
1529
1270
  target,
1530
1271
  ts: {
@@ -1534,7 +1275,6 @@ async function _resolveBuildContext(options) {
1534
1275
  };
1535
1276
  return ctx;
1536
1277
  }
1537
-
1538
1278
  function _spinner(msg) {
1539
1279
  const startTime = Date.now();
1540
1280
  console.log("".concat(chalk.yellow("run "), " ").concat(msg));
@@ -1547,7 +1287,6 @@ function _spinner(msg) {
1547
1287
  }
1548
1288
  };
1549
1289
  }
1550
-
1551
1290
  async function build(options) {
1552
1291
  const {
1553
1292
  cwd,
@@ -1570,15 +1309,11 @@ async function build(options) {
1570
1309
  strict,
1571
1310
  tsconfig
1572
1311
  });
1573
-
1574
1312
  const buildTasks = _resolveBuildTasks(ctx);
1575
-
1576
1313
  for (const task of buildTasks) {
1577
1314
  const handler = _buildTaskHandlers[task.type];
1578
1315
  const taskName = handler.name(ctx, task);
1579
-
1580
1316
  const spinner = _spinner(taskName);
1581
-
1582
1317
  try {
1583
1318
  const result = await handler.exec(ctx, task).toPromise();
1584
1319
  spinner.complete();
@@ -1586,24 +1321,20 @@ async function build(options) {
1586
1321
  handler.complete(ctx, task, result);
1587
1322
  } catch (err) {
1588
1323
  spinner.error();
1589
-
1590
1324
  if (err instanceof Error) {
1591
1325
  const RE_CWD = new RegExp("".concat(cwd), "g");
1592
1326
  ctx.logger.error(err.message.replace(RE_CWD, "."));
1593
1327
  ctx.logger.log();
1594
1328
  }
1595
-
1596
1329
  handler.error(ctx, task, err);
1597
1330
  process.exit(1);
1598
1331
  }
1599
1332
  }
1600
1333
  }
1601
-
1602
1334
  function _getFilesize(file) {
1603
1335
  const stats = statSync(file);
1604
1336
  return prettyBytes(stats.size);
1605
1337
  }
1606
-
1607
1338
  function _fileExists(file) {
1608
1339
  try {
1609
1340
  fs$1.accessSync(file);
@@ -1612,19 +1343,15 @@ function _fileExists(file) {
1612
1343
  return false;
1613
1344
  }
1614
1345
  }
1615
-
1616
1346
  function _getFileInfo(cwd, filePath) {
1617
1347
  const p = path.resolve(cwd, filePath);
1618
-
1619
1348
  const exists = _fileExists(p);
1620
-
1621
1349
  const size = exists ? _getFilesize(p) : void 0;
1622
1350
  return {
1623
1351
  exists,
1624
1352
  size
1625
1353
  };
1626
1354
  }
1627
-
1628
1355
  function _printPackageTree(ctx) {
1629
1356
  const {
1630
1357
  cwd,
@@ -1635,26 +1362,21 @@ function _printPackageTree(ctx) {
1635
1362
  if (!exports) return;
1636
1363
  logger.log("".concat(chalk.blue(pkg.name), "@").concat(chalk.green(pkg.version)));
1637
1364
  const tree = {};
1638
-
1639
1365
  if (pkg.bin) {
1640
1366
  tree.bin = pkg.bin;
1641
1367
  }
1642
-
1643
1368
  function _fileInfo(file) {
1644
1369
  const info = _getFileInfo(cwd, file);
1645
-
1646
1370
  if (!info.size) {
1647
1371
  return "".concat(chalk.gray(file), " ").concat(chalk.red("does not exist"));
1648
1372
  }
1649
-
1650
1373
  return "".concat(file, " ").concat(chalk.gray(info.size));
1651
1374
  }
1652
-
1653
- tree.exports = Object.fromEntries(Object.entries(exports).filter(_ref13 => {
1654
- let [, entry] = _ref13;
1375
+ tree.exports = Object.fromEntries(Object.entries(exports).filter(_ref12 => {
1376
+ let [, entry] = _ref12;
1655
1377
  return entry._exported;
1656
- }).map(_ref14 => {
1657
- let [exportPath, entry] = _ref14;
1378
+ }).map(_ref13 => {
1379
+ let [exportPath, entry] = _ref13;
1658
1380
  const exp = {
1659
1381
  source: entry.source,
1660
1382
  types: void 0,
@@ -1664,13 +1386,11 @@ function _printPackageTree(ctx) {
1664
1386
  require: void 0,
1665
1387
  default: entry.default
1666
1388
  };
1667
-
1668
1389
  if (entry.types) {
1669
1390
  exp.types = _fileInfo(entry.types);
1670
1391
  } else {
1671
1392
  delete exp.types;
1672
1393
  }
1673
-
1674
1394
  if (entry.browser) {
1675
1395
  exp.browser = {
1676
1396
  source: entry.browser.source
@@ -1680,7 +1400,6 @@ function _printPackageTree(ctx) {
1680
1400
  } else {
1681
1401
  delete exp.browser;
1682
1402
  }
1683
-
1684
1403
  if (entry.node) {
1685
1404
  exp.node = {
1686
1405
  source: entry.node.source
@@ -1690,25 +1409,21 @@ function _printPackageTree(ctx) {
1690
1409
  } else {
1691
1410
  delete exp.node;
1692
1411
  }
1693
-
1694
1412
  if (entry.import) {
1695
1413
  exp.import = _fileInfo(entry.import);
1696
1414
  } else {
1697
1415
  delete exp.import;
1698
1416
  }
1699
-
1700
1417
  if (entry.require) {
1701
1418
  exp.require = _fileInfo(entry.require);
1702
1419
  } else {
1703
1420
  delete exp.require;
1704
1421
  }
1705
-
1706
1422
  exp.default = _fileInfo(entry.default);
1707
1423
  return [chalk.green(path.join(pkg.name, exportPath)), exp];
1708
1424
  }));
1709
1425
  logger.log(treeify.asTree(tree, true, true));
1710
1426
  }
1711
-
1712
1427
  async function check(options) {
1713
1428
  const {
1714
1429
  cwd,
@@ -1732,51 +1447,39 @@ async function check(options) {
1732
1447
  const {
1733
1448
  logger
1734
1449
  } = ctx;
1735
-
1736
1450
  _printPackageTree(ctx);
1737
-
1738
1451
  if (strict) {
1739
1452
  const missingFiles = [];
1740
-
1741
1453
  for (const [, exp] of Object.entries(ctx.exports || {})) {
1742
1454
  if (exp.source && !_fileExists(path.resolve(cwd, exp.source))) {
1743
1455
  missingFiles.push(exp.source);
1744
1456
  }
1745
-
1746
1457
  if (exp.require && !_fileExists(path.resolve(cwd, exp.require))) {
1747
1458
  missingFiles.push(exp.require);
1748
1459
  }
1749
-
1750
1460
  if (exp.import && !_fileExists(path.resolve(cwd, exp.import))) {
1751
1461
  missingFiles.push(exp.import);
1752
1462
  }
1753
-
1754
1463
  if (exp.types && !_fileExists(path.resolve(cwd, exp.types))) {
1755
1464
  missingFiles.push(exp.types);
1756
1465
  }
1757
1466
  }
1758
-
1759
1467
  if (missingFiles.length) {
1760
1468
  logger.error("missing files");
1761
1469
  process.exit(1);
1762
1470
  }
1763
-
1764
1471
  const _paths = {
1765
1472
  require: [],
1766
1473
  import: []
1767
1474
  };
1768
-
1769
1475
  for (const exp of Object.values(ctx.exports || {})) {
1770
1476
  if (!exp._exported) continue;
1771
1477
  if (exp.require) _paths.require.push(exp.require);
1772
1478
  if (exp.import) _paths.import.push(exp.import);
1773
1479
  }
1774
-
1775
1480
  const external = Object.keys(pkg.dependencies || {}).concat(Object.keys(pkg.devDependencies || {}));
1776
-
1777
1481
  if (_paths.import.length) {
1778
1482
  const code = _paths.import.map(id => "import('".concat(id, "')")).join("\n");
1779
-
1780
1483
  try {
1781
1484
  const esbuildResult = await esbuild$1.build({
1782
1485
  external,
@@ -1791,7 +1494,6 @@ async function check(options) {
1791
1494
  outfile: "/dev/null",
1792
1495
  platform: "node"
1793
1496
  });
1794
-
1795
1497
  if (esbuildResult.warnings.length > 0) {
1796
1498
  logger.warn(...esbuildResult.warnings);
1797
1499
  }
@@ -1799,7 +1501,6 @@ async function check(options) {
1799
1501
  const {
1800
1502
  errors
1801
1503
  } = err;
1802
-
1803
1504
  for (const _err of errors) {
1804
1505
  if (_err.location) {
1805
1506
  logger.error(_err.detail || _err.text);
@@ -1808,17 +1509,13 @@ async function check(options) {
1808
1509
  } else {
1809
1510
  logger.error(_err.detail || _err.text);
1810
1511
  }
1811
-
1812
1512
  logger.log();
1813
1513
  }
1814
-
1815
1514
  process.exit(1);
1816
1515
  }
1817
1516
  }
1818
-
1819
1517
  if (_paths.require.length) {
1820
1518
  const code = _paths.require.map(id => "require('".concat(id, "')")).join("\n");
1821
-
1822
1519
  const esbuildResult = await esbuild$1.build({
1823
1520
  external,
1824
1521
  stdin: {
@@ -1831,22 +1528,18 @@ async function check(options) {
1831
1528
  outfile: "/dev/null",
1832
1529
  platform: "node"
1833
1530
  });
1834
-
1835
1531
  if (esbuildResult.errors.length > 0) {
1836
1532
  logger.error(esbuildResult.errors.join(", "));
1837
1533
  process.exit(1);
1838
1534
  }
1839
-
1840
1535
  if (esbuildResult.warnings.length > 0) {
1841
1536
  logger.warn(...esbuildResult.warnings);
1842
1537
  }
1843
1538
  }
1844
1539
  }
1845
1540
  }
1846
-
1847
1541
  function _resolveWatchTasks(ctx) {
1848
1542
  var _a, _b, _c, _d, _e;
1849
-
1850
1543
  const {
1851
1544
  config,
1852
1545
  cwd,
@@ -1854,8 +1547,8 @@ function _resolveWatchTasks(ctx) {
1854
1547
  target
1855
1548
  } = ctx;
1856
1549
  const tasks = [];
1857
- const exports = Object.entries(ctx.exports || {}).map(_ref15 => {
1858
- let [_path, exp] = _ref15;
1550
+ const exports = Object.entries(ctx.exports || {}).map(_ref14 => {
1551
+ let [_path, exp] = _ref14;
1859
1552
  return _objectSpread({
1860
1553
  _path
1861
1554
  }, exp);
@@ -1865,10 +1558,8 @@ function _resolveWatchTasks(ctx) {
1865
1558
  entries: []
1866
1559
  };
1867
1560
  const rollupTasks = {};
1868
-
1869
1561
  function _addRollupTaskEntry(format, runtime, entry) {
1870
1562
  const buildId = "".concat(format, ":").concat(runtime);
1871
-
1872
1563
  if (rollupTasks[buildId]) {
1873
1564
  rollupTasks[buildId].entries.push(entry);
1874
1565
  } else {
@@ -1882,10 +1573,8 @@ function _resolveWatchTasks(ctx) {
1882
1573
  };
1883
1574
  }
1884
1575
  }
1885
-
1886
1576
  for (const exp of exports) {
1887
1577
  const importId = path.join(pkg.name, exp._path);
1888
-
1889
1578
  if (exp.types) {
1890
1579
  dtsTask.entries.push({
1891
1580
  importId,
@@ -1895,89 +1584,72 @@ function _resolveWatchTasks(ctx) {
1895
1584
  });
1896
1585
  }
1897
1586
  }
1898
-
1899
1587
  for (const exp of exports) {
1900
1588
  const output = exp.require;
1901
1589
  if (!output) continue;
1902
-
1903
1590
  _addRollupTaskEntry("commonjs", ctx.runtime, {
1904
1591
  path: exp._path,
1905
1592
  source: exp.source,
1906
1593
  output
1907
1594
  });
1908
1595
  }
1909
-
1910
1596
  for (const exp of exports) {
1911
1597
  const output = (_a = exp.browser) == null ? void 0 : _a.require;
1912
1598
  if (!output) continue;
1913
-
1914
1599
  _addRollupTaskEntry("commonjs", "browser", {
1915
1600
  path: exp._path,
1916
1601
  source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
1917
1602
  output
1918
1603
  });
1919
1604
  }
1920
-
1921
1605
  for (const exp of exports) {
1922
1606
  const output = exp.import;
1923
1607
  if (!output) continue;
1924
-
1925
1608
  _addRollupTaskEntry("esm", ctx.runtime, {
1926
1609
  path: exp._path,
1927
1610
  source: exp.source,
1928
1611
  output
1929
1612
  });
1930
1613
  }
1931
-
1932
1614
  for (const exp of exports) {
1933
1615
  const output = (_c = exp.browser) == null ? void 0 : _c.import;
1934
1616
  if (!output) continue;
1935
-
1936
1617
  _addRollupTaskEntry("esm", "browser", {
1937
1618
  path: exp._path,
1938
1619
  source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
1939
1620
  output
1940
1621
  });
1941
1622
  }
1942
-
1943
1623
  if (dtsTask.entries.length) {
1944
1624
  tasks.push(dtsTask);
1945
1625
  }
1946
-
1947
1626
  tasks.push(...Object.values(rollupTasks));
1948
-
1949
1627
  if (config == null ? void 0 : config.legacyExports) {
1950
1628
  for (const exp of exports) {
1951
1629
  if (exp._exported && exp._path !== ".") {
1952
1630
  const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
1953
-
1954
1631
  if (relativeTargetPath) {
1955
1632
  fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
1956
1633
  }
1957
1634
  }
1958
1635
  }
1959
1636
  }
1960
-
1961
1637
  return tasks;
1962
1638
  }
1963
-
1964
1639
  function _globFiles(patterns) {
1965
1640
  return globby(patterns);
1966
1641
  }
1967
-
1968
1642
  function _watchFiles(patterns) {
1969
1643
  return new Observable(observer => {
1970
1644
  const watcher = chokidar.watch(patterns, {
1971
1645
  ignoreInitial: true
1972
1646
  });
1973
-
1974
1647
  function _handleFileEvent(type, file) {
1975
1648
  observer.next({
1976
1649
  type,
1977
1650
  file
1978
1651
  });
1979
1652
  }
1980
-
1981
1653
  watcher.on("all", _handleFileEvent);
1982
1654
  return () => {
1983
1655
  watcher.off("all", _handleFileEvent);
@@ -1985,35 +1657,28 @@ function _watchFiles(patterns) {
1985
1657
  };
1986
1658
  });
1987
1659
  }
1988
-
1989
1660
  async function _watchConfigFiles(options) {
1990
1661
  const {
1991
1662
  cwd
1992
1663
  } = options;
1993
1664
  const initialFiles = await _globFiles([path.resolve(cwd, "package.json"), path.resolve(cwd, "package.config.cjs"), path.resolve(cwd, "package.config.js"), path.resolve(cwd, "package.config.ts")]);
1994
-
1995
1665
  const fileEvent$ = _watchFiles([path.resolve(cwd, "package.json"), path.resolve(cwd, "package.config.cjs"), path.resolve(cwd, "package.config.js"), path.resolve(cwd, "package.config.ts")]);
1996
-
1997
1666
  return fileEvent$.pipe(scan((files, fileEvent) => {
1998
1667
  if (fileEvent.type === "add") {
1999
1668
  return files.concat(fileEvent.file);
2000
1669
  }
2001
-
2002
1670
  if (fileEvent.type === "unlink") {
2003
1671
  return files.filter(f => f !== fileEvent.file);
2004
1672
  }
2005
-
2006
1673
  if (fileEvent.type === "change") {
2007
1674
  console.log("--------------------------------------------------------------------------------");
2008
1675
  console.log(chalk.blue("info "), path.relative(cwd, fileEvent.file), "changed");
2009
1676
  console.log("");
2010
1677
  return files.slice(0);
2011
1678
  }
2012
-
2013
1679
  return files;
2014
1680
  }, initialFiles), startWith(initialFiles), distinctUntilChanged());
2015
1681
  }
2016
-
2017
1682
  async function watch(options) {
2018
1683
  const {
2019
1684
  cwd,
@@ -2025,13 +1690,10 @@ async function watch(options) {
2025
1690
  });
2026
1691
  const ctx$ = configFiles$.pipe(switchMap(async configFiles => {
2027
1692
  const _files = configFiles.map(f => path.relative(cwd, f));
2028
-
2029
1693
  const packageJsonPath = _files.find(f => f === "package.json");
2030
-
2031
1694
  if (!packageJsonPath) {
2032
1695
  throw new Error("missing package.json");
2033
1696
  }
2034
-
2035
1697
  const pkg = await _loadPkgWithReporting({
2036
1698
  cwd
2037
1699
  });
@@ -2049,7 +1711,6 @@ async function watch(options) {
2049
1711
  }));
2050
1712
  ctx$.subscribe(async ctx => {
2051
1713
  const watchTasks = _resolveWatchTasks(ctx);
2052
-
2053
1714
  for (const task of watchTasks) {
2054
1715
  const handler = _watchTaskHandlers[task.type];
2055
1716
  const result$ = handler.exec(ctx, task);
@@ -2070,6 +1731,5 @@ async function watch(options) {
2070
1731
  }
2071
1732
  });
2072
1733
  }
2073
-
2074
1734
  export { _DEFAULTS, _MODULE_EXT, _buildTaskHandlers, _dtsTask, _dtsWatchTask, _getExtractMessagesConfig, _isRecord, _loadConfig, _loadPkg, _loadPkgWithReporting, _loadTSConfig, _parseExports, _resolveBuildTasks, _resolveConfigProperty, _rollupTask, _rollupWatchTask, _watchTaskHandlers, build, check, defineConfig, watch };
2075
1735
  //# sourceMappingURL=index.esm.js.map