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

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