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