@sanity/pkg-utils 2.3.11 → 2.3.13-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/dist/build.js +69 -0
  2. package/dist/build.js.map +1 -0
  3. package/dist/check.js +152 -0
  4. package/dist/check.js.map +1 -0
  5. package/dist/cli.cjs +6 -6
  6. package/dist/cli.cjs.map +1 -1
  7. package/dist/consoleSpy.js +49 -0
  8. package/dist/consoleSpy.js.map +1 -0
  9. package/dist/core/config/defineConfig.js +5 -0
  10. package/dist/core/config/defineConfig.js.map +1 -0
  11. package/dist/core/config/findConfigFile.js +21 -0
  12. package/dist/core/config/findConfigFile.js.map +1 -0
  13. package/dist/core/config/loadConfig.js +34 -0
  14. package/dist/core/config/loadConfig.js.map +1 -0
  15. package/dist/core/config/resolveConfigProperty.js +9 -0
  16. package/dist/core/config/resolveConfigProperty.js.map +1 -0
  17. package/dist/core/defaults.js +3 -0
  18. package/dist/core/defaults.js.map +1 -0
  19. package/dist/core/findCommonPath.js +28 -0
  20. package/dist/core/findCommonPath.js.map +1 -0
  21. package/dist/core/isRecord.js +5 -0
  22. package/dist/core/isRecord.js.map +1 -0
  23. package/dist/core/pkg/helpers.js +24 -0
  24. package/dist/core/pkg/helpers.js.map +1 -0
  25. package/dist/core/pkg/loadPkg.js +18 -0
  26. package/dist/core/pkg/loadPkg.js.map +1 -0
  27. package/dist/core/pkg/loadPkgWithReporting.js +107 -0
  28. package/dist/core/pkg/loadPkgWithReporting.js.map +1 -0
  29. package/dist/core/pkg/parseExports.js +75 -0
  30. package/dist/core/pkg/parseExports.js.map +1 -0
  31. package/dist/core/pkg/pkgExt.js +29 -0
  32. package/dist/core/pkg/pkgExt.js.map +1 -0
  33. package/dist/core/pkg/validateExports.js +19 -0
  34. package/dist/core/pkg/validateExports.js.map +1 -0
  35. package/dist/core/pkg/validatePkg.js +49 -0
  36. package/dist/core/pkg/validatePkg.js.map +1 -0
  37. package/dist/core/template/createFromTemplate.js +59 -0
  38. package/dist/core/template/createFromTemplate.js.map +1 -0
  39. package/dist/core/template/define.js +5 -0
  40. package/dist/core/template/define.js.map +1 -0
  41. package/dist/core/ts/loadTSConfig.js +15 -0
  42. package/dist/core/ts/loadTSConfig.js.map +1 -0
  43. package/dist/fileExists.js +11 -0
  44. package/dist/fileExists.js.map +1 -0
  45. package/dist/getFilesize.js +8 -0
  46. package/dist/getFilesize.js.map +1 -0
  47. package/dist/globFiles.js +7 -0
  48. package/dist/globFiles.js.map +1 -0
  49. package/dist/index.cjs +44 -30
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.ts +4 -2
  52. package/dist/index.js +24 -2505
  53. package/dist/index.js.map +1 -1
  54. package/dist/init.js +42 -0
  55. package/dist/init.js.map +1 -0
  56. package/dist/isEmptyDirectory.js +6 -0
  57. package/dist/isEmptyDirectory.js.map +1 -0
  58. package/dist/logger.js +37 -0
  59. package/dist/logger.js.map +1 -0
  60. package/dist/package.json.cjs +8 -0
  61. package/dist/package.json.cjs.map +1 -0
  62. package/dist/printExtractMessages.js +32 -0
  63. package/dist/printExtractMessages.js.map +1 -0
  64. package/dist/printPackageTree.js +92 -0
  65. package/dist/printPackageTree.js.map +1 -0
  66. package/dist/resolveBrowserTarget.js +27 -0
  67. package/dist/resolveBrowserTarget.js.map +1 -0
  68. package/dist/resolveBrowserslistVersions.js +44 -0
  69. package/dist/resolveBrowserslistVersions.js.map +1 -0
  70. package/dist/resolveBuildContext.js +109 -0
  71. package/dist/resolveBuildContext.js.map +1 -0
  72. package/dist/resolveBuildTasks.js +140 -0
  73. package/dist/resolveBuildTasks.js.map +1 -0
  74. package/dist/resolveNodeTarget.js +12 -0
  75. package/dist/resolveNodeTarget.js.map +1 -0
  76. package/dist/resolveWatchTasks.js +103 -0
  77. package/dist/resolveWatchTasks.js.map +1 -0
  78. package/dist/spinner.js +15 -0
  79. package/dist/spinner.js.map +1 -0
  80. package/dist/{_chunks/buildAction-b2571e76.cjs → src/cli/buildAction.cjs} +6 -3
  81. package/dist/src/cli/buildAction.cjs.map +1 -0
  82. package/dist/{_chunks/checkAction-c3e5da35.cjs → src/cli/checkAction.cjs} +6 -3
  83. package/dist/src/cli/checkAction.cjs.map +1 -0
  84. package/dist/{_chunks/handleError-13d87f55.cjs → src/cli/handleError.cjs} +4 -1
  85. package/dist/src/cli/handleError.cjs.map +1 -0
  86. package/dist/{_chunks/initAction-2abd8576.cjs → src/cli/initAction.cjs} +6 -3
  87. package/dist/src/cli/initAction.cjs.map +1 -0
  88. package/dist/{_chunks/watchAction-79480cb8.cjs → src/cli/watchAction.cjs} +6 -3
  89. package/dist/src/cli/watchAction.cjs.map +1 -0
  90. package/dist/src/node/build.cjs +74 -0
  91. package/dist/src/node/build.cjs.map +1 -0
  92. package/dist/src/node/check.cjs +164 -0
  93. package/dist/src/node/check.cjs.map +1 -0
  94. package/dist/src/node/consoleSpy.cjs +54 -0
  95. package/dist/src/node/consoleSpy.cjs.map +1 -0
  96. package/dist/src/node/core/config/defineConfig.cjs +10 -0
  97. package/dist/src/node/core/config/defineConfig.cjs.map +1 -0
  98. package/dist/src/node/core/config/findConfigFile.cjs +33 -0
  99. package/dist/src/node/core/config/findConfigFile.cjs.map +1 -0
  100. package/dist/src/node/core/config/loadConfig.cjs +46 -0
  101. package/dist/src/node/core/config/loadConfig.cjs.map +1 -0
  102. package/dist/src/node/core/config/resolveConfigProperty.cjs +14 -0
  103. package/dist/src/node/core/config/resolveConfigProperty.cjs.map +1 -0
  104. package/dist/src/node/core/defaults.cjs +8 -0
  105. package/dist/src/node/core/defaults.cjs.map +1 -0
  106. package/dist/src/node/core/findCommonPath.cjs +40 -0
  107. package/dist/src/node/core/findCommonPath.cjs.map +1 -0
  108. package/dist/src/node/core/isRecord.cjs +10 -0
  109. package/dist/src/node/core/isRecord.cjs.map +1 -0
  110. package/dist/src/node/core/pkg/helpers.cjs +31 -0
  111. package/dist/src/node/core/pkg/helpers.cjs.map +1 -0
  112. package/dist/src/node/core/pkg/loadPkg.cjs +30 -0
  113. package/dist/src/node/core/pkg/loadPkg.cjs.map +1 -0
  114. package/dist/src/node/core/pkg/loadPkgWithReporting.cjs +118 -0
  115. package/dist/src/node/core/pkg/loadPkgWithReporting.cjs.map +1 -0
  116. package/dist/src/node/core/pkg/parseExports.cjs +80 -0
  117. package/dist/src/node/core/pkg/parseExports.cjs.map +1 -0
  118. package/dist/src/node/core/pkg/pkgExt.cjs +35 -0
  119. package/dist/src/node/core/pkg/pkgExt.cjs.map +1 -0
  120. package/dist/src/node/core/pkg/validateExports.cjs +24 -0
  121. package/dist/src/node/core/pkg/validateExports.cjs.map +1 -0
  122. package/dist/src/node/core/pkg/validatePkg.cjs +54 -0
  123. package/dist/src/node/core/pkg/validatePkg.cjs.map +1 -0
  124. package/dist/src/node/core/template/createFromTemplate.cjs +70 -0
  125. package/dist/src/node/core/template/createFromTemplate.cjs.map +1 -0
  126. package/dist/src/node/core/template/define.cjs +10 -0
  127. package/dist/src/node/core/template/define.cjs.map +1 -0
  128. package/dist/src/node/core/ts/loadTSConfig.cjs +26 -0
  129. package/dist/src/node/core/ts/loadTSConfig.cjs.map +1 -0
  130. package/dist/src/node/fileExists.cjs +16 -0
  131. package/dist/src/node/fileExists.cjs.map +1 -0
  132. package/dist/src/node/getFilesize.cjs +19 -0
  133. package/dist/src/node/getFilesize.cjs.map +1 -0
  134. package/dist/src/node/globFiles.cjs +19 -0
  135. package/dist/src/node/globFiles.cjs.map +1 -0
  136. package/dist/src/node/init.cjs +47 -0
  137. package/dist/src/node/init.cjs.map +1 -0
  138. package/dist/src/node/isEmptyDirectory.cjs +11 -0
  139. package/dist/src/node/isEmptyDirectory.cjs.map +1 -0
  140. package/dist/src/node/logger.cjs +48 -0
  141. package/dist/src/node/logger.cjs.map +1 -0
  142. package/dist/src/node/printExtractMessages.cjs +44 -0
  143. package/dist/src/node/printExtractMessages.cjs.map +1 -0
  144. package/dist/src/node/printPackageTree.cjs +105 -0
  145. package/dist/src/node/printPackageTree.cjs.map +1 -0
  146. package/dist/src/node/resolveBrowserTarget.cjs +32 -0
  147. package/dist/src/node/resolveBrowserTarget.cjs.map +1 -0
  148. package/dist/src/node/resolveBrowserslistVersions.cjs +55 -0
  149. package/dist/src/node/resolveBrowserslistVersions.cjs.map +1 -0
  150. package/dist/src/node/resolveBuildContext.cjs +120 -0
  151. package/dist/src/node/resolveBuildContext.cjs.map +1 -0
  152. package/dist/{_chunks/build-62cd452e.cjs → src/node/resolveBuildTasks.cjs} +8 -80
  153. package/dist/src/node/resolveBuildTasks.cjs.map +1 -0
  154. package/dist/src/node/resolveNodeTarget.cjs +17 -0
  155. package/dist/src/node/resolveNodeTarget.cjs.map +1 -0
  156. package/dist/src/node/resolveWatchTasks.cjs +115 -0
  157. package/dist/src/node/resolveWatchTasks.cjs.map +1 -0
  158. package/dist/src/node/spinner.cjs +26 -0
  159. package/dist/src/node/spinner.cjs.map +1 -0
  160. package/dist/src/node/tasks/dts/DtsError.cjs +17 -0
  161. package/dist/src/node/tasks/dts/DtsError.cjs.map +1 -0
  162. package/dist/src/node/tasks/dts/buildTypes.cjs +50 -0
  163. package/dist/src/node/tasks/dts/buildTypes.cjs.map +1 -0
  164. package/dist/src/node/tasks/dts/createApiExtractorConfig.cjs +52 -0
  165. package/dist/src/node/tasks/dts/createApiExtractorConfig.cjs.map +1 -0
  166. package/dist/src/node/tasks/dts/createTSDocConfig.cjs +37 -0
  167. package/dist/src/node/tasks/dts/createTSDocConfig.cjs.map +1 -0
  168. package/dist/src/node/tasks/dts/doExtract.cjs +88 -0
  169. package/dist/src/node/tasks/dts/doExtract.cjs.map +1 -0
  170. package/dist/src/node/tasks/dts/dtsTask.cjs +44 -0
  171. package/dist/src/node/tasks/dts/dtsTask.cjs.map +1 -0
  172. package/dist/src/node/tasks/dts/dtsWatchTask.cjs +47 -0
  173. package/dist/src/node/tasks/dts/dtsWatchTask.cjs.map +1 -0
  174. package/dist/src/node/tasks/dts/extractModuleBlocks.cjs +38 -0
  175. package/dist/src/node/tasks/dts/extractModuleBlocks.cjs.map +1 -0
  176. package/dist/src/node/tasks/dts/extractTypes.cjs +90 -0
  177. package/dist/src/node/tasks/dts/extractTypes.cjs.map +1 -0
  178. package/dist/src/node/tasks/dts/getExtractMessagesConfig.cjs +73 -0
  179. package/dist/src/node/tasks/dts/getExtractMessagesConfig.cjs.map +1 -0
  180. package/dist/src/node/tasks/dts/printDiagnostic.cjs +48 -0
  181. package/dist/src/node/tasks/dts/printDiagnostic.cjs.map +1 -0
  182. package/dist/src/node/tasks/index.cjs +26 -0
  183. package/dist/src/node/tasks/index.cjs.map +1 -0
  184. package/dist/src/node/tasks/node/reexportCjsTask.cjs +64 -0
  185. package/dist/src/node/tasks/node/reexportCjsTask.cjs.map +1 -0
  186. package/dist/src/node/tasks/rollup/resolveRollupConfig.cjs +207 -0
  187. package/dist/src/node/tasks/rollup/resolveRollupConfig.cjs.map +1 -0
  188. package/dist/src/node/tasks/rollup/rollupTask.cjs +116 -0
  189. package/dist/src/node/tasks/rollup/rollupTask.cjs.map +1 -0
  190. package/dist/src/node/tasks/rollup/rollupWatchTask.cjs +72 -0
  191. package/dist/src/node/tasks/rollup/rollupWatchTask.cjs.map +1 -0
  192. package/dist/{_chunks/init-2377e6e5.cjs → src/node/templates/default/template.cjs} +23 -112
  193. package/dist/src/node/templates/default/template.cjs.map +1 -0
  194. package/dist/src/node/watch.cjs +90 -0
  195. package/dist/src/node/watch.cjs.map +1 -0
  196. package/dist/src/node/watchConfigFiles.cjs +40 -0
  197. package/dist/src/node/watchConfigFiles.cjs.map +1 -0
  198. package/dist/src/node/watchFiles.cjs +33 -0
  199. package/dist/src/node/watchFiles.cjs.map +1 -0
  200. package/dist/tasks/dts/DtsError.js +12 -0
  201. package/dist/tasks/dts/DtsError.js.map +1 -0
  202. package/dist/tasks/dts/buildTypes.js +39 -0
  203. package/dist/tasks/dts/buildTypes.js.map +1 -0
  204. package/dist/tasks/dts/createApiExtractorConfig.js +41 -0
  205. package/dist/tasks/dts/createApiExtractorConfig.js.map +1 -0
  206. package/dist/tasks/dts/createTSDocConfig.js +32 -0
  207. package/dist/tasks/dts/createTSDocConfig.js.map +1 -0
  208. package/dist/tasks/dts/doExtract.js +76 -0
  209. package/dist/tasks/dts/doExtract.js.map +1 -0
  210. package/dist/tasks/dts/dtsTask.js +33 -0
  211. package/dist/tasks/dts/dtsTask.js.map +1 -0
  212. package/dist/tasks/dts/dtsWatchTask.js +36 -0
  213. package/dist/tasks/dts/dtsWatchTask.js.map +1 -0
  214. package/dist/tasks/dts/extractModuleBlocks.js +26 -0
  215. package/dist/tasks/dts/extractModuleBlocks.js.map +1 -0
  216. package/dist/tasks/dts/extractTypes.js +77 -0
  217. package/dist/tasks/dts/extractTypes.js.map +1 -0
  218. package/dist/tasks/dts/getExtractMessagesConfig.js +68 -0
  219. package/dist/tasks/dts/getExtractMessagesConfig.js.map +1 -0
  220. package/dist/tasks/dts/printDiagnostic.js +35 -0
  221. package/dist/tasks/dts/printDiagnostic.js.map +1 -0
  222. package/dist/tasks/index.js +16 -0
  223. package/dist/tasks/index.js.map +1 -0
  224. package/dist/tasks/node/reexportCjsTask.js +52 -0
  225. package/dist/tasks/node/reexportCjsTask.js.map +1 -0
  226. package/dist/tasks/rollup/resolveRollupConfig.js +189 -0
  227. package/dist/tasks/rollup/resolveRollupConfig.js.map +1 -0
  228. package/dist/tasks/rollup/rollupTask.js +104 -0
  229. package/dist/tasks/rollup/rollupTask.js.map +1 -0
  230. package/dist/tasks/rollup/rollupWatchTask.js +60 -0
  231. package/dist/tasks/rollup/rollupWatchTask.js.map +1 -0
  232. package/dist/templates/default/template.js +366 -0
  233. package/dist/templates/default/template.js.map +1 -0
  234. package/dist/watch.js +79 -0
  235. package/dist/watch.js.map +1 -0
  236. package/dist/watchConfigFiles.js +29 -0
  237. package/dist/watchConfigFiles.js.map +1 -0
  238. package/dist/watchFiles.js +22 -0
  239. package/dist/watchFiles.js.map +1 -0
  240. package/package.json +3 -2
  241. package/src/node/core/pkg/loadPkgWithReporting.ts +91 -18
  242. package/src/node/core/pkg/types.ts +4 -2
  243. package/src/node/core/pkg/validatePkg.ts +31 -3
  244. package/src/node/resolveBuildTasks.ts +2 -2
  245. package/src/node/tasks/node/reexportCjsTask.ts +1 -1
  246. package/src/node/tasks/rollup/resolveRollupConfig.ts +4 -0
  247. package/src/node/tasks/rollup/rollupTask.ts +8 -0
  248. package/dist/_chunks/build-62cd452e.cjs.map +0 -1
  249. package/dist/_chunks/buildAction-b2571e76.cjs.map +0 -1
  250. package/dist/_chunks/check-0665cb35.cjs +0 -250
  251. package/dist/_chunks/check-0665cb35.cjs.map +0 -1
  252. package/dist/_chunks/checkAction-c3e5da35.cjs.map +0 -1
  253. package/dist/_chunks/consoleSpy-d738cb9f.cjs +0 -550
  254. package/dist/_chunks/consoleSpy-d738cb9f.cjs.map +0 -1
  255. package/dist/_chunks/handleError-13d87f55.cjs.map +0 -1
  256. package/dist/_chunks/index-ad3fa5bb.cjs +0 -865
  257. package/dist/_chunks/index-ad3fa5bb.cjs.map +0 -1
  258. package/dist/_chunks/init-2377e6e5.cjs.map +0 -1
  259. package/dist/_chunks/initAction-2abd8576.cjs.map +0 -1
  260. package/dist/_chunks/logger-c593f06b.cjs +0 -97
  261. package/dist/_chunks/logger-c593f06b.cjs.map +0 -1
  262. package/dist/_chunks/watch-425eab1e.cjs +0 -231
  263. package/dist/_chunks/watch-425eab1e.cjs.map +0 -1
  264. package/dist/_chunks/watchAction-79480cb8.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,2506 +1,25 @@
1
- var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10, _templateObject11, _templateObject12;
2
- function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
3
- 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; }
4
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
5
- 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); }
6
- import { register } from 'esbuild-register/dist/node';
7
- import path, { relative, resolve, dirname } from 'path';
8
- import pkgUp from 'pkg-up';
9
- import findConfig from 'find-config';
10
- import fs$1, { statSync } from 'fs';
11
- import fs, { writeFile, readFile, readdir, lstat } from 'fs/promises';
12
- import { z, ZodError } from 'zod';
13
- import chalk from 'chalk';
14
- import { mkdirp } from 'mkdirp';
15
- import prompts from 'prompts';
16
- import ts from 'typescript';
17
- import browserslist from 'browserslist';
18
- import { Observable, from, switchMap } from 'rxjs';
19
- import rimraf from 'rimraf';
20
- import { ExtractorConfig, Extractor } from '@microsoft/api-extractor';
21
- import prettier from 'prettier';
22
- import { TSDocConfigFile } from '@microsoft/tsdoc-config';
23
- import { parse } from 'jsonc-parser';
24
- import { parse as parse$1, print } from 'recast';
25
- import typeScriptParser from 'recast/parsers/typescript';
26
- import { rollup, watch as watch$1 } from 'rollup';
27
- import alias from '@rollup/plugin-alias';
28
- import { getBabelOutputPlugin } from '@rollup/plugin-babel';
29
- import commonjs from '@rollup/plugin-commonjs';
30
- import json from '@rollup/plugin-json';
31
- import { nodeResolve } from '@rollup/plugin-node-resolve';
32
- import replace from '@rollup/plugin-replace';
33
- import terser from '@rollup/plugin-terser';
34
- import esbuild from 'rollup-plugin-esbuild';
35
- import esbuild$1 from 'esbuild';
36
- import treeify from 'treeify';
37
- import prettyBytes from 'pretty-bytes';
38
- import getLatestVersion from 'get-latest-version';
39
- import gitUrlParse from 'git-url-parse';
40
- import { outdent } from 'outdent';
41
- import parseGitConfig from 'parse-git-config';
42
- import { scan, startWith, distinctUntilChanged } from 'rxjs/operators';
43
- import globby from 'globby';
44
- import chokidar from 'chokidar';
45
- function defineConfig(configOptions) {
46
- return configOptions;
47
- }
48
- function fileExists(filePath) {
49
- try {
50
- statSync(filePath);
51
- return true;
52
- } catch (_) {
53
- return false;
54
- }
55
- }
56
- const CONFIG_FILE_NAMES = ["package.config.ts", "package.config.js", "package.config.cjs", "package.config.mjs"];
57
- function findConfigFile(cwd) {
58
- const pkgJsonPath = findConfig("package.json", {
59
- cwd
60
- });
61
- if (!pkgJsonPath) return void 0;
62
- const pkgPath = path.dirname(pkgJsonPath);
63
- for (const fileName of CONFIG_FILE_NAMES) {
64
- const configPath = path.resolve(pkgPath, fileName);
65
- const exists = fileExists(configPath);
66
- if (exists) {
67
- return configPath;
68
- }
69
- }
70
- return void 0;
71
- }
72
- async function loadConfig(options) {
73
- const {
74
- cwd
75
- } = options;
76
- const pkgPath = await pkgUp({
77
- cwd
78
- });
79
- if (!pkgPath) return void 0;
80
- const root = path.dirname(pkgPath);
81
- const configFile = await findConfigFile(root);
82
- if (!configFile) {
83
- return void 0;
84
- }
85
- if (!configFile.startsWith(cwd)) {
86
- return void 0;
87
- }
88
- const esbuildOptions = {
89
- extensions: [".js", ".mjs", ".ts"]
90
- };
91
- const {
92
- unregister
93
- } = globalThis.__DEV__ ? {
94
- unregister: () => void 0
95
- } : register(esbuildOptions);
96
- const mod = require(configFile);
97
- unregister();
98
- return (mod == null ? void 0 : mod.default) || mod || void 0;
99
- }
100
- function resolveConfigProperty(prop, initialValue) {
101
- if (!prop) return initialValue;
102
- if (typeof prop === "function") {
103
- return prop(initialValue);
104
- }
105
- return prop;
106
- }
107
- const DEFAULT_BROWSERSLIST_QUERY = ["> 0.2% and supports es6-module and supports es6-module-dynamic-import", "not dead", "not IE 11", "maintained node versions"];
108
- function isRecord(value) {
109
- return Boolean(value) && !Array.isArray(value) && typeof value === "object";
110
- }
111
- const pkgSchema = z.object({
112
- type: z.optional(z.enum(["commonjs", "module"])),
113
- name: z.string(),
114
- version: z.string(),
115
- license: z.string(),
116
- bin: z.optional(z.record(z.string())),
117
- dependencies: z.optional(z.record(z.string())),
118
- devDependencies: z.optional(z.record(z.string())),
119
- peerDependencies: z.optional(z.record(z.string())),
120
- source: z.optional(z.string()),
121
- main: z.optional(z.string()),
122
- browser: z.optional(z.record(z.string())),
123
- module: z.optional(z.string()),
124
- types: z.optional(z.string()),
125
- exports: z.optional(z.record(z.union([z.custom(val => /^\.\/.*\.json$/.test(val)), z.object({
126
- types: z.optional(z.string()),
127
- source: z.string(),
128
- require: z.optional(z.string()),
129
- browser: z.optional(z.object({
130
- source: z.string(),
131
- require: z.optional(z.string()),
132
- import: z.optional(z.string())
133
- })),
134
- node: z.optional(z.object({
135
- source: z.optional(z.string()),
136
- require: z.optional(z.string()),
137
- import: z.optional(z.string())
138
- })),
139
- import: z.optional(z.string()),
140
- default: z.string()
141
- })]))),
142
- browserslist: z.optional(z.array(z.string()))
143
- });
144
- function validatePkg(input) {
145
- return pkgSchema.parse(input);
146
- }
147
- async function loadPkg(options) {
148
- const {
149
- cwd
150
- } = options;
151
- const pkgPath = await pkgUp({
152
- cwd
153
- });
154
- if (!pkgPath) throw new Error("no package.json found");
155
- const buf = await fs.readFile(pkgPath);
156
- const raw = JSON.parse(buf.toString());
157
- validatePkg(raw);
158
- return raw;
159
- }
160
- function assertFirst(a, arr) {
161
- const aIdx = arr.indexOf(a);
162
- if (aIdx === -1) {
163
- return true;
164
- }
165
- return aIdx === 0;
166
- }
167
- function assertLast(a, arr) {
168
- const aIdx = arr.indexOf(a);
169
- if (aIdx === -1) {
170
- return true;
171
- }
172
- return aIdx === arr.length - 1;
173
- }
174
- function assertOrder(a, b, arr) {
175
- const aIdx = arr.indexOf(a);
176
- const bIdx = arr.indexOf(b);
177
- if (aIdx === -1 || bIdx === -1) {
178
- return true;
179
- }
180
- return aIdx < bIdx;
181
- }
182
- async function loadPkgWithReporting(options) {
183
- const {
184
- cwd,
185
- logger
186
- } = options;
187
- try {
188
- const pkg = await loadPkg({
189
- cwd
190
- });
191
- if (pkg.exports) {
192
- const _exports = Object.entries(pkg.exports);
193
- for (const [expPath, exp] of _exports) {
194
- if (typeof exp === "string") {
195
- continue;
196
- }
197
- const keys = Object.keys(exp);
198
- if (!assertFirst("types", keys)) {
199
- logger.warn("exports[\"".concat(expPath, "\"]: the `types` property should be the first property"));
200
- }
201
- if (!assertOrder("require", "import", keys)) {
202
- logger.warn("exports[\"".concat(expPath, "\"]: the `require` property should come before the `import` property"));
203
- }
204
- if (!assertOrder("require", "node", keys)) {
205
- logger.warn("exports[\"".concat(expPath, "\"]: the `require` property should come before the `node` property"));
206
- }
207
- if (!assertOrder("node", "import", keys)) {
208
- logger.warn("exports[\"".concat(expPath, "\"]: the `node` property should come before `import` property"));
209
- }
210
- if (!assertLast("default", keys)) {
211
- logger.warn("exports[\"".concat(expPath, "\"]: the `default` property should be the last property"));
212
- }
213
- }
214
- }
215
- return pkg;
216
- } catch (err) {
217
- if (err instanceof ZodError) {
218
- for (const issue of err.issues) {
219
- if (issue.code === "invalid_type") {
220
- logger.error(["`".concat(formatPath(issue.path), "` "), "in `./package.json` must be of type ".concat(chalk.magenta(issue.expected), " "), "(received ".concat(chalk.magenta(issue.received), ")")].join(""));
221
- continue;
222
- }
223
- logger.error(issue);
224
- }
225
- } else {
226
- logger.error(err);
227
- }
228
- process.exit(1);
229
- }
230
- }
231
- function formatPath(segments) {
232
- return segments.map((s, idx) => {
233
- if (idx === 0) return s;
234
- if (typeof s === "number") {
235
- return "[".concat(s, "]");
236
- }
237
- if (s.startsWith(".")) {
238
- return "[\"".concat(s, "\"]");
239
- }
240
- return ".".concat(s);
241
- }).join("");
242
- }
243
- function validateExports(_exports, options) {
244
- const {
245
- extMap,
246
- pkg
247
- } = options;
248
- const ext = extMap[pkg.type || "commonjs"];
249
- const errors = [];
250
- for (const exp of _exports) {
251
- if (exp.require && !exp.require.endsWith(ext.commonjs)) {
252
- errors.push("package.json with `type: \"".concat(pkg.type, "\"` - `exports[\"").concat(exp._path, "\"].require` must end with \"").concat(ext.commonjs, "\""));
253
- }
254
- if (exp.import && !exp.import.endsWith(ext.esm)) {
255
- errors.push("package.json with `type: \"".concat(pkg.type, "\"` - `exports[\"").concat(exp._path, "\"].import` must end with \"").concat(ext.esm, "\""));
256
- }
257
- }
258
- return errors;
259
- }
260
- function parseExports(options) {
261
- const {
262
- extMap,
263
- pkg,
264
- strict
265
- } = options;
266
- const rootExport = {
267
- _exported: true,
268
- _path: ".",
269
- types: pkg.types,
270
- source: pkg.source || "",
271
- browser: pkg.browser && {
272
- source: pkg.source || "",
273
- require: pkg.main && pkg.browser[pkg.main],
274
- import: pkg.module && pkg.browser[pkg.module]
275
- },
276
- require: pkg.main,
277
- import: pkg.module,
278
- default: pkg.module || pkg.main || ""
279
- };
280
- const extraExports = [];
281
- const errors = [];
282
- if (pkg.exports) {
283
- if (strict && !pkg.exports["./package.json"]) {
284
- errors.push('package.json: `exports["./package.json"] must be declared.');
285
- }
286
- for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {
287
- if (exportPath.endsWith(".json")) {
288
- if (exportPath === "./package.json") {
289
- if (exportEntry !== "./package.json") {
290
- errors.push('package.json: `exports["./package.json"] must be "./package.json".');
291
- }
292
- }
293
- } else if (isRecord(exportEntry)) {
294
- if (exportPath === ".") {
295
- if (exportEntry.require && rootExport.require && exportEntry.require !== rootExport.require) {
296
- errors.push('package.json: mismatch between "main" and "exports.require". These must be equal.');
297
- }
298
- if (exportEntry.import && rootExport.import && exportEntry.import !== rootExport.import) {
299
- errors.push('package.json: mismatch between "module" and "exports.import" These must be equal.');
300
- }
301
- if (exportEntry.types && rootExport.types && exportEntry.types !== rootExport.types) {
302
- errors.push('package.json: mismatch between "types" and "exports.types". These must be equal.');
303
- }
304
- if (exportEntry.source && rootExport.source && exportEntry.source !== rootExport.source) {
305
- errors.push('package.json: mismatch between "source" and "exports.source". These must be equal.');
306
- }
307
- Object.assign(rootExport, exportEntry);
308
- } else {
309
- const extraExport = {
310
- _exported: true,
311
- _path: exportPath,
312
- ...exportEntry
313
- };
314
- extraExports.push(extraExport);
315
- }
316
- } else {
317
- errors.push("package.json: exports must be an object");
318
- }
319
- }
320
- }
321
- const _exports = [rootExport, ...extraExports];
322
- errors.push(...validateExports(_exports, {
323
- extMap,
324
- pkg
325
- }));
326
- if (errors.length) {
327
- throw new Error("\n- " + errors.join("\n- "));
328
- }
329
- return _exports;
330
- }
331
- const DEFAULT_PKG_EXT_MAP = {
332
- // pkg.type: "commonjs"
333
- commonjs: {
334
- commonjs: ".js",
335
- esm: ".mjs"
336
- },
337
- // pkg.type: "module"
338
- module: {
339
- commonjs: ".cjs",
340
- esm: ".js"
341
- }
342
- };
343
- function getPkgExtMap(options) {
344
- const {
345
- legacyExports
346
- } = options;
347
- const ret = {
348
- ...DEFAULT_PKG_EXT_MAP
349
- };
350
- if (legacyExports) {
351
- ret["commonjs"] = {
352
- commonjs: ".js",
353
- esm: ".esm.js"
354
- };
355
- }
356
- return ret;
357
- }
358
- const promptsTypes = {
359
- string: "text"
360
- };
361
- async function createFromTemplate(options) {
362
- const {
363
- cwd,
364
- logger,
365
- packagePath,
366
- template: templateOrResolver
367
- } = options;
368
- const template = typeof templateOrResolver === "function" ? await templateOrResolver({
369
- cwd,
370
- logger,
371
- packagePath
372
- }) : templateOrResolver;
373
- logger.log("create new package at", relative(cwd, packagePath));
374
- const templateOptions = {};
375
- for (const templateOption of template.options) {
376
- const templateValidate = templateOption.validate;
377
- const res = await prompts({
378
- type: promptsTypes[templateOption.type],
379
- name: templateOption.name,
380
- message: templateOption.description,
381
- validate: templateValidate ? prev => templateValidate(prev) : void 0,
382
- initial: typeof templateOption.initial === "function" ? templateOption.initial(templateOptions) : templateOption.initial
383
- }, {
384
- onCancel: () => process.exit(0)
385
- });
386
- templateOptions[templateOption.name] = templateOption.parse ? templateOption.parse(res[templateOption.name]) : res[templateOption.name];
387
- }
388
- const features = {};
389
- for (const templateFeature of template.features) {
390
- const res = templateFeature.optional ? await prompts({
391
- type: "confirm",
392
- name: "confirm",
393
- message: "use ".concat(templateFeature.name, "?"),
394
- initial: templateFeature.initial
395
- }, {
396
- onCancel: () => process.exit(0)
397
- }) : void 0;
398
- features[templateFeature.name] = (res == null ? void 0 : res.confirm) || !templateFeature.optional;
399
- }
400
- const files = await template.getFiles(templateOptions, features);
401
- files.sort((a, b) => {
402
- return a.name.localeCompare(b.name);
403
- });
404
- for (const file of files) {
405
- const filePath = resolve(packagePath, file.name);
406
- await mkdirp(dirname(filePath));
407
- await writeFile(filePath, file.contents.trim() + "\n");
408
- logger.success("wrote ".concat(relative(cwd, filePath)));
409
- }
410
- }
411
- function defineTemplateOption(option) {
412
- return option;
413
- }
414
- async function loadTSConfig(options) {
415
- const {
416
- cwd,
417
- tsconfigPath
418
- } = options;
419
- const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath);
420
- if (!configPath) {
421
- throw new Error("could not find a valid '".concat(tsconfigPath, "'"));
422
- }
423
- const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
424
- return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd);
425
- }
426
- function createLogger() {
427
- return {
428
- /* eslint-disable no-console */
429
- log: function () {
430
- console.log(...arguments);
431
- },
432
- info: function () {
433
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
434
- args[_key] = arguments[_key];
435
- }
436
- console.log(chalk.blue("[info]"), ...args);
437
- },
438
- warn: function () {
439
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
440
- args[_key2] = arguments[_key2];
441
- }
442
- console.log(chalk.yellow("[warning]"), ...args);
443
- },
444
- error: function () {
445
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
446
- args[_key3] = arguments[_key3];
447
- }
448
- console.log(chalk.red("[error]"), ...args);
449
- },
450
- success: function () {
451
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
452
- args[_key4] = arguments[_key4];
453
- }
454
- console.log(chalk.green("[success]"), ...args);
455
- }
456
- /* eslint-enable no-console */
457
- };
458
- }
459
-
460
- function pathContains(containerPath, itemPath) {
461
- return !path.relative(containerPath, itemPath).startsWith("..");
462
- }
463
- function findCommonDirPath(filePaths) {
464
- let ret = void 0;
465
- for (const filePath of filePaths) {
466
- let dirPath = path.dirname(filePath);
467
- if (!ret) {
468
- ret = dirPath;
469
- continue;
470
- }
471
- while (dirPath !== ret) {
472
- dirPath = path.dirname(dirPath);
473
- if (dirPath === ret) {
474
- break;
475
- }
476
- if (pathContains(dirPath, ret)) {
477
- ret = dirPath;
478
- break;
479
- }
480
- if (dirPath === ".") return void 0;
481
- }
482
- }
483
- return ret;
484
- }
485
- function sortAsNumber(a, b) {
486
- const aVersion = Number(a);
487
- const bVersion = Number(b);
488
- return aVersion - bVersion;
489
- }
490
- function resolveBrowserslistVersions(query) {
491
- const result = browserslist(query);
492
- const entries = result.map(key => {
493
- const [name, version] = key.split(" ");
494
- return {
495
- name,
496
- version: version.split("-")[0].split(".")[0]
497
- };
498
- });
499
- const andChr = entries.filter(b => b.name === "and_chr");
500
- const andFf = entries.filter(b => b.name === "and_ff");
501
- const chrome = entries.filter(b => b.name === "chrome");
502
- const edge = entries.filter(b => b.name === "edge");
503
- const ff = entries.filter(b => b.name === "firefox");
504
- const iosSaf = entries.filter(b => b.name === "ios_saf");
505
- const saf = entries.filter(b => b.name === "safari");
506
- const opera = entries.filter(b => b.name === "opera");
507
- const node = entries.filter(b => b.name === "node");
508
- const versions = {
509
- chrome: andChr.concat(chrome).map(b => b.version),
510
- ff: andFf.concat(ff).map(b => b.version),
511
- edge: edge.map(b => b.version),
512
- iosSaf: iosSaf.map(b => b.version),
513
- saf: saf.map(b => b.version),
514
- opera: opera.map(b => b.version),
515
- node: node.map(b => b.version)
516
- };
517
- versions.chrome.sort(sortAsNumber);
518
- versions.ff.sort(sortAsNumber);
519
- versions.edge.sort(sortAsNumber);
520
- versions.iosSaf.sort(sortAsNumber);
521
- versions.saf.sort(sortAsNumber);
522
- versions.opera.sort(sortAsNumber);
523
- versions.node.sort(sortAsNumber);
524
- return versions;
525
- }
526
- function resolveBrowserTarget(versions) {
527
- const target = [];
528
- if (versions.chrome.length) {
529
- target.push("chrome".concat(versions.chrome[0]));
530
- }
531
- if (versions.ff.length) {
532
- target.push("firefox".concat(versions.ff[0]));
533
- }
534
- if (versions.edge.length) {
535
- target.push("edge".concat(versions.edge[0]));
536
- }
537
- if (versions.iosSaf.length) {
538
- target.push("ios".concat(versions.iosSaf[0]));
539
- }
540
- if (versions.saf.length) {
541
- target.push("safari".concat(versions.saf[0]));
542
- }
543
- if (versions.opera.length) {
544
- target.push("opera".concat(versions.opera[0]));
545
- }
546
- if (target.length === 0) {
547
- return void 0;
548
- }
549
- return target;
550
- }
551
- function resolveNodeTarget(versions) {
552
- const target = [];
553
- if (versions.node.length) {
554
- target.push("node".concat(versions.node[0]));
555
- }
556
- if (target.length === 0) {
557
- return void 0;
558
- }
559
- return target;
560
- }
561
- async function resolveBuildContext(options) {
562
- var _ref;
563
- const {
564
- config,
565
- cwd,
566
- emitDeclarationOnly = false,
567
- extMap,
568
- logger,
569
- pkg,
570
- strict,
571
- tsconfig: tsconfigPath
572
- } = options;
573
- const tsconfig = await loadTSConfig({
574
- cwd,
575
- tsconfigPath
576
- });
577
- const targetVersions = resolveBrowserslistVersions(pkg.browserslist || DEFAULT_BROWSERSLIST_QUERY);
578
- const nodeTarget = resolveNodeTarget(targetVersions);
579
- const webTarget = resolveBrowserTarget(targetVersions);
580
- if (!nodeTarget) {
581
- throw new Error("no matching `node` target");
582
- }
583
- if (!webTarget) {
584
- throw new Error("no matching `web` target");
585
- }
586
- const target = {
587
- "*": webTarget.concat(nodeTarget),
588
- browser: webTarget,
589
- node: nodeTarget
590
- };
591
- const parsedExports = parseExports({
592
- extMap,
593
- pkg,
594
- strict
595
- }).reduce((acc, x) => {
596
- const {
597
- _path: exportPath,
598
- ...exportEntry
599
- } = x;
600
- return {
601
- ...acc,
602
- [exportPath]: exportEntry
603
- };
604
- }, {});
605
- const exports = resolveConfigProperty(config == null ? void 0 : config.exports, parsedExports);
606
- const parsedExternal = [...(pkg.dependencies ? Object.keys(pkg.dependencies) : []), ...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : [])];
607
- const external = config && Array.isArray(config.external) ? [...parsedExternal, ...config.external] : resolveConfigProperty(config == null ? void 0 : config.external, parsedExternal);
608
- const outputPaths = Object.values(exports).flatMap(exportEntry => {
609
- var _a, _b, _c, _d;
610
- 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.source) && exportEntry.node.import, ((_d = exportEntry.node) == null ? void 0 : _d.source) && exportEntry.node.require].filter(Boolean);
611
- }).map(p => path.resolve(cwd, p));
612
- const commonDistPath = findCommonDirPath(outputPaths);
613
- if (commonDistPath === cwd) {
614
- throw new Error("all output files must share a common parent directory which is not the root package directory");
615
- }
616
- if (commonDistPath && !pathContains(cwd, commonDistPath)) {
617
- throw new Error("all output files must be located within the package");
618
- }
619
- const configDistPath = (config == null ? void 0 : config.dist) ? path.resolve(cwd, config.dist) : void 0;
620
- if (configDistPath && commonDistPath && configDistPath !== commonDistPath && !pathContains(configDistPath, commonDistPath)) {
621
- logger.log("did you mean to configure `dist: './".concat(path.relative(cwd, commonDistPath), "'`?"));
622
- throw new Error("all output files must be located with the configured `dist` path");
623
- }
624
- const distPath = configDistPath || commonDistPath;
625
- if (!distPath) {
626
- throw new Error("could not detect `dist` path");
627
- }
628
- const ctx = {
629
- config,
630
- cwd,
631
- distPath,
632
- emitDeclarationOnly,
633
- exports,
634
- external,
635
- extMap,
636
- files: [],
637
- logger,
638
- pkg,
639
- runtime: (_ref = config == null ? void 0 : config.runtime) !== null && _ref !== void 0 ? _ref : "*",
640
- strict,
641
- target,
642
- ts: {
643
- config: tsconfig,
644
- configPath: tsconfigPath
645
- }
646
- };
647
- return ctx;
648
- }
649
- function resolveBuildTasks(ctx) {
650
- var _a, _b, _c, _d, _e;
651
- const {
652
- config,
653
- cwd,
654
- pkg,
655
- target
656
- } = ctx;
657
- const bundles = (config == null ? void 0 : config.bundles) || [];
658
- const tasks = [];
659
- const exports = Object.entries(ctx.exports || {}).map(_ref2 => {
660
- let [_path, exp] = _ref2;
661
- return {
662
- _path,
663
- ...exp
664
- };
665
- });
666
- const dtsTask = {
667
- type: "build:dts",
668
- entries: []
669
- };
670
- const rollupTasks = {};
671
- function addRollupTaskEntry(format, runtime, entry) {
672
- const buildId = "".concat(format, ":").concat(runtime);
673
- if (rollupTasks[buildId]) {
674
- rollupTasks[buildId].entries.push(entry);
675
- } else {
676
- rollupTasks[buildId] = {
677
- type: "build:js",
678
- buildId,
679
- entries: [entry],
680
- runtime,
681
- format,
682
- target: target[runtime]
683
- };
684
- }
685
- }
686
- for (const exp of exports) {
687
- const importId = path.join(pkg.name, exp._path);
688
- if (exp.types) {
689
- dtsTask.entries.push({
690
- importId,
691
- exportPath: exp._path,
692
- sourcePath: exp.source,
693
- targetPath: exp.types
694
- });
695
- }
696
- }
697
- if (dtsTask.entries.length) {
698
- tasks.push(dtsTask);
699
- }
700
- if (!ctx.emitDeclarationOnly) {
701
- for (const exp of exports) {
702
- const output = exp.require;
703
- if (!output) continue;
704
- addRollupTaskEntry("commonjs", ctx.runtime, {
705
- path: exp._path,
706
- source: exp.source,
707
- output
708
- });
709
- }
710
- for (const exp of exports) {
711
- const output = exp.import;
712
- if (!output) continue;
713
- addRollupTaskEntry("esm", ctx.runtime, {
714
- path: exp._path,
715
- source: exp.source,
716
- output
717
- });
718
- }
719
- for (const exp of exports) {
720
- const output = (_a = exp.browser) == null ? void 0 : _a.require;
721
- if (!output) continue;
722
- addRollupTaskEntry("commonjs", "browser", {
723
- path: exp._path,
724
- source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
725
- output
726
- });
727
- }
728
- for (const exp of exports) {
729
- const output = (_c = exp.browser) == null ? void 0 : _c.import;
730
- if (!output) continue;
731
- addRollupTaskEntry("esm", "browser", {
732
- path: exp._path,
733
- source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
734
- output
735
- });
736
- }
737
- for (const bundle of bundles) {
738
- const idx = bundles.indexOf(bundle);
739
- if (bundle.require) {
740
- addRollupTaskEntry("commonjs", bundle.runtime || ctx.runtime, {
741
- path: "__$$bundle_cjs_".concat(idx, "$$__"),
742
- source: bundle.source,
743
- output: bundle.require
744
- });
745
- }
746
- if (bundle.import) {
747
- addRollupTaskEntry("esm", bundle.runtime || ctx.runtime, {
748
- path: "__$$bundle_esm_".concat(idx, "$$__"),
749
- source: bundle.source,
750
- output: bundle.import
751
- });
752
- }
753
- }
754
- tasks.push(...Object.values(rollupTasks));
755
- if (config == null ? void 0 : config.legacyExports) {
756
- for (const exp of exports) {
757
- if (exp._exported && exp._path !== ".") {
758
- const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
759
- if (relativeTargetPath) {
760
- fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
761
- }
762
- }
763
- }
764
- }
765
- }
766
- const nodeReexportCjsEntries = [];
767
- for (const exp of exports) {
768
- if (exp.node && !exp.node.source && exp.node.import && exp.node.require && (exp.node.import.endsWith(".cjs.js") || exp.node.import.endsWith(".cjs.mjs"))) {
769
- const importId = path.join(pkg.name, exp._path);
770
- nodeReexportCjsEntries.push({
771
- importId,
772
- import: exp.node.import,
773
- require: exp.node.require
774
- });
775
- }
776
- }
777
- if (nodeReexportCjsEntries.length) {
778
- tasks.push({
779
- type: "node:reexport-cjs",
780
- entries: nodeReexportCjsEntries
781
- });
782
- }
783
- return tasks;
784
- }
785
- function createSpinner(msg) {
786
- const startTime = Date.now();
787
- console.log(msg);
788
- return {
789
- complete: () => {
790
- console.log("".concat(chalk.green("[success]"), " ").concat(chalk.gray("".concat(Date.now() - startTime, "ms"))));
791
- },
792
- error: () => {
793
- console.log("".concat(chalk.red("[error]"), " ").concat(chalk.gray("".concat(Date.now() - startTime, "ms"))));
794
- }
795
- };
796
- }
797
- function printExtractMessages(ctx, messages) {
798
- const {
799
- cwd,
800
- logger
801
- } = ctx;
802
- const warnings = messages.filter(msg => msg.logLevel === "warning");
803
- if (warnings.length) {
804
- logger.log();
805
- }
806
- for (const msg of warnings) {
807
- const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
808
- if (msg.messageId === "TS6307") {
809
- continue;
810
- }
811
- 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(""));
812
- }
813
- const errors = messages.filter(msg => msg.logLevel === "error");
814
- if (!warnings.length && errors.length) {
815
- logger.log("");
816
- }
817
- for (const msg of errors) {
818
- const sourceFilePath = msg.sourceFilePath && path.relative(cwd, msg.sourceFilePath);
819
- 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(""));
820
- }
821
- if (errors.length) {
822
- process.exit(1);
823
- }
824
- }
825
- function printDiagnostic(options) {
826
- const {
827
- cwd,
828
- logger,
829
- diagnostic
830
- } = options;
831
- if (diagnostic.file && diagnostic.start) {
832
- const {
833
- line,
834
- character
835
- } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
836
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
837
- const file = path.relative(cwd, diagnostic.file.fileName);
838
- const output = ["".concat(chalk.yellow(file), ":").concat(chalk.blue(line + 1), ":").concat(chalk.blue(character + 1), " - "), "".concat(chalk.gray("TS".concat(diagnostic.code, ":")), " ").concat(message)].join("");
839
- if (diagnostic.category === ts.DiagnosticCategory.Error) {
840
- logger.error(output);
841
- }
842
- if (diagnostic.category === ts.DiagnosticCategory.Warning) {
843
- logger.warn(output);
844
- }
845
- if (diagnostic.category === ts.DiagnosticCategory.Message) {
846
- logger.log(output);
847
- }
848
- if (diagnostic.category === ts.DiagnosticCategory.Suggestion) {
849
- logger.log(output);
850
- }
851
- } else {
852
- logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
853
- }
854
- }
855
- async function buildTypes(options) {
856
- const {
857
- cwd,
858
- logger,
859
- outDir,
860
- tsconfig,
861
- strict = false
862
- } = options;
863
- const compilerOptions = {
864
- ...tsconfig.options,
865
- declaration: true,
866
- declarationDir: outDir,
867
- emitDeclarationOnly: true,
868
- noEmit: false,
869
- outDir
870
- };
871
- const program = ts.createProgram(tsconfig.fileNames, compilerOptions);
872
- const emitResult = program.emit();
873
- const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
874
- for (const diagnostic of allDiagnostics) {
875
- printDiagnostic({
876
- cwd,
877
- logger,
878
- diagnostic
879
- });
880
- }
881
- if (emitResult.emitSkipped) {
882
- const errors = allDiagnostics.filter(diag => diag.category === ts.DiagnosticCategory.Error);
883
- if (errors.length) {
884
- if (strict) {
885
- throw new Error("failed to compile TypeScript definitions");
886
- }
887
- }
888
- }
889
- }
890
- class DtsError extends Error {
891
- constructor(message, messages) {
892
- super(message);
893
- _defineProperty(this, "messages", void 0);
894
- this.messages = messages;
895
- }
896
- }
897
- function createApiExtractorConfig(options) {
898
- const {
899
- distPath,
900
- exportPath,
901
- filePath,
902
- messages,
903
- projectFolder,
904
- mainEntryPointFilePath,
905
- tsconfigPath
906
- } = options;
907
- return {
908
- apiReport: {
909
- enabled: false,
910
- reportFileName: "<unscopedPackageName>.api.md"
911
- },
912
- // bundledPackages: [],
913
- compiler: {
914
- tsconfigFilePath: tsconfigPath
915
- },
916
- docModel: {
917
- enabled: false,
918
- apiJsonFilePath: path.resolve(distPath, "".concat(exportPath, ".api.json"))
919
- },
920
- dtsRollup: {
921
- enabled: true,
922
- untrimmedFilePath: path.resolve(distPath, filePath)
923
- // betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
924
- // publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
925
- },
926
-
927
- tsdocMetadata: {
928
- enabled: false
929
- },
930
- messages,
931
- mainEntryPointFilePath,
932
- projectFolder
933
- };
934
- }
935
- async function createTSDocConfig(opts) {
936
- const {
937
- customTags
938
- } = opts;
939
- if (customTags.length === 0) {
940
- return void 0;
941
- }
942
- const tsDocBaseBuf = await readFile(require.resolve("@microsoft/api-extractor/extends/tsdoc-base.json"));
943
- const tsDocBaseConfig = parse(tsDocBaseBuf.toString());
944
- const tagDefinitions = (tsDocBaseConfig.tagDefinitions || []).concat(customTags.map(t => ({
945
- tagName: "@".concat(t.name),
946
- syntaxKind: t.syntaxKind,
947
- allowMultiple: t.allowMultiple
948
- })));
949
- const supportForTags = {
950
- ...tsDocBaseConfig.supportForTags
951
- };
952
- for (const customTag of customTags) {
953
- supportForTags["@".concat(customTag.name)] = true;
954
- }
955
- return TSDocConfigFile.loadFromObject({
956
- ...tsDocBaseConfig,
957
- noStandardTags: false,
958
- tagDefinitions,
959
- supportForTags
960
- });
961
- }
962
- async function extractModuleBlocksFromTypes(_ref3) {
963
- let {
964
- tsOutDir,
965
- extractResult
966
- } = _ref3;
967
- const program = extractResult.compilerState.program;
968
- const moduleBlocks = [];
969
- const allProgramFiles = [...program.getSourceFiles()];
970
- const sourceFiles = allProgramFiles.filter(sourceFile => sourceFile.fileName.includes(tsOutDir));
971
- for (const sourceFile of sourceFiles) {
972
- if (sourceFile.text.includes("declare module")) {
973
- moduleBlocks.push(...extractModuleBlocks(sourceFile.text));
974
- }
975
- }
976
- return moduleBlocks;
977
- }
978
- function extractModuleBlocks(fileContent) {
979
- const ast = parse$1(fileContent, {
980
- parser: typeScriptParser
981
- });
982
- return ast.program.body.filter(node => node.type === "TSModuleDeclaration").map(node => print(node).code);
983
- }
984
- const LOG_LEVELS = {
985
- error: "error",
986
- info: "info",
987
- off: "none",
988
- warn: "warning"
989
- };
990
- function getExtractMessagesConfig(options) {
991
- const {
992
- rules
993
- } = options;
994
- function ruleToLogLevel(key, defaultLevel) {
995
- const r = rules == null ? void 0 : rules[key];
996
- return r ? LOG_LEVELS[r] : defaultLevel || "warning";
997
- }
998
- return {
999
- compilerMessageReporting: {
1000
- default: {
1001
- logLevel: "warning"
1002
- }
1003
- },
1004
- extractorMessageReporting: {
1005
- default: {
1006
- logLevel: "warning",
1007
- addToApiReportFile: false
1008
- },
1009
- "ae-forgotten-export": {
1010
- logLevel: ruleToLogLevel("ae-forgotten-export", "error"),
1011
- addToApiReportFile: false
1012
- },
1013
- "ae-incompatible-release-tags": {
1014
- logLevel: ruleToLogLevel("ae-incompatible-release-tags", "error"),
1015
- addToApiReportFile: false
1016
- },
1017
- "ae-internal-missing-underscore": {
1018
- logLevel: ruleToLogLevel("ae-internal-missing-underscore"),
1019
- addToApiReportFile: false
1020
- },
1021
- "ae-missing-release-tag": {
1022
- logLevel: ruleToLogLevel("ae-missing-release-tag", "error"),
1023
- addToApiReportFile: false
1024
- },
1025
- "ae-wrong-input-file-type": {
1026
- logLevel: "none",
1027
- addToApiReportFile: false
1028
- }
1029
- },
1030
- tsdocMessageReporting: {
1031
- default: {
1032
- logLevel: "warning",
1033
- addToApiReportFile: false
1034
- },
1035
- "tsdoc-link-tag-unescaped-text": {
1036
- logLevel: ruleToLogLevel("tsdoc-link-tag-unescaped-text", "warning"),
1037
- addToApiReportFile: false
1038
- },
1039
- "tsdoc-undefined-tag": {
1040
- logLevel: ruleToLogLevel("tsdoc-undefined-tag", "error"),
1041
- addToApiReportFile: false
1042
- },
1043
- "tsdoc-unsupported-tag": {
1044
- logLevel: ruleToLogLevel("tsdoc-unsupported-tag", "none"),
1045
- addToApiReportFile: false
1046
- }
1047
- }
1048
- };
1049
- }
1050
- async function extractTypes(options) {
1051
- const {
1052
- customTags,
1053
- distPath,
1054
- exportPath,
1055
- files,
1056
- filePath,
1057
- projectPath,
1058
- rules,
1059
- sourceTypesPath,
1060
- tmpPath,
1061
- tsconfigPath
1062
- } = options;
1063
- const tsdocConfigFile = await createTSDocConfig({
1064
- customTags: customTags || []
1065
- });
1066
- const extractorConfig = ExtractorConfig.prepare({
1067
- configObject: createApiExtractorConfig({
1068
- distPath,
1069
- exportPath,
1070
- filePath,
1071
- messages: getExtractMessagesConfig({
1072
- rules
1073
- }),
1074
- projectFolder: projectPath,
1075
- mainEntryPointFilePath: sourceTypesPath,
1076
- tsconfigPath
1077
- }),
1078
- configObjectFullPath: void 0,
1079
- tsdocConfigFile,
1080
- packageJsonFullPath: path.resolve(projectPath, "package.json")
1081
- });
1082
- const messages = [];
1083
- const extractorResult = Extractor.invoke(extractorConfig, {
1084
- // Equivalent to the "--local" command-line parameter
1085
- localBuild: true,
1086
- // Equivalent to the "--verbose" command-line parameter
1087
- showVerboseMessages: true,
1088
- // handle messages
1089
- messageCallback(message) {
1090
- messages.push(message);
1091
- message.handled = true;
1092
- }
1093
- });
1094
- const typesPath = path.resolve(distPath, filePath);
1095
- const typesBuf = await fs.readFile(typesPath);
1096
- const prettierConfig = await prettier.resolveConfig(typesPath);
1097
- await mkdirp(path.dirname(typesPath));
1098
- const moduleBlocks = await extractModuleBlocksFromTypes({
1099
- extractResult: extractorResult,
1100
- tsOutDir: tmpPath
1101
- });
1102
- const code = [typesBuf.toString(), ...moduleBlocks].join("\n\n");
1103
- await fs.writeFile(typesPath, await prettier.format(code, {
1104
- ...prettierConfig,
1105
- filepath: typesPath
1106
- }));
1107
- files.push({
1108
- type: "types",
1109
- path: typesPath
1110
- });
1111
- return {
1112
- extractorResult,
1113
- messages
1114
- };
1115
- }
1116
- async function doExtract(ctx, task) {
1117
- var _a, _b;
1118
- const {
1119
- config,
1120
- cwd,
1121
- files,
1122
- logger,
1123
- strict,
1124
- ts
1125
- } = ctx;
1126
- if (!ts.config || !ts.configPath) {
1127
- return {
1128
- type: "dts",
1129
- messages: [],
1130
- results: []
1131
- };
1132
- }
1133
- const {
1134
- outDir,
1135
- rootDir = cwd
1136
- } = ts.config.options;
1137
- if (!outDir) {
1138
- throw new Error("tsconfig.json is missing `compilerOptions.outDir`");
1139
- }
1140
- const tmpPath = path.resolve(outDir, "__tmp__");
1141
- await buildTypes({
1142
- cwd,
1143
- logger,
1144
- outDir: tmpPath,
1145
- strict,
1146
- tsconfig: ts.config
1147
- });
1148
- const messages = [];
1149
- const results = [];
1150
- for (const entry of task.entries) {
1151
- const exportPath = entry.exportPath === "." ? "./index" : entry.exportPath;
1152
- const sourceTypesPath = path.resolve(tmpPath, path.relative(rootDir, path.resolve(cwd, entry.sourcePath)).replace(/\.ts$/, ".d.ts"));
1153
- const targetPath = path.resolve(cwd, entry.targetPath);
1154
- const filePath = path.relative(outDir, targetPath);
1155
- const result = await extractTypes({
1156
- customTags: (_a = config == null ? void 0 : config.extract) == null ? void 0 : _a.customTags,
1157
- cwd,
1158
- distPath: outDir,
1159
- exportPath,
1160
- files,
1161
- filePath,
1162
- projectPath: cwd,
1163
- rules: (_b = config == null ? void 0 : config.extract) == null ? void 0 : _b.rules,
1164
- sourceTypesPath,
1165
- tmpPath,
1166
- tsconfigPath: path.resolve(cwd, ts.configPath || "tsconfig.json")
1167
- });
1168
- messages.push(...result.messages);
1169
- if (result.messages.some(msg => msg.logLevel === "error")) {
1170
- await rimraf(tmpPath);
1171
- throw new DtsError("encountered errors when extracting types", result.messages);
1172
- }
1173
- results.push({
1174
- sourcePath: path.resolve(cwd, entry.sourcePath),
1175
- filePath: targetPath
1176
- });
1177
- }
1178
- await rimraf(tmpPath);
1179
- return {
1180
- type: "dts",
1181
- messages,
1182
- results
1183
- };
1184
- }
1185
- const dtsTask = {
1186
- name: (_ctx, task) => ["Build type definitions...", " entries:", ...task.entries.map(entry => [" - ".concat(chalk.cyan(entry.importId), ": "), "".concat(chalk.yellow(entry.sourcePath), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(entry.targetPath))].join(""))].join("\n"),
1187
- exec: (ctx, task) => {
1188
- return new Observable(observer => {
1189
- doExtract(ctx, task).then(result => {
1190
- observer.next(result);
1191
- observer.complete();
1192
- }).catch(err => {
1193
- observer.error(err);
1194
- });
1195
- });
1196
- },
1197
- complete: (ctx, _task, result) => {
1198
- printExtractMessages(ctx, result.messages);
1199
- },
1200
- error: (ctx, _task, err) => {
1201
- const {
1202
- logger
1203
- } = ctx;
1204
- if (err instanceof DtsError) {
1205
- printExtractMessages(ctx, err.messages);
1206
- } else if (err instanceof Error) {
1207
- logger.error(err);
1208
- }
1209
- }
1210
- };
1211
- const dtsWatchTask = {
1212
- name: (_ctx, task) => ["build type definitions", ...task.entries.map(entry => " ".concat(chalk.blue(entry.importId), ": ").concat(entry.sourcePath, " -> ").concat(entry.targetPath))].join("\n"),
1213
- exec: (ctx, task) => {
1214
- return new Observable(observer => {
1215
- doExtract(ctx, task).then(result => {
1216
- observer.next(result);
1217
- observer.complete();
1218
- }).catch(err => observer.error(err));
1219
- });
1220
- },
1221
- complete: (ctx, _task, result) => {
1222
- const {
1223
- logger
1224
- } = ctx;
1225
- printExtractMessages(ctx, result.messages);
1226
- logger.warn("watching typescript definitions is currently not supported");
1227
- logger.log();
1228
- },
1229
- error: (ctx, _task, err) => {
1230
- const {
1231
- logger
1232
- } = ctx;
1233
- if (err instanceof DtsError) {
1234
- printExtractMessages(ctx, err.messages);
1235
- } else if (err instanceof Error) {
1236
- logger.error(err);
1237
- }
1238
- }
1239
- };
1240
- const nodeReexportCjsTask = {
1241
- name: (_ctx, task) => ["Re-export CommonJS module in ESM wrapper\u2026", " entries:", ...task.entries.map(entry => [" - ".concat(chalk.cyan(entry.importId), ": "), "".concat(chalk.yellow(entry.require), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(entry.import))].join(""))].join("\n"),
1242
- exec: (ctx, task) => {
1243
- return from(exec(ctx, task));
1244
- },
1245
- complete: () => {},
1246
- error: (_ctx, _task, err) => {
1247
- console.error(err);
1248
- }
1249
- };
1250
- async function exec(ctx, task) {
1251
- const {
1252
- cwd
1253
- } = ctx;
1254
- for (const entry of task.entries) {
1255
- const sourcePath = path.resolve(cwd, entry.require);
1256
- const targetPath = path.resolve(cwd, entry.import);
1257
- const targetDir = path.dirname(targetPath);
1258
- await mkdirp(targetDir);
1259
- const mod = require(sourcePath);
1260
- let relativeImport = "./".concat(path.relative(targetDir, sourcePath));
1261
- if (relativeImport.startsWith("./.")) {
1262
- relativeImport = relativeImport.slice(2);
1263
- }
1264
- const code = compileESMWrapper(mod, relativeImport);
1265
- await writeFile(targetPath, code, "utf8");
1266
- }
1267
- }
1268
- function compileESMWrapper(mod, relativeImport) {
1269
- const keys = Object.keys(mod).filter(k => k !== "__esModule");
1270
- let code = "import cjs from '".concat(relativeImport, "';\n");
1271
- if (keys.length) {
1272
- code += "\n";
1273
- code += keys.filter(k => mod.__esModule ? k !== "default" : true).map(k => "export const ".concat(k, " = cjs.").concat(k, ";\n")).join("");
1274
- }
1275
- code += "\n";
1276
- if (mod.__esModule) {
1277
- if ("default" in keys) {
1278
- code += "export default cjs.default;\n";
1279
- }
1280
- } else {
1281
- code += "export default cjs;\n";
1282
- }
1283
- return code;
1284
- }
1285
- function createConsoleSpy(options) {
1286
- const {
1287
- onRestored
1288
- } = options || {};
1289
- const original = {
1290
- log: console.log,
1291
- warn: console.warn,
1292
- error: console.error
1293
- };
1294
- const messages = [];
1295
- console.log = function () {
1296
- for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
1297
- args[_key5] = arguments[_key5];
1298
- }
1299
- return messages.push({
1300
- type: "log",
1301
- args
1302
- });
1303
- };
1304
- console.warn = function () {
1305
- for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
1306
- args[_key6] = arguments[_key6];
1307
- }
1308
- return messages.push({
1309
- type: "warn",
1310
- args
1311
- });
1312
- };
1313
- console.error = function () {
1314
- for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
1315
- args[_key7] = arguments[_key7];
1316
- }
1317
- return messages.push({
1318
- type: "error",
1319
- args
1320
- });
1321
- };
1322
- return {
1323
- messages,
1324
- restore: () => {
1325
- console.log = original.log;
1326
- console.warn = original.warn;
1327
- console.error = original.error;
1328
- onRestored == null ? void 0 : onRestored(messages);
1329
- }
1330
- };
1331
- }
1332
- function resolveRollupConfig(ctx, buildTask) {
1333
- var _ref4, _ref7, _ref8, _ref9, _ref10, _ref11;
1334
- var _a, _b, _c, _d;
1335
- const {
1336
- format,
1337
- runtime,
1338
- target
1339
- } = buildTask;
1340
- const {
1341
- config,
1342
- cwd,
1343
- exports: _exports,
1344
- extMap,
1345
- external,
1346
- distPath,
1347
- logger,
1348
- pkg,
1349
- ts
1350
- } = ctx;
1351
- const outputExt = extMap[pkg.type || "commonjs"][format];
1352
- const minify = (_ref4 = config == null ? void 0 : config.minify) !== null && _ref4 !== void 0 ? _ref4 : false;
1353
- const outDir = path.relative(cwd, distPath);
1354
- const pathAliases = Object.fromEntries(Object.entries(((_a = ts.config) == null ? void 0 : _a.options.paths) || {}).map(_ref5 => {
1355
- let [key, val] = _ref5;
1356
- var _a2;
1357
- return [key, path.resolve(cwd, ((_a2 = ts.config) == null ? void 0 : _a2.options.baseUrl) || ".", val[0])];
1358
- }));
1359
- const entries = buildTask.entries.map(entry => {
1360
- return {
1361
- ...entry,
1362
- name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
1363
- };
1364
- }, {});
1365
- const exportIds = _exports && Object.keys(_exports).map(exportPath => path.join(pkg.name, exportPath));
1366
- const sourcePaths = _exports && Object.values(_exports).map(e => path.resolve(cwd, e.source));
1367
- const replacements = Object.fromEntries(Object.entries((config == null ? void 0 : config.define) || {}).map(_ref6 => {
1368
- let [key, val] = _ref6;
1369
- return [key, JSON.stringify(val)];
1370
- }));
1371
- const defaultPlugins = [replace({
1372
- preventAssignment: true,
1373
- values: {
1374
- ...(pkg.name === "@sanity/pkg-utils" ? {
1375
- ...replacements
1376
- } : {
1377
- "process.env.PKG_FILE_PATH": arg => {
1378
- const sourcePath = "./" + path.relative(cwd, arg);
1379
- const entry = entries.find(e => e.source === sourcePath);
1380
- if (!entry) {
1381
- console.error("could not find source entry: ".concat(sourcePath));
1382
- return "null";
1383
- }
1384
- return JSON.stringify(path.relative(cwd, path.resolve(outDir, entry.name + outputExt)));
1385
- },
1386
- "process.env.PKG_FORMAT": JSON.stringify(format),
1387
- "process.env.PKG_RUNTIME": JSON.stringify(runtime),
1388
- "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version),
1389
- ...replacements
1390
- })
1391
- }
1392
- }), alias({
1393
- entries: {
1394
- ...pathAliases
1395
- }
1396
- }), nodeResolve({
1397
- // mainFields: ['module', 'jsnext', 'main'],
1398
- browser: runtime === "browser",
1399
- // exportConditions: [runtime === 'node' ? 'node' : 'browser'],
1400
- extensions: [".cjs", ".mjs", ".js", ".jsx", ".json", ".node"],
1401
- preferBuiltins: true
1402
- // runtime === 'node',
1403
- }), commonjs(), json(), esbuild({
1404
- jsx: (_ref7 = config == null ? void 0 : config.jsx) !== null && _ref7 !== void 0 ? _ref7 : "automatic",
1405
- jsxFactory: (_ref8 = config == null ? void 0 : config.jsxFactory) !== null && _ref8 !== void 0 ? _ref8 : "createElement",
1406
- jsxFragment: (_ref9 = config == null ? void 0 : config.jsxFragment) !== null && _ref9 !== void 0 ? _ref9 : "Fragment",
1407
- jsxImportSource: (_ref10 = config == null ? void 0 : config.jsxImportSource) !== null && _ref10 !== void 0 ? _ref10 : "react",
1408
- target,
1409
- tsconfig: ctx.ts.configPath || "tsconfig.json"
1410
- }), getBabelOutputPlugin({
1411
- babelrc: false,
1412
- plugins: (_b = config == null ? void 0 : config.babel) == null ? void 0 : _b.plugins,
1413
- presets: [["@babel/preset-env", {
1414
- targets: pkg.browserslist || DEFAULT_BROWSERSLIST_QUERY,
1415
- modules: false
1416
- }]]
1417
- }), minify && terser({
1418
- compress: {
1419
- // Needed until https://github.com/terser/terser/issues/1320 is fixed
1420
- directives: false
1421
- },
1422
- output: {
1423
- comments: (_node, comment) => {
1424
- const text = comment.value;
1425
- const type = comment.type;
1426
- if (type == "comment2") {
1427
- return /@preserve|@license|@cc_on/i.test(text);
1428
- }
1429
- return false;
1430
- }
1431
- }
1432
- })].filter(Boolean);
1433
- const userPlugins = (_c = config == null ? void 0 : config.rollup) == null ? void 0 : _c.plugins;
1434
- const plugins = Array.isArray(userPlugins) ? defaultPlugins.concat(userPlugins) : resolveConfigProperty((_d = config == null ? void 0 : config.rollup) == null ? void 0 : _d.plugins, defaultPlugins);
1435
- return {
1436
- inputOptions: {
1437
- context: cwd,
1438
- external: (id, importer) => {
1439
- if (exportIds == null ? void 0 : exportIds.includes(id)) {
1440
- return true;
1441
- }
1442
- if (importer && (id.startsWith(".") || id.startsWith("/"))) {
1443
- const idPath = path.resolve(path.dirname(importer), id);
1444
- if (sourcePaths == null ? void 0 : sourcePaths.includes(idPath)) {
1445
- logger.warn("detected self-referencing import \u2013 treating as external: ".concat(path.relative(cwd, idPath)));
1446
- return true;
1447
- }
1448
- }
1449
- const idParts = id.split("/");
1450
- const name = idParts[0].startsWith("@") ? "".concat(idParts[0], "/").concat(idParts[1]) : idParts[0];
1451
- if (name && external.includes(name)) {
1452
- return true;
1453
- }
1454
- return false;
1455
- },
1456
- input: entries.reduce((acc, entry) => {
1457
- return {
1458
- ...acc,
1459
- [entry.name]: entry.source
1460
- };
1461
- }, {}),
1462
- plugins,
1463
- treeshake: {
1464
- propertyReadSideEffects: false
1465
- }
1466
- },
1467
- outputOptions: {
1468
- chunkFileNames: () => {
1469
- const parts = outputExt.split(".");
1470
- if (parts.length === 3) {
1471
- return "_chunks/[name]-[hash].".concat(parts[2]);
1472
- }
1473
- return "_chunks/[name]-[hash]".concat(outputExt);
1474
- },
1475
- compact: minify,
1476
- dir: outDir,
1477
- entryFileNames: () => {
1478
- const parts = outputExt.split(".");
1479
- if (parts.length === 3) {
1480
- return "[name].".concat(parts[2]);
1481
- }
1482
- return "[name]".concat(outputExt);
1483
- },
1484
- esModule: true,
1485
- format,
1486
- interop: "compat",
1487
- minifyInternalExports: minify,
1488
- sourcemap: (_ref11 = config == null ? void 0 : config.sourcemap) !== null && _ref11 !== void 0 ? _ref11 : true,
1489
- hoistTransitiveImports: false
1490
- }
1491
- };
1492
- }
1493
- const rollupTask = {
1494
- name: (ctx, task) => {
1495
- const bundleEntries = task.entries.filter(e => e.path.includes("__$$bundle_"));
1496
- const entries = task.entries.filter(e => !e.path.includes("__$$bundle_"));
1497
- const targetLines = task.target.length ? [" target:", ...task.target.map(t => " - ".concat(chalk.yellow(t)))] : [];
1498
- const bundlesLines = bundleEntries.length ? [" bundles:", ...bundleEntries.map(e => [" - ", "".concat(chalk.yellow(e.source), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(e.output))].join(""))] : [];
1499
- const entriesLines = entries.length ? [" entries:", ...entries.map(e => [" - ", "".concat(chalk.cyan(path.join(ctx.pkg.name, e.path)), ": "), "".concat(chalk.yellow(e.source), " ").concat(chalk.gray("\u2192"), " ").concat(chalk.yellow(e.output))].join(""))] : [];
1500
- return ["Build javascript files...", " format: ".concat(chalk.yellow(task.format)), ...targetLines, ...bundlesLines, ...entriesLines].join("\n");
1501
- },
1502
- exec: (ctx, task) => {
1503
- return new Observable(observer => {
1504
- execPromise(ctx, task).then(result => {
1505
- observer.next(result);
1506
- observer.complete();
1507
- }).catch(err => observer.error(err));
1508
- });
1509
- },
1510
- complete: () => {},
1511
- error: (_ctx, _task, err) => {
1512
- console.error(err);
1513
- }
1514
- };
1515
- async function execPromise(ctx, task) {
1516
- const {
1517
- distPath,
1518
- files,
1519
- logger
1520
- } = ctx;
1521
- const outDir = path.relative(ctx.cwd, distPath);
1522
- const consoleSpy = createConsoleSpy({
1523
- onRestored: messages => {
1524
- for (const msg of messages) {
1525
- const text = String(msg.args[0]);
1526
- if (msg.code === "CIRCULAR_DEPENDENCY") {
1527
- continue;
1528
- }
1529
- if (text.startsWith("Dynamic import can only")) {
1530
- continue;
1531
- }
1532
- if (text.startsWith("Sourcemap is likely to be incorrect")) {
1533
- continue;
1534
- }
1535
- if (msg.type === "log") {
1536
- logger.info(...msg.args);
1537
- }
1538
- if (msg.type === "warn") {
1539
- logger.warn(...msg.args);
1540
- }
1541
- if (msg.type === "error") {
1542
- logger.error(...msg.args);
1543
- }
1544
- }
1545
- }
1546
- });
1547
- try {
1548
- const {
1549
- inputOptions,
1550
- outputOptions
1551
- } = resolveRollupConfig(ctx, task);
1552
- const bundle = await rollup({
1553
- ...inputOptions,
1554
- onwarn(warning) {
1555
- consoleSpy.messages.push({
1556
- type: "warn",
1557
- code: warning.code,
1558
- args: [warning.message]
1559
- });
1560
- }
1561
- });
1562
- const {
1563
- output
1564
- } = await bundle.generate(outputOptions);
1565
- for (const chunkOrAsset of output) {
1566
- if (chunkOrAsset.type === "asset") {
1567
- files.push({
1568
- type: "asset",
1569
- path: path.resolve(outDir, chunkOrAsset.fileName)
1570
- });
1571
- } else {
1572
- files.push({
1573
- type: "chunk",
1574
- path: path.resolve(outDir, chunkOrAsset.fileName)
1575
- });
1576
- }
1577
- }
1578
- await bundle.write(outputOptions);
1579
- await bundle.close();
1580
- consoleSpy.restore();
1581
- } catch (err) {
1582
- consoleSpy.restore();
1583
- throw err;
1584
- }
1585
- }
1586
- const rollupWatchTask = {
1587
- 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 ")),
1588
- exec: (ctx, task) => {
1589
- const {
1590
- inputOptions,
1591
- outputOptions
1592
- } = resolveRollupConfig(ctx, task);
1593
- return new Observable(observer => {
1594
- const watchOptions = {
1595
- ...inputOptions,
1596
- output: outputOptions
1597
- };
1598
- const watcher = watch$1(watchOptions);
1599
- watcher.on("event", event => {
1600
- observer.next(event);
1601
- });
1602
- return () => {
1603
- watcher.close();
1604
- };
1605
- });
1606
- },
1607
- complete: (ctx, task, event) => {
1608
- const {
1609
- logger
1610
- } = ctx;
1611
- if (event.code === "BUNDLE_END") {
1612
- 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 ")));
1613
- logger.log("");
1614
- return;
1615
- }
1616
- if (event.code === "BUNDLE_START") {
1617
- return;
1618
- }
1619
- if (event.code === "END") {
1620
- return;
1621
- }
1622
- if (event.code === "ERROR") {
1623
- logger.error(event.code, event);
1624
- return;
1625
- }
1626
- if (event.code === "START") {
1627
- return;
1628
- }
1629
- },
1630
- error: (ctx, _task, err) => {
1631
- const {
1632
- logger
1633
- } = ctx;
1634
- if (err instanceof Error) {
1635
- logger.log(err);
1636
- }
1637
- }
1638
- };
1639
- const buildTaskHandlers = {
1640
- "build:dts": dtsTask,
1641
- "build:js": rollupTask,
1642
- "node:reexport-cjs": nodeReexportCjsTask
1643
- };
1644
- const watchTaskHandlers = {
1645
- "watch:dts": dtsWatchTask,
1646
- "watch:js": rollupWatchTask
1647
- };
1648
- async function build(options) {
1649
- var _ref12;
1650
- const {
1651
- cwd,
1652
- emitDeclarationOnly,
1653
- strict = false,
1654
- tsconfig: tsconfigOption
1655
- } = options;
1656
- const logger = createLogger();
1657
- const pkg = await loadPkgWithReporting({
1658
- cwd,
1659
- logger
1660
- });
1661
- const config = await loadConfig({
1662
- cwd
1663
- });
1664
- const extMap = getPkgExtMap({
1665
- legacyExports: (_ref12 = config == null ? void 0 : config.legacyExports) !== null && _ref12 !== void 0 ? _ref12 : false
1666
- });
1667
- const tsconfig = tsconfigOption || (config == null ? void 0 : config.tsconfig) || "tsconfig.json";
1668
- const ctx = await resolveBuildContext({
1669
- config,
1670
- cwd,
1671
- emitDeclarationOnly,
1672
- extMap,
1673
- logger,
1674
- pkg,
1675
- strict,
1676
- tsconfig
1677
- });
1678
- const buildTasks = resolveBuildTasks(ctx);
1679
- for (const task of buildTasks) {
1680
- const handler = buildTaskHandlers[task.type];
1681
- const taskName = handler.name(ctx, task);
1682
- const spinner = createSpinner(taskName);
1683
- try {
1684
- const result = await handler.exec(ctx, task).toPromise();
1685
- spinner.complete();
1686
- ctx.logger.log();
1687
- handler.complete(ctx, task, result);
1688
- } catch (err) {
1689
- spinner.error();
1690
- if (err instanceof Error) {
1691
- const RE_CWD = new RegExp("".concat(cwd), "g");
1692
- ctx.logger.error(err.message.replace(RE_CWD, "."));
1693
- ctx.logger.log();
1694
- }
1695
- handler.error(ctx, task, err);
1696
- process.exit(1);
1697
- }
1698
- }
1699
- }
1700
- function getFilesize(file) {
1701
- const stats = statSync(file);
1702
- return prettyBytes(stats.size);
1703
- }
1704
- function getFileInfo(cwd, filePath) {
1705
- const p = path.resolve(cwd, filePath);
1706
- const exists = fileExists(p);
1707
- const size = exists ? getFilesize(p) : void 0;
1708
- return {
1709
- exists,
1710
- size
1711
- };
1712
- }
1713
- function printPackageTree(ctx) {
1714
- const {
1715
- cwd,
1716
- exports,
1717
- logger,
1718
- pkg
1719
- } = ctx;
1720
- if (!exports) return;
1721
- logger.log("".concat(chalk.blue(pkg.name), "@").concat(chalk.green(pkg.version)));
1722
- const tree = {};
1723
- if (pkg.type) {
1724
- tree.type = chalk.yellow(pkg.type);
1725
- }
1726
- if (pkg.bin) {
1727
- tree.bin = Object.fromEntries(Object.entries(pkg.bin).map(_ref13 => {
1728
- let [name, file] = _ref13;
1729
- return [chalk.cyan(name), fileInfo(file)];
1730
- }));
1731
- }
1732
- function fileInfo(file) {
1733
- const info = getFileInfo(cwd, file);
1734
- if (!info.size) {
1735
- return "".concat(chalk.gray(file), " ").concat(chalk.red("does not exist"));
1736
- }
1737
- return "".concat(chalk.yellow(file), " ").concat(chalk.gray(info.size));
1738
- }
1739
- tree.exports = Object.fromEntries(Object.entries(exports).filter(_ref14 => {
1740
- let [, entry] = _ref14;
1741
- return entry._exported;
1742
- }).map(_ref15 => {
1743
- let [exportPath, entry] = _ref15;
1744
- const exp = {
1745
- types: void 0,
1746
- source: fileInfo(entry.source),
1747
- browser: void 0,
1748
- require: void 0,
1749
- node: void 0,
1750
- import: void 0,
1751
- default: fileInfo(entry.default)
1752
- };
1753
- if (entry.types) {
1754
- exp.types = fileInfo(entry.types);
1755
- } else {
1756
- delete exp.types;
1757
- }
1758
- if (entry.browser) {
1759
- exp.browser = {
1760
- source: fileInfo(entry.browser.source)
1761
- };
1762
- if (entry.browser.import) exp.browser.import = fileInfo(entry.browser.import);
1763
- if (entry.browser.require) exp.browser.require = fileInfo(entry.browser.require);
1764
- } else {
1765
- delete exp.browser;
1766
- }
1767
- if (entry.require) {
1768
- exp.require = fileInfo(entry.require);
1769
- } else {
1770
- delete exp.require;
1771
- }
1772
- if (entry.node) {
1773
- exp.node = {};
1774
- if (entry.node.source) exp.node.source = fileInfo(entry.node.source);
1775
- if (entry.node.import) exp.node.import = fileInfo(entry.node.import);
1776
- if (entry.node.require) exp.node.require = fileInfo(entry.node.require);
1777
- } else {
1778
- delete exp.node;
1779
- }
1780
- if (entry.import) {
1781
- exp.import = fileInfo(entry.import);
1782
- } else {
1783
- delete exp.import;
1784
- }
1785
- return [chalk.cyan(path.join(pkg.name, exportPath)), exp];
1786
- }));
1787
- logger.log(treeify.asTree(tree, true, true));
1788
- }
1789
- async function check(options) {
1790
- var _ref16;
1791
- const {
1792
- cwd,
1793
- strict = false,
1794
- tsconfig: tsconfigOption
1795
- } = options;
1796
- const logger = createLogger();
1797
- const pkg = await loadPkgWithReporting({
1798
- cwd,
1799
- logger
1800
- });
1801
- const config = await loadConfig({
1802
- cwd
1803
- });
1804
- const extMap = getPkgExtMap({
1805
- legacyExports: (_ref16 = config == null ? void 0 : config.legacyExports) !== null && _ref16 !== void 0 ? _ref16 : false
1806
- });
1807
- const tsconfig = tsconfigOption || (config == null ? void 0 : config.tsconfig) || "tsconfig.json";
1808
- const ctx = await resolveBuildContext({
1809
- config,
1810
- cwd,
1811
- extMap,
1812
- logger,
1813
- pkg,
1814
- strict,
1815
- tsconfig
1816
- });
1817
- printPackageTree(ctx);
1818
- if (strict) {
1819
- const missingFiles = [];
1820
- for (const [, exp] of Object.entries(ctx.exports || {})) {
1821
- if (exp.source && !fileExists(path.resolve(cwd, exp.source))) {
1822
- missingFiles.push(exp.source);
1823
- }
1824
- if (exp.require && !fileExists(path.resolve(cwd, exp.require))) {
1825
- missingFiles.push(exp.require);
1826
- }
1827
- if (exp.import && !fileExists(path.resolve(cwd, exp.import))) {
1828
- missingFiles.push(exp.import);
1829
- }
1830
- if (exp.types && !fileExists(path.resolve(cwd, exp.types))) {
1831
- missingFiles.push(exp.types);
1832
- }
1833
- }
1834
- if (missingFiles.length) {
1835
- logger.error("missing files");
1836
- process.exit(1);
1837
- }
1838
- const exportPaths = {
1839
- require: [],
1840
- import: []
1841
- };
1842
- for (const exp of Object.values(ctx.exports || {})) {
1843
- if (!exp._exported) continue;
1844
- if (exp.require) exportPaths.require.push(exp.require);
1845
- if (exp.import) exportPaths.import.push(exp.import);
1846
- }
1847
- const external = [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {})];
1848
- const consoleSpy = createConsoleSpy();
1849
- if (exportPaths.import.length) {
1850
- checkExports(exportPaths.import, {
1851
- cwd,
1852
- external,
1853
- format: "esm",
1854
- logger
1855
- });
1856
- }
1857
- if (exportPaths.require.length) {
1858
- checkExports(exportPaths.require, {
1859
- cwd,
1860
- external,
1861
- format: "cjs",
1862
- logger
1863
- });
1864
- }
1865
- consoleSpy.restore();
1866
- }
1867
- }
1868
- async function checkExports(exportPaths, options) {
1869
- const {
1870
- cwd,
1871
- external,
1872
- format,
1873
- logger
1874
- } = options;
1875
- const code = exportPaths.map(id => format ? "import('".concat(id, "');") : "require('".concat(id, "');")).join("\n");
1876
- try {
1877
- const esbuildResult = await esbuild$1.build({
1878
- bundle: true,
1879
- external,
1880
- format,
1881
- logLevel: "silent",
1882
- // otherwise output maps to stdout as we're using stdin
1883
- outfile: "/dev/null",
1884
- platform: "node",
1885
- stdin: {
1886
- contents: code,
1887
- loader: "js",
1888
- resolveDir: cwd
1889
- }
1890
- });
1891
- if (esbuildResult.errors.length > 0) {
1892
- for (const msg of esbuildResult.errors) {
1893
- printEsbuildMessage(logger.warn, msg);
1894
- logger.log();
1895
- }
1896
- process.exit(1);
1897
- }
1898
- const esbuildWarnings = esbuildResult.warnings.filter(msg => {
1899
- !(msg.detail || msg.text).includes("does not affect esbuild's own target setting");
1900
- });
1901
- for (const msg of esbuildWarnings) {
1902
- printEsbuildMessage(logger.warn, msg);
1903
- logger.log();
1904
- }
1905
- } catch (err) {
1906
- const {
1907
- errors
1908
- } = err;
1909
- for (const msg of errors) {
1910
- printEsbuildMessage(logger.error, msg);
1911
- logger.log();
1912
- }
1913
- process.exit(1);
1914
- }
1915
- }
1916
- function printEsbuildMessage(log, msg) {
1917
- if (msg.location) {
1918
- log(["".concat(msg.detail || msg.text, "\n"), "".concat(msg.location.line, " | ").concat(msg.location.lineText, "\n"), "in ./".concat(msg.location.file, ":").concat(msg.location.line, ":").concat(msg.location.column)].join(""));
1919
- } else {
1920
- log(msg.detail || msg.text);
1921
- }
1922
- }
1923
- async function isEmptyDirectory(dirPath) {
1924
- return (await readdir(dirPath)).length === 0;
1925
- }
1926
- const RE_NAME = /^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i;
1927
- const defaultTemplate = async _ref17 => {
1928
- let {
1929
- cwd,
1930
- logger,
1931
- packagePath
1932
- } = _ref17;
1933
- var _a, _b;
1934
- const gitConfig = await parseGitConfig({
1935
- cwd,
1936
- type: "global"
1937
- });
1938
- return {
1939
- options: [defineTemplateOption({
1940
- name: "repo",
1941
- type: "string",
1942
- description: "git url",
1943
- validate: v => {
1944
- if (!v) return true;
1945
- try {
1946
- gitUrlParse(v);
1947
- return true;
1948
- } catch (err) {
1949
- return "invalid git url";
1950
- }
1951
- },
1952
- parse: v => {
1953
- if (!v) return null;
1954
- const result = gitUrlParse(v);
1955
- return {
1956
- source: result.source,
1957
- owner: result.owner,
1958
- name: result.name
1959
- };
1960
- }
1961
- }), defineTemplateOption({
1962
- name: "pkgName",
1963
- type: "string",
1964
- description: "package name",
1965
- initial: options => {
1966
- var _a2;
1967
- return ((_a2 = options.repo) == null ? void 0 : _a2.name) || void 0;
1968
- },
1969
- validate: v => {
1970
- if (!v) return "package name is required";
1971
- const match = RE_NAME.exec(v);
1972
- if (!match) {
1973
- return "invalid package name";
1974
- }
1975
- return true;
1976
- },
1977
- parse: v => {
1978
- if (!v) {
1979
- throw new Error("package name is required");
1980
- }
1981
- const match = RE_NAME.exec(v);
1982
- if (!match) {
1983
- throw new Error("invalid package name");
1984
- }
1985
- const [scope, name] = v.split("/");
1986
- return {
1987
- scope,
1988
- name,
1989
- fullName: v
1990
- };
1991
- }
1992
- }), defineTemplateOption({
1993
- name: "description",
1994
- type: "string",
1995
- description: "package description"
1996
- }), defineTemplateOption({
1997
- name: "authorName",
1998
- type: "string",
1999
- description: "package author name",
2000
- initial: (_a = gitConfig == null ? void 0 : gitConfig.user) == null ? void 0 : _a.name
2001
- }), defineTemplateOption({
2002
- name: "authorEmail",
2003
- type: "string",
2004
- description: "package author email",
2005
- initial: (_b = gitConfig == null ? void 0 : gitConfig.user) == null ? void 0 : _b.email
2006
- }), defineTemplateOption({
2007
- name: "license",
2008
- type: "string",
2009
- description: "package license",
2010
- initial: "MIT",
2011
- validate: v => {
2012
- if (!v) return "license is required";
2013
- return true;
2014
- }
2015
- })],
2016
- features: [{
2017
- name: "eslint",
2018
- optional: true,
2019
- initial: true
2020
- }, {
2021
- name: "typescript",
2022
- optional: true,
2023
- initial: true
2024
- }],
2025
- async getFiles(options, features) {
2026
- var _filter$join, _options$description;
2027
- var _a2;
2028
- const {
2029
- pkgName,
2030
- repo
2031
- } = options;
2032
- const {
2033
- fullName: name
2034
- } = pkgName;
2035
- const author = (_filter$join = [options.authorName, options.authorEmail && "<".concat(options.authorEmail, ">")].filter(Boolean).join(" ")) !== null && _filter$join !== void 0 ? _filter$join : void 0;
2036
- const prettierConfig = {
2037
- bracketSpacing: false,
2038
- printWidth: 100,
2039
- semi: false,
2040
- singleQuote: true,
2041
- tabWidth: 2,
2042
- plugins: ["prettier-plugin-packagejson"],
2043
- overrides: [{
2044
- files: ["*.yml"],
2045
- options: {
2046
- singleQuote: false
2047
- }
2048
- }]
2049
- };
2050
- const pkgJson = {
2051
- name,
2052
- version: "0.0.0",
2053
- description: (_options$description = options.description) !== null && _options$description !== void 0 ? _options$description : void 0,
2054
- keywords: [],
2055
- license: options.license,
2056
- author,
2057
- type: "module",
2058
- exports: {
2059
- ".": {
2060
- types: void 0,
2061
- source: features.typescript ? "./src/index.ts" : "./src/index.js",
2062
- require: "./dist/index.cjs",
2063
- import: "./dist/index.js",
2064
- default: "./dist/index.js"
2065
- },
2066
- "./package.json": "./package.json"
2067
- },
2068
- main: "./dist/index.cjs",
2069
- module: "./dist/index.js",
2070
- source: features.typescript ? "./src/index.ts" : "./src/index.js",
2071
- files: ["dist", "src"],
2072
- scripts: {
2073
- build: "run-s clean pkg:build pkg:check",
2074
- clean: "rimraf dist",
2075
- format: "prettier --write --cache --ignore-unknown .",
2076
- "pkg:build": "pkg build --strict",
2077
- "pkg:check": "pkg check --strict"
2078
- },
2079
- prettier: prettierConfig,
2080
- "lint-staged": {
2081
- "*": ["prettier --write --cache --ignore-unknown"]
2082
- },
2083
- dependencies: {},
2084
- devDependencies: {
2085
- "@sanity/pkg-utils": "*",
2086
- "lint-staged": "*",
2087
- "npm-run-all": "*",
2088
- prettier: "*",
2089
- "prettier-plugin-packagejson": "*",
2090
- rimraf: "*"
2091
- },
2092
- engines: {
2093
- node: ">=18.0.0"
2094
- }
2095
- };
2096
- const files = [];
2097
- files.push({
2098
- name: ".editorconfig",
2099
- contents: outdent(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n root = true\n\n [*]\n charset = utf-8\n indent_style = space\n indent_size = 2\n end_of_line = lf\n insert_final_newline = true\n trim_trailing_whitespace = true\n "])))
2100
- });
2101
- files.push({
2102
- name: ".gitignore",
2103
- contents: outdent(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n *.local\n *.log\n\n .DS_Store\n etc\n dist\n node_modules\n "])))
2104
- });
2105
- files.push({
2106
- name: ".prettierignore",
2107
- contents: outdent(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n /dist\n /pnpm-lock.yaml\n "])))
2108
- });
2109
- if (repo) {
2110
- pkgJson.repository = {
2111
- type: "git",
2112
- url: "git+ssh://git@".concat(repo.source, "/").concat(repo.owner, "/").concat(repo.name, ".git")
2113
- };
2114
- pkgJson.bugs = {
2115
- url: "https://".concat(repo.source, "/").concat(repo.owner, "/").concat(repo.name, "/issues")
2116
- };
2117
- pkgJson.homepage = "https://".concat(repo.source, "/").concat(repo.owner, "/").concat(repo.name, "#readme");
2118
- }
2119
- if (features.typescript) {
2120
- pkgJson.types = "./dist/index.d.ts";
2121
- const mainExport = (_a2 = pkgJson.exports) == null ? void 0 : _a2["."];
2122
- if (isRecord(mainExport)) {
2123
- mainExport.types = "./dist/index.d.ts";
2124
- }
2125
- pkgJson.scripts = {
2126
- ...pkgJson.scripts,
2127
- ["type:check"]: "tsc --build"
2128
- };
2129
- const devDependencies = pkgJson.devDependencies;
2130
- if (isRecord(devDependencies)) {
2131
- devDependencies["typescript"] = "*";
2132
- }
2133
- }
2134
- if (features.eslint) {
2135
- const eslintConfig = {
2136
- root: true,
2137
- env: {
2138
- browser: true,
2139
- es6: true,
2140
- node: true
2141
- },
2142
- extends: ["eslint:recommended", "plugin:prettier/recommended"],
2143
- parserOptions: {
2144
- ecmaVersion: 2020,
2145
- sourceType: "module"
2146
- },
2147
- plugins: ["import", "prettier"],
2148
- rules: {
2149
- "no-console": "error",
2150
- "no-shadow": "error",
2151
- "no-warning-comments": ["warn", {
2152
- location: "start",
2153
- terms: ["todo", "fixme"]
2154
- }]
2155
- }
2156
- };
2157
- files.push({
2158
- name: ".eslintignore",
2159
- contents: outdent(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n /dist\n "])))
2160
- });
2161
- pkgJson.scripts = {
2162
- ...pkgJson.scripts,
2163
- lint: features.typescript ? "eslint . --ext .cjs,.js,.ts,.tsx" : "eslint . --ext .cjs,.js"
2164
- };
2165
- pkgJson.devDependencies = {
2166
- ...pkgJson.devDependencies,
2167
- eslint: "*",
2168
- "eslint-config-prettier": "*",
2169
- "eslint-plugin-import": "*",
2170
- "eslint-plugin-prettier": "*"
2171
- };
2172
- if (features.typescript) {
2173
- pkgJson.devDependencies = {
2174
- ...pkgJson.devDependencies,
2175
- "@typescript-eslint/eslint-plugin": "*",
2176
- "@typescript-eslint/parser": "*"
2177
- };
2178
- const eslintConfigOverride = {
2179
- files: ["**/*.ts", "**/*.tsx"],
2180
- parser: "@typescript-eslint/parser",
2181
- parserOptions: {
2182
- project: ["./tsconfig.json"]
2183
- },
2184
- extends: ["eslint:recommended", "plugin:prettier/recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended"].filter(Boolean),
2185
- plugins: ["import", "@typescript-eslint", "prettier"].filter(Boolean),
2186
- rules: {
2187
- "@typescript-eslint/explicit-module-boundary-types": "error",
2188
- "@typescript-eslint/interface-name-prefix": "off",
2189
- "@typescript-eslint/member-delimiter-style": "off",
2190
- "@typescript-eslint/no-empty-interface": "off"
2191
- }
2192
- };
2193
- eslintConfig.overrides = [eslintConfigOverride];
2194
- }
2195
- files.push({
2196
- name: ".eslintrc.cjs",
2197
- contents: await format(resolve(packagePath, ".eslintrc.cjs"), outdent(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["\n 'use strict'\n\n /** @type import('eslint').Linter.Config */\n module.exports = ", "\n "])), JSON.stringify(eslintConfig, null, 2)), prettierConfig)
2198
- });
2199
- }
2200
- if (features.typescript) {
2201
- files.push({
2202
- name: "tsconfig.settings.json",
2203
- contents: await format(resolve(packagePath, "tsconfig.settings.json"), outdent(_templateObject6 || (_templateObject6 = _taggedTemplateLiteral(["\n {\n \"compilerOptions\": {\n \"module\": \"ES2020\",\n \"target\": \"ES2020\",\n \"declaration\": true,\n \"declarationMap\": true,\n \"sourceMap\": true,\n\n // Strict type-checking\n \"strict\": true,\n \"noImplicitAny\": true,\n \"strictNullChecks\": true,\n \"strictFunctionTypes\": true,\n \"strictPropertyInitialization\": true,\n \"noImplicitThis\": true,\n \"alwaysStrict\": true,\n\n // Additional checks\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"noImplicitReturns\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"skipLibCheck\": true,\n\n // Module resolution\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"esModuleInterop\": true\n }\n }\n "]))), prettierConfig)
2204
- });
2205
- files.push({
2206
- name: "tsconfig.dist.json",
2207
- contents: await format(resolve(packagePath, "tsconfig.dist.json"), outdent(_templateObject7 || (_templateObject7 = _taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./src\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"emitDeclarationOnly\": true,\n \"resolveJsonModule\": true\n }\n }\n "]))), prettierConfig)
2208
- });
2209
- files.push({
2210
- name: "tsconfig.json",
2211
- contents: await format(resolve(packagePath, "tsconfig.json"), outdent(_templateObject8 || (_templateObject8 = _taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./*.cjs\", \"./*.ts\", \"./package.config.ts\", \"./src\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"noEmit\": true,\n \"allowJs\": true,\n \"resolveJsonModule\": true,\n }\n }\n "]))), prettierConfig)
2212
- });
2213
- }
2214
- if (features.typescript) {
2215
- files.push({
2216
- name: "package.config.ts",
2217
- contents: await format(resolve(packagePath, "package.config.ts"), outdent(_templateObject9 || (_templateObject9 = _taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with `_`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n\n // the path to the tsconfig file for distributed builds\n tsconfig: 'tsconfig.dist.json',\n })\n "], ["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with \\`_\\`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n\n // the path to the tsconfig file for distributed builds\n tsconfig: 'tsconfig.dist.json',\n })\n "]))), prettierConfig)
2218
- });
2219
- files.push({
2220
- name: "src/index.ts",
2221
- contents: await format(resolve(packagePath, "src/index.ts"), outdent(_templateObject10 || (_templateObject10 = _taggedTemplateLiteral(["\n /** @public */\n export function main(): void {\n //\n }\n "]))), prettierConfig)
2222
- });
2223
- } else {
2224
- files.push({
2225
- name: "package.config.js",
2226
- contents: await format(resolve(packagePath, "package.config.js"), outdent(_templateObject11 || (_templateObject11 = _taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with `_`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "], ["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with \\`_\\`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "]))), prettierConfig)
2227
- });
2228
- files.push({
2229
- name: "src/index.js",
2230
- contents: await format(resolve(packagePath, "src/index.js"), outdent(_templateObject12 || (_templateObject12 = _taggedTemplateLiteral(["\n /** @public */\n export function main() {\n //\n }\n "]))), prettierConfig)
2231
- });
2232
- }
2233
- try {
2234
- var _pkgJson$dependencies;
2235
- pkgJson.dependencies = await resolveLatestDeps((_pkgJson$dependencies = pkgJson.dependencies) !== null && _pkgJson$dependencies !== void 0 ? _pkgJson$dependencies : {});
2236
- } catch (error) {
2237
- logger.warn(error instanceof Error ? error.message : error);
2238
- }
2239
- try {
2240
- var _pkgJson$devDependenc;
2241
- pkgJson.devDependencies = await resolveLatestDeps((_pkgJson$devDependenc = pkgJson.devDependencies) !== null && _pkgJson$devDependenc !== void 0 ? _pkgJson$devDependenc : {});
2242
- } catch (error) {
2243
- logger.warn(error instanceof Error ? error.message : error);
2244
- }
2245
- files.push({
2246
- name: "package.json",
2247
- contents: await format(resolve(packagePath, "package.json"), JSON.stringify(pkgJson, null, 2), prettierConfig)
2248
- });
2249
- return files;
2250
- }
2251
- };
2252
- };
2253
- function format(filepath, input, prettierOptions) {
2254
- return prettier.format(input, {
2255
- ...prettierOptions,
2256
- filepath
2257
- });
2258
- }
2259
- async function resolveLatestDeps(deps) {
2260
- const depsEntries = Object.entries(deps);
2261
- const latestDeps = {};
2262
- for (const entry of depsEntries) {
2263
- const [name, version] = entry;
2264
- const latestVersion = await getLatestVersion(name, version);
2265
- latestDeps[name] = latestVersion ? "^".concat(latestVersion) : version;
2266
- }
2267
- return latestDeps;
2268
- }
2269
- async function init(options) {
2270
- if (!options.cwd) {
2271
- throw new Error("Missing required option: cwd");
2272
- }
2273
- if (!options.path) {
2274
- throw new Error("Missing required option: path");
2275
- }
2276
- const logger = createLogger();
2277
- const packagePath = resolve(options.cwd, options.path);
2278
- await ensurePackagePath(packagePath);
2279
- await createFromTemplate({
2280
- cwd: options.cwd,
2281
- logger,
2282
- template: defaultTemplate,
2283
- packagePath
2284
- });
2285
- }
2286
- async function ensurePackagePath(packagePath) {
2287
- const exists = fileExists(packagePath);
2288
- if (!exists) {
2289
- await mkdirp(packagePath);
2290
- return;
2291
- }
2292
- const dir = (await lstat(packagePath)).isDirectory();
2293
- if (!dir) {
2294
- throw new Error("the package path is a file, not a directory");
2295
- }
2296
- const empty = await isEmptyDirectory(packagePath);
2297
- if (!empty) {
2298
- throw new Error("the package directory is not empty");
2299
- }
2300
- }
2301
- function resolveWatchTasks(ctx) {
2302
- var _a, _b, _c, _d, _e;
2303
- const {
2304
- config,
2305
- cwd,
2306
- pkg,
2307
- target
2308
- } = ctx;
2309
- const tasks = [];
2310
- const exports = Object.entries(ctx.exports || {}).map(_ref18 => {
2311
- let [_path, exp] = _ref18;
2312
- return {
2313
- _path,
2314
- ...exp
2315
- };
2316
- });
2317
- const dtsTask = {
2318
- type: "watch:dts",
2319
- entries: []
2320
- };
2321
- const rollupTasks = {};
2322
- function addRollupTaskEntry(format, runtime, entry) {
2323
- const buildId = "".concat(format, ":").concat(runtime);
2324
- if (rollupTasks[buildId]) {
2325
- rollupTasks[buildId].entries.push(entry);
2326
- } else {
2327
- rollupTasks[buildId] = {
2328
- type: "watch:js",
2329
- buildId,
2330
- entries: [entry],
2331
- runtime,
2332
- format,
2333
- target: target[runtime]
2334
- };
2335
- }
2336
- }
2337
- for (const exp of exports) {
2338
- const importId = path.join(pkg.name, exp._path);
2339
- if (exp.types) {
2340
- dtsTask.entries.push({
2341
- importId,
2342
- exportPath: exp._path,
2343
- sourcePath: exp.source,
2344
- targetPath: exp.types
2345
- });
2346
- }
2347
- }
2348
- for (const exp of exports) {
2349
- const output = exp.require;
2350
- if (!output) continue;
2351
- addRollupTaskEntry("commonjs", ctx.runtime, {
2352
- path: exp._path,
2353
- source: exp.source,
2354
- output
2355
- });
2356
- }
2357
- for (const exp of exports) {
2358
- const output = (_a = exp.browser) == null ? void 0 : _a.require;
2359
- if (!output) continue;
2360
- addRollupTaskEntry("commonjs", "browser", {
2361
- path: exp._path,
2362
- source: ((_b = exp.browser) == null ? void 0 : _b.source) || exp.source,
2363
- output
2364
- });
2365
- }
2366
- for (const exp of exports) {
2367
- const output = exp.import;
2368
- if (!output) continue;
2369
- addRollupTaskEntry("esm", ctx.runtime, {
2370
- path: exp._path,
2371
- source: exp.source,
2372
- output
2373
- });
2374
- }
2375
- for (const exp of exports) {
2376
- const output = (_c = exp.browser) == null ? void 0 : _c.import;
2377
- if (!output) continue;
2378
- addRollupTaskEntry("esm", "browser", {
2379
- path: exp._path,
2380
- source: ((_d = exp.browser) == null ? void 0 : _d.source) || exp.source,
2381
- output
2382
- });
2383
- }
2384
- if (dtsTask.entries.length) {
2385
- tasks.push(dtsTask);
2386
- }
2387
- tasks.push(...Object.values(rollupTasks));
2388
- if (config == null ? void 0 : config.legacyExports) {
2389
- for (const exp of exports) {
2390
- if (exp._exported && exp._path !== ".") {
2391
- const relativeTargetPath = (((_e = exp.browser) == null ? void 0 : _e.import) || exp.import || "").replace(/\.[^/.]+$/, "");
2392
- if (relativeTargetPath) {
2393
- fs$1.writeFileSync(path.resolve(cwd, "".concat(exp._path, ".js")), ["// AUTO-GENERATED \u2013 DO NOT EDIT", "export * from '".concat(relativeTargetPath, "'"), ""].join("\n"));
2394
- }
2395
- }
2396
- }
2397
- }
2398
- return tasks;
2399
- }
2400
- function globFiles(patterns) {
2401
- return globby(patterns.map(pattern => pattern.split(path.sep).join(path.posix.sep)));
2402
- }
2403
- function watchFiles(patterns) {
2404
- return new Observable(observer => {
2405
- const watcher = chokidar.watch(patterns, {
2406
- ignoreInitial: true
2407
- });
2408
- function handleFileEvent(type, file) {
2409
- observer.next({
2410
- type,
2411
- file
2412
- });
2413
- }
2414
- watcher.on("all", handleFileEvent);
2415
- return () => {
2416
- watcher.off("all", handleFileEvent);
2417
- watcher.close();
2418
- };
2419
- });
2420
- }
2421
- async function watchConfigFiles(options) {
2422
- const {
2423
- cwd,
2424
- logger
2425
- } = options;
2426
- 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")]);
2427
- 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")]);
2428
- return fileEvent$.pipe(scan((files, fileEvent) => {
2429
- if (fileEvent.type === "add") {
2430
- return files.concat(fileEvent.file);
2431
- }
2432
- if (fileEvent.type === "unlink") {
2433
- return files.filter(f => f !== fileEvent.file);
2434
- }
2435
- if (fileEvent.type === "change") {
2436
- logger.log("--------------------------------------------------------------------------------");
2437
- logger.info(path.relative(cwd, fileEvent.file), "changed");
2438
- logger.log("");
2439
- return files.slice(0);
2440
- }
2441
- return files;
2442
- }, initialFiles), startWith(initialFiles), distinctUntilChanged());
2443
- }
2444
- async function watch(options) {
2445
- const {
2446
- cwd,
2447
- strict = false,
2448
- tsconfig: tsconfigOption
2449
- } = options;
2450
- const logger = createLogger();
2451
- const configFiles$ = await watchConfigFiles({
2452
- cwd,
2453
- logger
2454
- });
2455
- const ctx$ = configFiles$.pipe(switchMap(async configFiles => {
2456
- var _ref19;
2457
- const files = configFiles.map(f => path.relative(cwd, f));
2458
- const packageJsonPath = files.find(f => f === "package.json");
2459
- if (!packageJsonPath) {
2460
- throw new Error("missing package.json");
2461
- }
2462
- const pkg = await loadPkgWithReporting({
2463
- cwd,
2464
- logger
2465
- });
2466
- const config = await loadConfig({
2467
- cwd
2468
- });
2469
- const extMap = getPkgExtMap({
2470
- legacyExports: (_ref19 = config == null ? void 0 : config.legacyExports) !== null && _ref19 !== void 0 ? _ref19 : false
2471
- });
2472
- const tsconfig = tsconfigOption || (config == null ? void 0 : config.tsconfig) || "tsconfig.json";
2473
- return resolveBuildContext({
2474
- config,
2475
- cwd,
2476
- extMap,
2477
- logger,
2478
- pkg,
2479
- strict,
2480
- tsconfig
2481
- });
2482
- }));
2483
- ctx$.subscribe(async ctx => {
2484
- const watchTasks = resolveWatchTasks(ctx);
2485
- for (const task of watchTasks) {
2486
- const handler = watchTaskHandlers[task.type];
2487
- const result$ = handler.exec(ctx, task);
2488
- result$.subscribe({
2489
- error: err => {
2490
- ctx.logger.error(err);
2491
- ctx.logger.log();
2492
- process.exit(1);
2493
- },
2494
- next: result => {
2495
- handler.complete(ctx, task, result);
2496
- },
2497
- complete: () => {
2498
- ctx.logger.success(handler.name(ctx, task));
2499
- ctx.logger.log();
2500
- }
2501
- });
2502
- }
2503
- });
2504
- }
2505
- export { DEFAULT_BROWSERSLIST_QUERY, DEFAULT_PKG_EXT_MAP, build, buildTaskHandlers, check, createFromTemplate, createLogger, defineConfig, defineTemplateOption, dtsTask, dtsWatchTask, getExtractMessagesConfig, getPkgExtMap, init, isRecord, loadConfig, loadPkg, loadPkgWithReporting, loadTSConfig, parseExports, resolveBuildTasks, resolveConfigProperty, rollupTask, rollupWatchTask, watch, watchTaskHandlers };
1
+ export { build } from './build.js';
2
+ export { check } from './check.js';
3
+ export { defineConfig } from './core/config/defineConfig.js';
4
+ export { loadConfig } from './core/config/loadConfig.js';
5
+ export { resolveConfigProperty } from './core/config/resolveConfigProperty.js';
6
+ export { DEFAULT_BROWSERSLIST_QUERY } from './core/defaults.js';
7
+ export { isRecord } from './core/isRecord.js';
8
+ export { loadPkg } from './core/pkg/loadPkg.js';
9
+ export { loadPkgWithReporting } from './core/pkg/loadPkgWithReporting.js';
10
+ export { parseExports } from './core/pkg/parseExports.js';
11
+ export { DEFAULT_PKG_EXT_MAP, getPkgExtMap } from './core/pkg/pkgExt.js';
12
+ export { createFromTemplate } from './core/template/createFromTemplate.js';
13
+ export { defineTemplateOption } from './core/template/define.js';
14
+ export { loadTSConfig } from './core/ts/loadTSConfig.js';
15
+ export { init } from './init.js';
16
+ export { createLogger } from './logger.js';
17
+ export { resolveBuildTasks } from './resolveBuildTasks.js';
18
+ export { buildTaskHandlers, watchTaskHandlers } from './tasks/index.js';
19
+ export { watch } from './watch.js';
20
+ export { dtsTask } from './tasks/dts/dtsTask.js';
21
+ export { dtsWatchTask } from './tasks/dts/dtsWatchTask.js';
22
+ export { getExtractMessagesConfig } from './tasks/dts/getExtractMessagesConfig.js';
23
+ export { rollupTask } from './tasks/rollup/rollupTask.js';
24
+ export { rollupWatchTask } from './tasks/rollup/rollupWatchTask.js';
2506
25
  //# sourceMappingURL=index.js.map