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