@sanity/pkg-utils 1.20.4 → 2.0.0-beta.2

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