@visulima/packem 2.0.0-alpha.43 → 2.0.0-alpha.45

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 (99) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE.md +156 -102
  3. package/dist/builder/typedoc/generate-reference-documentation.d.ts +4 -0
  4. package/dist/builder/typedoc/index.js +3 -160
  5. package/dist/cli/commands/add.d.ts +4 -0
  6. package/dist/cli/commands/build.d.ts +21 -0
  7. package/dist/cli/commands/init.d.ts +3 -0
  8. package/dist/cli/commands/migrate.d.ts +21 -0
  9. package/dist/cli/commands/utils/css-loader-dependencies.d.ts +2 -0
  10. package/dist/cli/index.js +52 -1377
  11. package/dist/config/index.js +1 -4
  12. package/dist/config/preset/auto.d.ts +3 -0
  13. package/dist/config/preset/react.js +1 -43
  14. package/dist/config/preset/solid.js +1 -72
  15. package/dist/config/preset/svelte.d.ts +1 -1
  16. package/dist/config/preset/svelte.js +1 -44
  17. package/dist/config/preset/utils/infer-entries.d.ts +12 -0
  18. package/dist/config/preset/utils/overwrite-with-publish-config.d.ts +4 -0
  19. package/dist/config/preset/vue.js +1 -33
  20. package/dist/config/utils/find-packem-file.d.ts +2 -0
  21. package/dist/config/utils/load-package-json.d.ts +6 -0
  22. package/dist/config/utils/load-packem-config.d.ts +7 -0
  23. package/dist/config/utils/load-preset.d.ts +4 -0
  24. package/dist/config/utils/load-tsconfig.d.ts +5 -0
  25. package/dist/config/utils/prepare-entries.d.ts +4 -0
  26. package/dist/index.js +1 -30
  27. package/dist/jit/create-stub.d.ts +4 -0
  28. package/dist/packem/build.d.ts +21 -0
  29. package/dist/packem/index.d.ts +25 -0
  30. package/dist/packem/utils/brotli-size.d.ts +2 -0
  31. package/dist/packem/utils/group-by-keys.d.ts +3 -0
  32. package/dist/packem/utils/gzip-size.d.ts +2 -0
  33. package/dist/packem_shared/browserslistToEsbuild-C0IWmbNe-C6xPL1oW.js +1 -0
  34. package/dist/packem_shared/create-or-update-key-storage-C0tWtgSr.js +3 -0
  35. package/dist/packem_shared/default-5XUc-qHw.js +1 -0
  36. package/dist/packem_shared/default-B2EOH52z.js +1 -0
  37. package/dist/packem_shared/default-BYM_JvQL.js +1 -0
  38. package/dist/packem_shared/default-B_dUKZ_J.js +1 -0
  39. package/dist/packem_shared/default-DsjSAv7m.js +1 -0
  40. package/dist/packem_shared/esbuildPlugin-pPPsJB9N-YI_X-5wr.js +3 -0
  41. package/dist/packem_shared/index-CUp9WuCG.js +1 -0
  42. package/dist/packem_shared/index-ChtiNkgT.js +174 -0
  43. package/dist/packem_shared/isolatedDeclarationsOxcTransformer-WbfE6cGu-NeZOx2Y7.js +1 -0
  44. package/dist/packem_shared/isolatedDeclarationsSwcTransformer-Ch2AgtWC-B-0lOgFf.js +1 -0
  45. package/dist/packem_shared/isolatedDeclarationsTypescriptTransformer-DkuEkofo-Cwe3ODMG.js +3 -0
  46. package/dist/packem_shared/oxcResolvePlugin-Ccef6pyL-D14z9S9i.js +1 -0
  47. package/dist/packem_shared/oxcTransformPlugin-DfVQouIB-Cpfv95eA.js +4 -0
  48. package/dist/packem_shared/resolveTypescriptMjsCtsPlugin-DcZrZTmM-CauidYR5.js +6 -0
  49. package/dist/packem_shared/swcPlugin-Boip4lWG-CwJ-HVJc.js +1 -0
  50. package/dist/rollup/build-types.d.ts +5 -0
  51. package/dist/rollup/build.d.ts +5 -0
  52. package/dist/rollup/get-rollup-options.d.ts +5 -0
  53. package/dist/rollup/plugins/css/loaders/less.js +1 -1
  54. package/dist/rollup/plugins/css/loaders/lightningcss.js +1 -1
  55. package/dist/rollup/plugins/css/loaders/postcss.js +1 -1
  56. package/dist/rollup/plugins/css/loaders/sass.js +1 -1
  57. package/dist/rollup/plugins/css/loaders/sourcemap.js +1 -1
  58. package/dist/rollup/plugins/css/loaders/stylus.js +1 -1
  59. package/dist/rollup/plugins/css/loaders/tailwindcss.js +1 -1
  60. package/dist/rollup/plugins/css/minifiers/cssnano.js +1 -1
  61. package/dist/rollup/plugins/css/minifiers/lightningcss.js +1 -1
  62. package/dist/rollup/plugins/esbuild/index.js +1 -1
  63. package/dist/rollup/plugins/oxc/isolated-declarations-oxc-transformer.js +1 -1
  64. package/dist/rollup/plugins/oxc/oxc-transformer.js +1 -1
  65. package/dist/rollup/plugins/sucrase/index.js +1 -1
  66. package/dist/rollup/plugins/swc/isolated-declarations-swc-transformer.js +1 -1
  67. package/dist/rollup/plugins/swc/swc-plugin.js +1 -1
  68. package/dist/rollup/plugins/typescript/isolated-declarations-typescript-transformer.js +1 -1
  69. package/dist/rollup/utils/resolve-aliases.d.ts +4 -0
  70. package/dist/rollup/watch.d.ts +5 -0
  71. package/dist/utils/clean-distribution-directories.d.ts +4 -0
  72. package/dist/utils/create-or-update-key-storage.d.ts +3 -0
  73. package/dist/utils/extract-export-filenames.d.ts +16 -0
  74. package/dist/utils/find-alternatives.d.ts +2 -0
  75. package/dist/utils/get-package-side-effect.d.ts +3 -0
  76. package/dist/utils/infer-export-type.d.ts +3 -0
  77. package/dist/utils/kill-process.d.ts +14 -0
  78. package/dist/utils/log-build-errors.d.ts +4 -0
  79. package/dist/utils/remove-old-cache-folders.d.ts +3 -0
  80. package/dist/utils/warn-legacy-cjs.d.ts +8 -0
  81. package/dist/validator/attw.d.ts +7 -0
  82. package/dist/validator/package-json/index.d.ts +4 -0
  83. package/dist/validator/package-json/validate-dependencies.d.ts +4 -0
  84. package/dist/validator/package-json/validate-engines.d.ts +4 -0
  85. package/dist/validator/package-json/validate-package-entries.d.ts +4 -0
  86. package/dist/validator/package-json/validate-package-fields.d.ts +4 -0
  87. package/dist/validator/validate-alias-entries.d.ts +3 -0
  88. package/dist/validator/validate-bundle-size.d.ts +4 -0
  89. package/package.json +10 -120
  90. package/dist/packem_shared/create-or-update-key-storage-Dd7b8-t1.js +0 -36
  91. package/dist/packem_shared/default-79SPobLI.js +0 -12
  92. package/dist/packem_shared/default-DWBYeUSC.js +0 -210
  93. package/dist/packem_shared/default-DaU6CQEi.js +0 -28
  94. package/dist/packem_shared/default-DavaZMwC.js +0 -32
  95. package/dist/packem_shared/default-DeYZ934H.js +0 -32
  96. package/dist/packem_shared/default-tUOOZ8w7.js +0 -42
  97. package/dist/packem_shared/default-wScAfTaq.js +0 -27
  98. package/dist/packem_shared/index-CTIRxV2x.js +0 -63
  99. package/dist/packem_shared/index-DzTDn4ad.js +0 -9521
package/dist/cli/index.js CHANGED
@@ -1,1391 +1,66 @@
1
1
  #!/usr/bin/env node
2
- import { createCerebro } from '@visulima/cerebro';
3
- import createPailLogger from '@visulima/cerebro/logger/pail';
4
- import { SimpleReporter } from '@visulima/pail/reporter/simple';
5
- import process, { cwd, exit } from 'node:process';
6
- import { installPackage } from '@antfu/install-pkg';
7
- import { spinner, confirm, cancel, select, multiselect, intro, log, outro } from '@clack/prompts';
8
- import { isAccessible, readFile, writeFile, isAccessibleSync, writeJsonSync, writeFileSync } from '@visulima/fs';
9
- import { parsePackageJson } from '@visulima/package/package-json';
10
- import { join, resolve } from '@visulima/path';
11
- import MagicString from 'magic-string';
12
- import { exec } from 'tinyexec';
13
- import { P as PRODUCTION_ENV, b as DEVELOPMENT_ENV } from '../packem_shared/index-CTIRxV2x.js';
14
- import { defu } from 'defu';
15
- import { createJiti } from 'jiti';
16
- import { p as packem, a as autoPreset } from '../packem_shared/index-DzTDn4ad.js';
17
- import { createReactPreset } from '../config/preset/react.js';
18
- import { createSolidPreset } from '../config/preset/solid.js';
19
- import { createSveltePreset } from '../config/preset/svelte.js';
20
- import { createVuePreset } from '../config/preset/vue.js';
21
- import { existsSync } from 'node:fs';
22
- import { readFile as readFile$1, writeFile as writeFile$1 } from 'node:fs/promises';
23
- import { createInterface } from 'node:readline/promises';
24
-
25
- import __cjs_mod__ from "node:module"; // -- packem CommonJS require shim --
2
+ var X=Object.defineProperty;var h=(t,s)=>X(t,"name",{value:s,configurable:!0});import{createCerebro as _}from"@visulima/cerebro";import Y from"@visulima/cerebro/logger/pail";import{SimpleReporter as H}from"@visulima/pail/reporter/simple";import j,{cwd as L,exit as Q}from"node:process";import{installPackage as D}from"@antfu/install-pkg";import{confirm as w,select as v,multiselect as q,spinner as E,cancel as F,intro as Z,log as N,outro as ee}from"@clack/prompts";import{isAccessible as se,readFile as te,writeFile as ae,isAccessibleSync as O,writeJsonSync as ie,writeFileSync as oe}from"@visulima/fs";import{parsePackageJson as G}from"@visulima/package/package-json";import{join as S,resolve as B}from"@visulima/path";import re from"magic-string";import{exec as ne}from"tinyexec";import{t as V,E as ce}from"../packem_shared/index-CUp9WuCG.js";import{defu as le}from"defu";import{createJiti as de}from"jiti";import{j as pe,w as ue}from"../packem_shared/index-ChtiNkgT.js";import{existsSync as U}from"node:fs";import{readFile as me,writeFile as fe}from"node:fs/promises";import{createInterface as ge}from"node:readline/promises";import __cjs_mod__ from "node:module"; // -- packem CommonJS require shim --
26
3
  const require = __cjs_mod__.createRequire(import.meta.url);
27
- var name = "@visulima/packem";
28
- var version = "2.0.0-alpha.40";
29
- const pkg = {
30
- version: version};
31
-
32
- const findPackemFile = async (rootDirectory, configPath = "") => {
33
- let packemConfigFilePath = configPath;
34
- if (!packemConfigFilePath) {
35
- const packemConfigFiles = ["packem.config.js", "packem.config.mjs", "packem.config.cjs", "packem.config.ts", "packem.config.cts", "packem.config.mts"];
36
- for (const file of packemConfigFiles) {
37
- if (await isAccessible(join(rootDirectory, file))) {
38
- packemConfigFilePath = `./${file}`;
39
- break;
40
- }
41
- }
42
- }
43
- if (!/\.(?:js|mjs|cjs|ts|cts|mts)$/.test(packemConfigFilePath)) {
44
- throw new Error("Invalid packem config file extension. Only .js, .mjs, .cjs, .ts, .cts and .mts extensions are allowed.");
45
- }
46
- return packemConfigFilePath;
47
- };
48
-
49
- const cssLoaderDependencies = {
50
- less: ["less"],
51
- lightningcss: ["lightningcss"],
52
- "node-sass": ["node-sass"],
53
- postcss: [
54
- "postcss",
55
- "postcss-load-config",
56
- "postcss-modules-extract-imports",
57
- "postcss-modules-local-by-default",
58
- "postcss-modules-scope",
59
- "postcss-modules-values",
60
- "postcss-value-parser",
61
- "@csstools/css-parser-algorithms",
62
- "@csstools/css-tokenizer",
63
- "@csstools/postcss-slow-plugins",
64
- "icss-utils",
65
- "@visulima/css-style-inject"
66
- ],
67
- sass: ["sass"],
68
- "sass-embedded": ["sass-embedded"],
69
- stylus: ["stylus"],
70
- tailwindcss: ["@tailwindcss/node", "@tailwindcss/oxide", "tailwindcss"]
71
- };
72
-
73
- const typedocPackages = ["typedoc", "typedoc-plugin-markdown", "typedoc-plugin-rename-defaults"];
74
- const reactDevDependencies = ["@babel/core", "@babel/preset-react"];
75
- const reactDependencies = ["react", "react-dom"];
76
- const solidDevDependencies = ["@babel/core", "babel-preset-solid"];
77
- const solidDependencies = ["solid-js"];
78
- const vueDevDependencies = ["unplugin-vue"];
79
- const vueDependencies = ["vue"];
80
- const svelteDevDependencies = ["rollup-plugin-svelte"];
81
- const svelteDependencies = ["svelte"];
82
- const checkPresetExists = (config, presetName, importName) => config.includes(`preset: '${presetName}'`) || config.includes(`preset: "${presetName}"`) || config.includes(`preset: '${presetName}',`) || config.includes(`preset: "${presetName}",`) || config.includes(importName) || config.includes(`@visulima/packem/config/preset/${presetName}`);
83
- const insertPreset = (context, presetName) => {
84
- const { logger, magic, packemConfig } = context;
85
- const defineConfigMatch = packemConfig.match(/defineConfig\s*\(\s*\{/);
86
- if (defineConfigMatch && defineConfigMatch.index !== void 0) {
87
- const insertIndex = defineConfigMatch.index + defineConfigMatch[0].length;
88
- if (packemConfig.includes("preset:")) {
89
- const presetMatch = packemConfig.match(/preset:\s*['"]([^'"]+)['"]/);
90
- if (presetMatch) {
91
- magic.replace(presetMatch[0], `preset: '${presetName}'`);
92
- } else {
93
- logger.warn(`A preset already exists in the config. Please manually set it to '${presetName}'.`);
94
- throw new Error("Preset exists but is not a string");
95
- }
96
- } else {
97
- magic.appendLeft(insertIndex, `
98
- preset: '${presetName}',`);
99
- }
100
- } else if (packemConfig.includes("transformer:")) {
101
- magic.replace("transformer:", `preset: '${presetName}',
102
- transformer:`);
103
- } else {
104
- const configStart = packemConfig.indexOf("{");
105
- if (configStart !== -1) {
106
- magic.appendLeft(configStart + 1, `
107
- preset: '${presetName}',`);
108
- }
109
- }
110
- };
111
- const checkGitDirty = async (rootDirectory) => {
112
- try {
113
- const result = await exec("git", ["status", "--porcelain"], {
114
- nodeOptions: {
115
- cwd: rootDirectory,
116
- stdio: ["pipe", "pipe", "pipe"]
117
- }
118
- });
119
- return result.stdout?.trim().length > 0;
120
- } catch {
121
- return false;
122
- }
123
- };
124
- const checkTypeScriptInstalled = async (rootDirectory) => {
125
- const packageJsonPath = join(rootDirectory, "package.json");
126
- const packageJson = await parsePackageJson(packageJsonPath, {
127
- resolveCatalogs: true
128
- });
129
- return Boolean(packageJson.devDependencies?.typescript ?? packageJson.dependencies?.typescript);
130
- };
131
- const getReactTypeDependencies = async (rootDirectory) => {
132
- const hasTypescript = await checkTypeScriptInstalled(rootDirectory);
133
- const packages = [...reactDependencies];
134
- const devPackages = [...reactDevDependencies];
135
- if (hasTypescript) {
136
- devPackages.push("@types/react", "@types/react-dom");
137
- } else {
138
- const useTypescript = await confirm({
139
- initialValue: false,
140
- message: "Do you want to use TypeScript?"
141
- });
142
- if (useTypescript) {
143
- devPackages.push("typescript", "@types/react", "@types/react-dom");
144
- }
145
- }
146
- return { devPackages, packages };
147
- };
148
- const installPackages = async (context, devPackages, packages) => {
149
- const { rootDirectory, spinner: s } = context;
150
- s.start("Installing packages");
151
- await installPackage(packages, {
152
- cwd: rootDirectory,
153
- dev: false,
154
- silent: true
155
- });
156
- await installPackage(devPackages, {
157
- cwd: rootDirectory,
158
- dev: true,
159
- silent: true
160
- });
161
- s.stop("Installed packages");
162
- };
163
- const addTypedoc = async (context) => {
164
- const { logger, magic, packemConfig, packemConfigFormat, rootDirectory, spinner: s, transformerReplaceKey, transformerSearchKey } = context;
165
- if (packemConfig.includes("typedoc: typedocBuilder") || packemConfig.includes("@visulima/packem/builder/typedoc")) {
166
- logger.warn("Typedoc has already been added to the packem config.");
167
- return;
168
- }
169
- if (packemConfigFormat === "cjs") {
170
- magic.prepend(`const typedocBuilder = require("@visulima/packem/builder/typedoc");
171
- `);
172
- } else {
173
- magic.prepend(`import typedocBuilder from "@visulima/packem/builder/typedoc";
174
- `);
175
- }
176
- if (packemConfig.includes("builder: {")) {
177
- magic.replace("builder: {", `builder: {
4
+ var ye="@visulima/packem",J="2.0.0-alpha.44";const R={version:J};var we=Object.defineProperty,be=h((t,s)=>we(t,"name",{value:s,configurable:!0}),"t");const z=be(async(t,s="")=>{let e=s;if(!e){const a=["packem.config.js","packem.config.mjs","packem.config.cjs","packem.config.ts","packem.config.cts","packem.config.mts"];for(const o of a)if(await se(S(t,o))){e=`./${o}`;break}}if(!/\.(?:js|mjs|cjs|ts|cts|mts)$/.test(e))throw new Error("Invalid packem config file extension. Only .js, .mjs, .cjs, .ts, .cts and .mts extensions are allowed.");return e},"findPackemFile"),K={less:["less"],lightningcss:["lightningcss"],"node-sass":["node-sass"],postcss:["postcss","postcss-load-config","postcss-modules-extract-imports","postcss-modules-local-by-default","postcss-modules-scope","postcss-modules-values","postcss-value-parser","@csstools/css-parser-algorithms","@csstools/css-tokenizer","@csstools/postcss-slow-plugins","icss-utils","@visulima/css-style-inject"],sass:["sass"],"sass-embedded":["sass-embedded"],stylus:["stylus"],tailwindcss:["@tailwindcss/node","@tailwindcss/oxide","tailwindcss"]};var ve=Object.defineProperty,y=h((t,s)=>ve(t,"name",{value:s,configurable:!0}),"r$2");const he=["typedoc","typedoc-plugin-markdown","typedoc-plugin-rename-defaults"],ke=["@babel/core","@babel/preset-react"],Se=["react","react-dom"],$e=["@babel/core","babel-preset-solid"],je=["solid-js"],Ce=["unplugin-vue"],xe=["vue"],De=["rollup-plugin-svelte"],Pe=["svelte"],M=y((t,s,e)=>t.includes(`preset: '${s}'`)||t.includes(`preset: "${s}"`)||t.includes(`preset: '${s}',`)||t.includes(`preset: "${s}",`)||t.includes(e)||t.includes(`@visulima/packem/config/preset/${s}`),"checkPresetExists"),T=y((t,s)=>{const{logger:e,magic:a,packemConfig:o}=t,r=o.match(/defineConfig\s*\(\s*\{/);if(r&&r.index!==void 0){const n=r.index+r[0].length;if(o.includes("preset:")){const i=o.match(/preset:\s*['"]([^'"]+)['"]/);if(i)a.replace(i[0],`preset: '${s}'`);else throw e.warn(`A preset already exists in the config. Please manually set it to '${s}'.`),new Error("Preset exists but is not a string")}else a.appendLeft(n,`
5
+ preset: '${s}',`)}else if(o.includes("transformer:"))a.replace("transformer:",`preset: '${s}',
6
+ transformer:`);else{const n=o.indexOf("{");n!==-1&&a.appendLeft(n+1,`
7
+ preset: '${s}',`)}},"insertPreset"),Me=y(async t=>{try{return((await ne("git",["status","--porcelain"],{nodeOptions:{cwd:t,stdio:["pipe","pipe","pipe"]}})).stdout?.trim().length??0)>0}catch{return!1}},"checkGitDirty"),Te=y(async t=>{const s=S(t,"package.json"),e=await G(s,{resolveCatalogs:!0});return!!(e.devDependencies?.typescript??e.dependencies?.typescript)},"checkTypeScriptInstalled"),Ie=y(async t=>{const s=await Te(t),e=[...Se],a=[...ke];return s?a.push("@types/react","@types/react-dom"):await w({initialValue:!1,message:"Do you want to use TypeScript?"})&&a.push("typescript","@types/react","@types/react-dom"),{devPackages:a,packages:e}},"getReactTypeDependencies"),I=y(async(t,s,e)=>{const{rootDirectory:a,spinner:o}=t;o.start("Installing packages"),await D(e,{cwd:a,dev:!1,silent:!0}),await D(s,{cwd:a,dev:!0,silent:!0}),o.stop("Installed packages")},"installPackages"),Oe=y(async t=>{const{logger:s,magic:e,packemConfig:a,packemConfigFormat:o,rootDirectory:r,spinner:n,transformerReplaceKey:i,transformerSearchKey:l}=t;if(a.includes("typedoc: typedocBuilder")||a.includes("@visulima/packem/builder/typedoc")){s.warn("Typedoc has already been added to the packem config.");return}o==="cjs"?e.prepend(`const typedocBuilder = require("@visulima/packem/builder/typedoc");
8
+ `):e.prepend(`import typedocBuilder from "@visulima/packem/builder/typedoc";
9
+ `),a.includes("builder: {")?e.replace("builder: {",`builder: {
178
10
  typedoc: typedocBuilder,
179
- `);
180
- } else {
181
- magic.replace(transformerSearchKey, `${transformerReplaceKey}
11
+ `):e.replace(l,`${i}
182
12
  builder: {
183
13
  typedoc: typedocBuilder,
184
- },`);
185
- }
186
- logger.info("Adding typedoc dependencies...");
187
- s.start("Installing packages");
188
- await installPackage(typedocPackages, {
189
- cwd: rootDirectory,
190
- dev: true,
191
- silent: true
192
- });
193
- s.stop("Installed packages");
194
- logger.success("\nTypedoc added!");
195
- };
196
- const addReact = async (context) => {
197
- const { logger, packemConfig } = context;
198
- if (checkPresetExists(packemConfig, "react", "createReactPreset")) {
199
- logger.warn("React preset has already been added to the packem config.");
200
- return;
201
- }
202
- insertPreset(context, "react");
203
- const { devPackages, packages } = await getReactTypeDependencies(context.rootDirectory);
204
- logger.info("Adding React dependencies...");
205
- await installPackages(context, devPackages, packages);
206
- logger.success("\nReact preset added!");
207
- };
208
- const addSolid = async (context) => {
209
- const { logger, packemConfig } = context;
210
- if (checkPresetExists(packemConfig, "solid", "createSolidPreset")) {
211
- logger.warn("Solid preset has already been added to the packem config.");
212
- return;
213
- }
214
- insertPreset(context, "solid");
215
- logger.info("Adding Solid dependencies...");
216
- await installPackages(context, solidDevDependencies, solidDependencies);
217
- logger.success("\nSolid preset added!");
218
- };
219
- const addVue = async (context) => {
220
- const { logger, packemConfig } = context;
221
- if (checkPresetExists(packemConfig, "vue", "createVuePreset")) {
222
- logger.warn("Vue preset has already been added to the packem config.");
223
- return;
224
- }
225
- insertPreset(context, "vue");
226
- logger.info("Adding Vue dependencies...");
227
- await installPackages(context, vueDevDependencies, vueDependencies);
228
- logger.success("\nVue preset added!");
229
- };
230
- const addSvelte = async (context) => {
231
- const { logger, packemConfig } = context;
232
- if (checkPresetExists(packemConfig, "svelte", "createSveltePreset")) {
233
- logger.warn("Svelte preset has already been added to the packem config.");
234
- return;
235
- }
236
- insertPreset(context, "svelte");
237
- logger.info("Adding Svelte dependencies...");
238
- await installPackages(context, svelteDevDependencies, svelteDependencies);
239
- logger.success("\nSvelte preset added!");
240
- };
241
- const addCss = async (context) => {
242
- const { logger, magic, packemConfig, packemConfigFormat, transformerReplaceKey, transformerSearchKey } = context;
243
- if (packemConfig.includes("css: {") || packemConfig.includes("@visulima/packem/css")) {
244
- logger.warn("Css loaders have already been added to the packem config.");
245
- return;
246
- }
247
- const cssLoaders = [];
248
- const mainCssLoader = await select({
249
- message: "Pick a css loader",
250
- options: [
251
- { label: "PostCSS", value: "postcss" },
252
- {
253
- hint: "experimental",
254
- label: "Lightning CSS",
255
- value: "lightningcss"
256
- },
257
- {
258
- hint: "Tailwind Css Oxide",
259
- label: "Tailwind CSS",
260
- value: "tailwindcss"
261
- }
262
- ]
263
- });
264
- cssLoaders.push(mainCssLoader);
265
- if (mainCssLoader !== "tailwindcss") {
266
- let extraCssLoaders = await multiselect({
267
- message: "Pick extra loaders",
268
- options: [
269
- { label: "Sass", value: "sass" },
270
- { label: "Stylus", value: "stylus" },
271
- { label: "Less", value: "less" }
272
- ],
273
- required: false
274
- });
275
- if (extraCssLoaders.includes("sass")) {
276
- const sassLoader = await select({
277
- message: "Pick a sass loader",
278
- options: [
279
- {
280
- hint: "recommended",
281
- label: "Sass embedded",
282
- value: "sass-embedded"
283
- },
284
- { label: "Sass", value: "sass" },
285
- {
286
- hint: "legacy",
287
- label: "Node Sass",
288
- value: "node-sass"
289
- }
290
- ]
291
- });
292
- if (sassLoader !== "sass") {
293
- extraCssLoaders = extraCssLoaders.filter((loader) => loader !== "sass");
294
- extraCssLoaders.push(sassLoader);
295
- }
296
- }
297
- cssLoaders.push(...extraCssLoaders);
298
- }
299
- const packagesToInstall = [];
300
- for (const loader of cssLoaders) {
301
- packagesToInstall.push(...cssLoaderDependencies[loader]);
302
- }
303
- if (mainCssLoader !== "tailwindcss") {
304
- cssLoaders.push("sourceMap");
305
- }
306
- for (const loader of cssLoaders) {
307
- const normalizedLoader = loader === "sass-embedded" || loader === "node-sass" ? "sass" : loader;
308
- if (packemConfigFormat === "cjs") {
309
- magic.prepend(`const ${normalizedLoader}Loader = require("@visulima/packem/css/loader/${normalizedLoader.toLowerCase()}");
310
- `);
311
- } else {
312
- magic.prepend(`import ${normalizedLoader}Loader from "@visulima/packem/css/loader/${normalizedLoader.toLowerCase()}";
313
- `);
314
- }
315
- }
316
- const useCssMinifier = await confirm({
317
- initialValue: false,
318
- message: "Do you want to minify your css?"
319
- });
320
- let cssMinifier;
321
- if (useCssMinifier) {
322
- cssMinifier = await select({
323
- message: "Pick a css minifier",
324
- options: [
325
- { label: "CSSNano", value: "cssnano" },
326
- { label: "Lightning CSS", value: "lightningcss" }
327
- ]
328
- });
329
- if (!cssLoaders.includes("lightningcss")) {
330
- packagesToInstall.push(cssMinifier);
331
- }
332
- if (packemConfigFormat === "cjs") {
333
- magic.prepend(`const ${cssMinifier}Minifier = require("@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}");
334
- `);
335
- } else {
336
- magic.prepend(`import ${cssMinifier}Minifier from "@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}";
337
- `);
338
- }
339
- }
340
- const stringCssLoaders = cssLoaders.map((loader) => {
341
- if (loader === "sass-embedded" || loader === "node-sass") {
342
- return "sass";
343
- }
344
- return `${loader}Loader`;
345
- }).join(", ");
346
- if (packemConfig.includes("rollup: {")) {
347
- magic.replace(
348
- "rollup: {",
349
- `rollup: {
350
- css: {${cssMinifier ? `
351
- minifier: ${cssMinifier}Minifier,` : ""}
352
- loaders: [${stringCssLoaders}],
14
+ },`),s.info("Adding typedoc dependencies..."),n.start("Installing packages"),await D(he,{cwd:r,dev:!0,silent:!0}),n.stop("Installed packages"),s.success(`
15
+ Typedoc added!`)},"addTypedoc"),Ee=y(async t=>{const{logger:s,packemConfig:e}=t;if(M(e,"react","createReactPreset")){s.warn("React preset has already been added to the packem config.");return}T(t,"react");const{devPackages:a,packages:o}=await Ie(t.rootDirectory);s.info("Adding React dependencies..."),await I(t,a,o),s.success(`
16
+ React preset added!`)},"addReact"),Le=y(async t=>{const{logger:s,packemConfig:e}=t;if(M(e,"solid","createSolidPreset")){s.warn("Solid preset has already been added to the packem config.");return}T(t,"solid"),s.info("Adding Solid dependencies..."),await I(t,$e,je),s.success(`
17
+ Solid preset added!`)},"addSolid"),Be=y(async t=>{const{logger:s,packemConfig:e}=t;if(M(e,"vue","createVuePreset")){s.warn("Vue preset has already been added to the packem config.");return}T(t,"vue"),s.info("Adding Vue dependencies..."),await I(t,Ce,xe),s.success(`
18
+ Vue preset added!`)},"addVue"),Ne=y(async t=>{const{logger:s,packemConfig:e}=t;if(M(e,"svelte","createSveltePreset")){s.warn("Svelte preset has already been added to the packem config.");return}T(t,"svelte"),s.info("Adding Svelte dependencies..."),await I(t,De,Pe),s.success(`
19
+ Svelte preset added!`)},"addSvelte"),Ve=y(async t=>{const{logger:s,magic:e,packemConfig:a,packemConfigFormat:o,transformerReplaceKey:r,transformerSearchKey:n}=t;if(a.includes("css: {")||a.includes("@visulima/packem/css")){s.warn("Css loaders have already been added to the packem config.");return}const i=[],l=await v({message:"Pick a css loader",options:[{label:"PostCSS",value:"postcss"},{hint:"experimental",label:"Lightning CSS",value:"lightningcss"},{hint:"Tailwind Css Oxide",label:"Tailwind CSS",value:"tailwindcss"}]});if(i.push(l),l!=="tailwindcss"){let f=await q({message:"Pick extra loaders",options:[{label:"Sass",value:"sass"},{label:"Stylus",value:"stylus"},{label:"Less",value:"less"}],required:!1});if(f.includes("sass")){const b=await v({message:"Pick a sass loader",options:[{hint:"recommended",label:"Sass embedded",value:"sass-embedded"},{label:"Sass",value:"sass"},{hint:"legacy",label:"Node Sass",value:"node-sass"}]});b!=="sass"&&(f=f.filter(d=>d!=="sass"),f.push(b))}i.push(...f)}const p=[];for(const f of i)p.push(...K[f]);l!=="tailwindcss"&&i.push("sourceMap");for(const f of i){const b=f==="sass-embedded"||f==="node-sass"?"sass":f;o==="cjs"?e.prepend(`const ${b}Loader = require("@visulima/packem/css/loader/${b.toLowerCase()}");
20
+ `):e.prepend(`import ${b}Loader from "@visulima/packem/css/loader/${b.toLowerCase()}";
21
+ `)}const m=await w({initialValue:!1,message:"Do you want to minify your css?"});let g;m&&(g=await v({message:"Pick a css minifier",options:[{label:"CSSNano",value:"cssnano"},{label:"Lightning CSS",value:"lightningcss"}]}),i.includes("lightningcss")||p.push(g),o==="cjs"?e.prepend(`const ${g}Minifier = require("@visulima/packem/css/minifier/${g.toLowerCase()}");
22
+ `):e.prepend(`import ${g}Minifier from "@visulima/packem/css/minifier/${g.toLowerCase()}";
23
+ `));const c=i.map(f=>f==="sass-embedded"||f==="node-sass"?"sass":`${f}Loader`).join(", ");a.includes("rollup: {")?e.replace("rollup: {",`rollup: {
24
+ css: {${g?`
25
+ minifier: ${g}Minifier,`:""}
26
+ loaders: [${c}],
353
27
  },
354
- `
355
- );
356
- } else {
357
- magic.replace(
358
- transformerSearchKey,
359
- `${transformerReplaceKey}
28
+ `):e.replace(n,`${r}
360
29
  rollup: {
361
- css: {${cssMinifier ? `
362
- minifier: ${cssMinifier}Minifier,` : ""}
363
- loaders: [${stringCssLoaders}],
30
+ css: {${g?`
31
+ minifier: ${g}Minifier,`:""}
32
+ loaders: [${c}],
364
33
  },
365
- },`
366
- );
367
- }
368
- context.spinner.start("Installing packages");
369
- await installPackage(packagesToInstall, {
370
- cwd: context.rootDirectory,
371
- dev: true,
372
- silent: true
373
- });
374
- context.spinner.stop("Installed packages");
375
- logger.success("\nCSS loaders added!");
376
- };
377
- const createAddCommand = (cli) => {
378
- cli.addCommand({
379
- argument: {
380
- description: "Add a packem feature to your project",
381
- name: "feature",
382
- required: true
383
- },
384
- description: "Add a optional packem feature to your project",
385
- execute: async ({ argument, logger, options }) => {
386
- const s = spinner();
387
- const rootDirectory = resolve(cwd(), options.dir ?? ".");
388
- let packemConfigFilePath;
389
- try {
390
- packemConfigFilePath = await findPackemFile(rootDirectory, options.config);
391
- } catch {
392
- logger.error("Could not find a packem config file, please run `packem init` first.");
393
- return;
394
- }
395
- const isGitDirty = await checkGitDirty(rootDirectory);
396
- if (isGitDirty) {
397
- const proceed = await confirm({
398
- initialValue: false,
399
- message: "Git repository has uncommitted changes. Do you want to proceed?"
400
- });
401
- if (!proceed) {
402
- cancel("Operation cancelled.");
403
- return;
404
- }
405
- }
406
- const packemConfig = await readFile(packemConfigFilePath, {
407
- buffer: false
408
- });
409
- const packemConfigFormat = packemConfig.includes("import") ? "esm" : "cjs";
410
- const magic = new MagicString(packemConfig);
411
- const transformerReplaceKey = " transformer,";
412
- const transformerSearchKey = packemConfig.includes(" transformer,") ? " transformer," : " transformer";
413
- const context = {
414
- logger,
415
- magic,
416
- packemConfig,
417
- packemConfigFormat,
418
- rootDirectory,
419
- spinner: s,
420
- transformerReplaceKey,
421
- transformerSearchKey
422
- };
423
- if (argument.includes("typedoc")) {
424
- await addTypedoc(context);
425
- }
426
- if (argument.includes("react")) {
427
- await addReact(context);
428
- }
429
- if (argument.includes("solid")) {
430
- await addSolid(context);
431
- }
432
- if (argument.includes("vue")) {
433
- await addVue(context);
434
- }
435
- if (argument.includes("svelte")) {
436
- await addSvelte(context);
437
- }
438
- if (argument.includes("css")) {
439
- await addCss(context);
440
- }
441
- await writeFile(packemConfigFilePath, magic.toString(), {
442
- overwrite: true
443
- });
444
- },
445
- name: "add",
446
- options: [
447
- {
448
- defaultValue: ".",
449
- description: "The directory to build",
450
- name: "dir",
451
- type: String
452
- },
453
- {
454
- description: "Use a custom config file",
455
- name: "config",
456
- type: String
457
- }
458
- ]
459
- });
460
- };
461
-
462
- const loadPackemConfig = async (jiti, rootDirectory, environment, mode, configPath) => {
463
- const packemConfigFilePath = await findPackemFile(rootDirectory, configPath);
464
- let buildConfig = await jiti.import(packemConfigFilePath, {
465
- default: true,
466
- try: true
467
- }) || {};
468
- if (typeof buildConfig === "function") {
469
- buildConfig = await buildConfig(environment, mode);
470
- }
471
- return {
472
- config: buildConfig,
473
- path: packemConfigFilePath
474
- };
475
- };
476
-
477
- const loadPreset = async (preset, jiti) => {
478
- switch (preset) {
479
- case "none": {
480
- return {};
481
- }
482
- case "react": {
483
- preset = createReactPreset();
484
- break;
485
- }
486
- case "solid": {
487
- preset = createSolidPreset();
488
- break;
489
- }
490
- case "svelte": {
491
- preset = createSveltePreset();
492
- break;
493
- }
494
- case "vue": {
495
- preset = createVuePreset();
496
- break;
497
- }
498
- default: {
499
- if (typeof preset === "string") {
500
- preset = await jiti.import(preset) || {};
501
- }
502
- }
503
- }
504
- if (typeof preset === "function") {
505
- preset = preset();
506
- }
507
- return preset;
508
- };
509
-
510
- const createBuildCommand = (cli) => {
511
- cli.addCommand({
512
- description: "Demonstrate options required",
513
- // eslint-disable-next-line sonarjs/cognitive-complexity
514
- execute: async ({ logger, options }) => {
515
- let mode = "build";
516
- if (options.watch) {
517
- mode = "watch";
518
- } else if (options.jit) {
519
- mode = "jit";
520
- }
521
- const environments = {};
522
- let nodeEnvironment;
523
- if (options.env) {
524
- for (const environment of options.env) {
525
- if (environment.key === "NODE_ENV") {
526
- nodeEnvironment = environment.value;
527
- } else {
528
- environments[`process.env.${environment.key}`] = JSON.stringify(environment.value);
529
- }
530
- }
531
- }
532
- if (nodeEnvironment === void 0) {
533
- if (options.production) {
534
- nodeEnvironment = PRODUCTION_ENV;
535
- } else if (options.development) {
536
- nodeEnvironment = DEVELOPMENT_ENV;
537
- }
538
- }
539
- const externals = [];
540
- if (options.external) {
541
- for (const extension of options.external) {
542
- externals.push(extension.split(","));
543
- }
544
- }
545
- const rootPath = resolve(cwd(), options.dir ?? ".");
546
- const jiti = createJiti(rootPath, { debug: options.debug });
547
- const { config: buildConfig, path: buildConfigPath } = await loadPackemConfig(
548
- jiti,
549
- rootPath,
550
- nodeEnvironment,
551
- mode,
552
- options.config ?? void 0
553
- );
554
- logger.debug("Using packem config found at", buildConfigPath);
555
- const preset = await loadPreset(buildConfig.preset ?? "none", jiti);
556
- if (options.minify && options.sourcemap === void 0) {
557
- options.sourcemap = true;
558
- }
559
- try {
560
- await packem(
561
- rootPath,
562
- mode,
563
- nodeEnvironment,
564
- logger,
565
- options.debug,
566
- defu(buildConfig, autoPreset, preset, {
567
- analyze: options.analyze,
568
- cjsInterop: options.cjsInterop,
569
- clean: options.clean,
570
- dtsOnly: options.dtsOnly,
571
- externals,
572
- killSignal: options.killSignal,
573
- minify: options.minify === void 0 ? nodeEnvironment === PRODUCTION_ENV : options.minify,
574
- onSuccess: options.onSuccess,
575
- rollup: {
576
- esbuild: {
577
- target: options.target
578
- },
579
- license: {
580
- path: options.license
581
- },
582
- metafile: options.metafile,
583
- replace: {
584
- values: environments
585
- },
586
- resolveExternals: options.noExternal ? {
587
- builtins: false,
588
- deps: false,
589
- devDeps: false,
590
- optDeps: false,
591
- peerDeps: false
592
- } : {}
593
- },
594
- runtime: options.runtime,
595
- sourcemap: options.metafile || options.analyze || options.sourcemap,
596
- unbundle: options.unbundle,
597
- // validation will take the default values
598
- validation: options.validation === false ? false : {},
599
- ...options.typedoc ? {
600
- typedoc: {
601
- format: "html"
602
- }
603
- } : {}
604
- }),
605
- options.tsconfig ?? void 0
606
- );
607
- } catch (error) {
608
- logger.error(error);
609
- exit(1);
610
- }
611
- },
612
- name: "build",
613
- options: [
614
- {
615
- defaultValue: ".",
616
- description: "The directory to build",
617
- name: "dir",
618
- type: String
619
- },
620
- {
621
- alias: "t",
622
- description: "Environments to support. `target` in tsconfig.json is automatically added. Defaults to the current Node.js version.",
623
- name: "target"
624
- },
625
- {
626
- description: "Use a custom config file",
627
- name: "config",
628
- type: String
629
- },
630
- {
631
- description: "Path to the tsconfig.json file",
632
- name: "tsconfig",
633
- type: String
634
- },
635
- {
636
- description: "Minify the output",
637
- name: "minify",
638
- type: Boolean
639
- },
640
- {
641
- description: "Generate sourcemaps (experimental)",
642
- name: "sourcemap",
643
- type: Boolean
644
- },
645
- {
646
- conflicts: "jit",
647
- description: "Watch for changes",
648
- name: "watch",
649
- type: Boolean
650
- },
651
- {
652
- conflicts: "watch",
653
- description: "Stub the package for JIT compilation",
654
- name: "jit",
655
- type: Boolean
656
- },
657
- {
658
- description: "Compile-time environment variables (eg. --env.NODE_ENV=production)",
659
- multiple: true,
660
- name: "env",
661
- type: (input) => {
662
- const [key, value] = input.split("=");
663
- return {
664
- key,
665
- value
666
- };
667
- }
668
- },
669
- {
670
- defaultValue: false,
671
- description: "Generate meta file (experimental)",
672
- name: "metafile",
673
- type: Boolean
674
- },
675
- {
676
- description: "Path to the license file",
677
- name: "license",
678
- type: String
679
- },
680
- {
681
- conflicts: "watch",
682
- description: "Visualize and analyze the bundle",
683
- name: "analyze",
684
- type: Boolean
685
- },
686
- {
687
- description: "CJS interop mode, can export default and named export, (experimental).",
688
- name: "cjsInterop",
689
- type: Boolean
690
- },
691
- {
692
- conflicts: "development",
693
- description: "Run code in production environment",
694
- name: "production",
695
- type: Boolean
696
- },
697
- {
698
- conflicts: "production",
699
- description: "Run code in development environment",
700
- name: "development",
701
- type: Boolean
702
- },
703
- {
704
- description: "Do not clean the dist directory before building",
705
- name: "no-clean",
706
- type: Boolean
707
- },
708
- {
709
- description: "Only generate .d.ts files",
710
- name: "dts-only",
711
- type: Boolean
712
- },
713
- {
714
- description: "Disable the output validation",
715
- name: "no-validation",
716
- type: Boolean
717
- },
718
- {
719
- description: "Disable the cache",
720
- name: "no-cache",
721
- type: Boolean
722
- },
723
- {
724
- description: "Generate type documentation",
725
- name: "typedoc",
726
- type: Boolean
727
- },
728
- {
729
- description: "Execute command after successful build, specially useful for watch mode",
730
- name: "onSuccess",
731
- type: String
732
- },
733
- {
734
- description: 'Signal to kill child process, "SIGTERM" or "SIGKILL"',
735
- name: "killSignal",
736
- type: (input) => {
737
- if (input === "SIGTERM" || input === "SIGKILL") {
738
- return input;
739
- }
740
- throw new Error("Invalid kill signal. Use 'SIGTERM' or 'SIGKILL'.");
741
- }
742
- },
743
- {
744
- description: "Specify an external dependency, separate by comma (eg. --external lodash,react,react-dom)",
745
- multiple: true,
746
- name: "external",
747
- typeLabel: "string[]"
748
- },
749
- {
750
- description: "do not bundle external dependencies",
751
- name: "no-external",
752
- type: Boolean
753
- },
754
- {
755
- // defaultValue: "browser",
756
- description: "Specify the build runtime (nodejs, browser).",
757
- name: "runtime",
758
- type: (input) => {
759
- if (input === "node" || input === "browser") {
760
- return input;
761
- }
762
- throw new Error("Invalid runtime. Use 'node' or 'browser'.");
763
- }
764
- },
765
- {
766
- description: "Enable unbundle mode to preserve source file structure instead of bundling into a single file",
767
- name: "unbundle",
768
- type: Boolean
769
- }
770
- ]
771
- });
772
- };
773
-
774
- const createInitCommand = (cli) => {
775
- cli.addCommand({
776
- description: "Initialize packem configuration",
777
- // eslint-disable-next-line sonarjs/cognitive-complexity
778
- execute: async ({ logger, options }) => {
779
- intro("Welcome to packem setup");
780
- if (isAccessibleSync(join(options.dir, "packem.config.ts"))) {
781
- logger.info("Packem project already initialized, you can use `packem build` to build your project");
782
- return;
783
- }
784
- const rootDirectory = resolve(cwd(), options.dir ?? ".");
785
- const packageJsonPath = join(rootDirectory, "package.json");
786
- if (!isAccessibleSync(packageJsonPath)) {
787
- throw new Error("No package.json found in the directory");
788
- }
789
- const packageJson = await parsePackageJson(packageJsonPath, {
790
- resolveCatalogs: true
791
- });
792
- const packages = [];
793
- if (packageJson.dependencies) {
794
- packages.push(...Object.keys(packageJson.dependencies));
795
- }
796
- if (packageJson.devDependencies) {
797
- packages.push(...Object.keys(packageJson.devDependencies));
798
- }
799
- const hasTypescript = Boolean(packageJson.devDependencies?.typescript ?? packageJson.dependencies?.typescript);
800
- const packagesToInstall = [];
801
- if (options.typescript === void 0 && !hasTypescript) {
802
- options.typescript = await confirm({
803
- message: "Do you want to install TypeScript?"
804
- });
805
- if (options.typescript) {
806
- packagesToInstall.push("typescript@latest");
807
- }
808
- } else {
809
- log.message(`TypeScript version ${packageJson.devDependencies?.typescript ?? packageJson.dependencies?.typescript} is already installed`);
810
- }
811
- if (!isAccessibleSync(join(rootDirectory, "tsconfig.json"))) {
812
- const shouldGenerate = await confirm({
813
- message: "Do you want to use generate a tsconfig.json?"
814
- });
815
- const runInDom = await confirm({
816
- message: "Do you want to run your code in the DOM?"
817
- });
818
- if (shouldGenerate) {
819
- const s2 = spinner();
820
- s2.start("Generating tsconfig.json");
821
- writeJsonSync(join(rootDirectory, "tsconfig.json"), {
822
- compilerOptions: {
823
- esModuleInterop: true,
824
- skipLibCheck: true,
825
- target: "es2022",
826
- allowJs: true,
827
- resolveJsonModule: true,
828
- moduleDetection: "force",
829
- isolatedModules: true,
830
- verbatimModuleSyntax: true,
831
- strict: true,
832
- noUncheckedIndexedAccess: true,
833
- noImplicitOverride: true,
834
- module: "NodeNext",
835
- outDir: "dist",
836
- sourceMap: true,
837
- declaration: true,
838
- lib: runInDom ? ["es2022", "dom", "dom.iterable"] : ["es2022"]
839
- }
840
- });
841
- s2.stop("");
842
- }
843
- }
844
- if (options.runtime === void 0) {
845
- options.runtime = await select({
846
- message: "Pick a build runtime",
847
- options: [
848
- { label: "Node", value: "node" },
849
- { label: "Browser", value: "browser" }
850
- ]
851
- });
852
- }
853
- if (packages.includes("esbuild")) {
854
- options.transformer = "esbuild";
855
- } else if (packages.includes("@swc/core")) {
856
- options.transformer = "swc";
857
- } else if (packages.includes("sucrase")) {
858
- options.transformer = "sucrase";
859
- }
860
- if (options.transformer === void 0) {
861
- options.transformer = await select({
862
- message: "Pick a transformer",
863
- options: [
864
- { label: "esbuild", value: "esbuild" },
865
- { label: "swc", value: "swc" },
866
- { label: "Sucrase", value: "sucrase" },
867
- { label: "OXC", value: "oxc" }
868
- ]
869
- });
870
- if (options.transformer && options.transformer !== "oxc" && !packages.includes(options.transformer)) {
871
- const shouldInstall = await confirm({
872
- message: `Do you want to install ${options.transformer}?`
873
- });
874
- if (shouldInstall) {
875
- packagesToInstall.push(options.transformer === "swc" ? "@swc/core" : options.transformer);
876
- }
877
- }
878
- } else {
879
- log.message(`Transformer ${options.transformer} is already installed.`);
880
- }
881
- if (options.isolatedDeclarationTransformer === void 0) {
882
- options.isolatedDeclarationTransformer = await confirm({
883
- message: "Do you want to use an isolated declaration types?",
884
- initialValue: false
885
- });
886
- }
887
- if (options.isolatedDeclarationTransformer === void 0) {
888
- options.isolatedDeclarationTransformer = await select({
889
- message: "Pick a isolated declaration transformer",
890
- options: [
891
- { label: "Typescript", value: "typescript" },
892
- { label: "swc", value: "swc" },
893
- { label: "OXC", value: "oxc" },
894
- { label: "None", value: void 0 }
895
- ]
896
- });
897
- if (options.isolatedDeclarationTransformer !== void 0) {
898
- let packageName;
899
- switch (options.isolatedDeclarationTransformer) {
900
- case "oxc": {
901
- packageName = "oxc-transform";
902
- break;
903
- }
904
- case "swc": {
905
- packageName = "@swc/core";
906
- break;
907
- }
908
- case "typescript": {
909
- packageName = "typescript";
910
- break;
911
- }
912
- default: {
913
- cancel("Invalid isolated declaration transformer");
914
- }
915
- }
916
- if (packageName !== void 0 && !packages.includes(packageName)) {
917
- const shouldInstall = await confirm({
918
- message: `Do you want to install ${packageName}?`
919
- });
920
- if (shouldInstall) {
921
- packagesToInstall.push(packageName);
922
- }
923
- }
924
- }
925
- }
926
- if (options.css === void 0) {
927
- options.css = await confirm({
928
- message: "Do you want to use css in your project?",
929
- initialValue: false
930
- });
931
- }
932
- const cssLoaders = [];
933
- if (options.css) {
934
- const mainCssLoader = await select({
935
- message: "Pick a css loader",
936
- options: [
937
- { label: "PostCSS", value: "postcss" },
938
- {
939
- hint: "experimental",
940
- label: "Lightning CSS",
941
- value: "lightningcss"
942
- }
943
- ]
944
- });
945
- cssLoaders.push(mainCssLoader);
946
- let extraCssLoaders = await multiselect({
947
- message: "Pick your loaders",
948
- options: [
949
- { label: "Sass", value: "sass" },
950
- { label: "Stylus", value: "stylus" },
951
- { label: "Less", value: "less" }
952
- ],
953
- required: false
954
- });
955
- if (extraCssLoaders.includes("sass")) {
956
- const sassLoader = await select({
957
- message: "Pick a sass loader",
958
- options: [
959
- {
960
- label: "Sass embedded",
961
- value: "sass-embedded",
962
- hint: "recommended"
963
- },
964
- { label: "Sass", value: "sass" },
965
- {
966
- label: "Node Sass",
967
- value: "node-sass",
968
- hint: "legacy"
969
- }
970
- ]
971
- });
972
- if (sassLoader !== "sass") {
973
- extraCssLoaders = extraCssLoaders.filter((loader) => loader !== "sass");
974
- extraCssLoaders.push(sassLoader);
975
- }
976
- }
977
- cssLoaders.push(...extraCssLoaders);
978
- const shouldInstall = await confirm({
979
- message: `Do you want to install "${cssLoaders.join('", "')}"?`
980
- });
981
- if (shouldInstall) {
982
- for (const loader of cssLoaders) {
983
- packagesToInstall.push(...cssLoaderDependencies[loader]);
984
- }
985
- }
986
- cssLoaders.push("sourceMap");
987
- }
988
- if (options.cssMinifier === void 0) {
989
- options.cssMinifier = await confirm({
990
- message: "Do you want to minify your css?",
991
- initialValue: false
992
- });
993
- }
994
- let cssMinifier;
995
- if (options.cssMinifier) {
996
- cssMinifier = await select({
997
- message: "Pick a css minifier",
998
- options: [
999
- { label: "CSSNano", value: "cssnano" },
1000
- { label: "Lightning CSS", value: "lightningcss" }
1001
- ]
1002
- });
1003
- if (!cssLoaders.includes("lightningcss")) {
1004
- const shouldInstall = await confirm({
1005
- message: `Do you want to install "${cssMinifier}"?`
1006
- });
1007
- if (shouldInstall) {
1008
- packagesToInstall.push(cssMinifier);
1009
- }
1010
- }
1011
- }
1012
- let template = "";
1013
- let packemConfig = "";
1014
- if (options.isolatedDeclarationTransformer) {
1015
- packemConfig += ",\n isolatedDeclarationTransformer";
1016
- }
1017
- if (options.css || options.cssMinifier) {
1018
- packemConfig += ",\n rollup: {\n css: {";
1019
- }
1020
- if (options.css) {
1021
- const stringCssLoaders = cssLoaders.map((loader) => {
1022
- if (loader === "sass-embedded" || loader === "node-sass") {
1023
- loader = "sass";
1024
- }
1025
- return `${loader}Loader`;
1026
- }).join(", ");
1027
- packemConfig += `
1028
- loaders: [${stringCssLoaders}],`;
1029
- }
1030
- if (options.cssMinifier && cssMinifier) {
1031
- packemConfig += `
1032
- minifier: ${cssMinifier}Minifier,`;
1033
- }
1034
- if (options.css || options.cssMinifier) {
1035
- packemConfig += "\n }\n }";
1036
- }
1037
- if (hasTypescript || packageJson.type === "module") {
1038
- let imports = "";
1039
- if (options.isolatedDeclarationTransformer) {
1040
- imports += `import isolatedDeclarationTransformer from "@visulima/packem/dts/isolated/transformer/${options.isolatedDeclarationTransformer}";
1041
- `;
1042
- }
1043
- if (options.css) {
1044
- for (let loader of cssLoaders) {
1045
- if (loader === "sass-embedded" || loader === "node-sass") {
1046
- loader = "sass";
1047
- }
1048
- imports += `import ${loader}Loader from "@visulima/packem/css/loader/${loader.toLowerCase()}";
1049
- `;
1050
- }
1051
- }
1052
- if (options.cssMinifier && cssMinifier) {
1053
- imports += `import ${cssMinifier}Minifier from "@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}";
1054
- `;
1055
- }
1056
- template = `import { defineConfig } from "@visulima/packem/config";
1057
- import transformer from "@visulima/packem/transformer/${options.transformer}";
1058
- ${imports}
34
+ },`),t.spinner.start("Installing packages"),await D(p,{cwd:t.rootDirectory,dev:!0,silent:!0}),t.spinner.stop("Installed packages"),s.success(`
35
+ CSS loaders added!`)},"addCss"),Re=y(t=>{t.addCommand({argument:{description:"Add a packem feature to your project",name:"feature",required:!0},description:"Add a optional packem feature to your project",execute:y(async({argument:s,logger:e,options:a})=>{const o=E(),r=B(L(),a.dir??".");let n;try{n=await z(r,a.config)}catch{e.error("Could not find a packem config file, please run `packem init` first.");return}if(await Me(r)&&!await w({initialValue:!1,message:"Git repository has uncommitted changes. Do you want to proceed?"})){F("Operation cancelled.");return}const i=await te(n,{buffer:!1}),l=i.includes("import")?"esm":"cjs",p=new re(i),m=" transformer,",g=i.includes(" transformer,")?" transformer,":" transformer",c={logger:e,magic:p,packemConfig:i,packemConfigFilePath:n,packemConfigFormat:l,rootDirectory:r,spinner:o,transformerReplaceKey:m,transformerSearchKey:g};s.includes("typedoc")&&await Oe(c),s.includes("react")&&await Ee(c),s.includes("solid")&&await Le(c),s.includes("vue")&&await Be(c),s.includes("svelte")&&await Ne(c),s.includes("css")&&await Ve(c),await ae(n,p.toString(),{overwrite:!0})},"execute"),name:"add",options:[{defaultValue:".",description:"The directory to build",name:"dir",type:String},{description:"Use a custom config file",name:"config",type:String}]})},"createAddCommand");var Ae=Object.defineProperty,qe=h((t,s)=>Ae(t,"name",{value:s,configurable:!0}),"e$2");const Fe=qe(async(t,s,e,a,o)=>{const r=await z(s,o);let n=await t.import(r,{default:!0,try:!0})||{};return typeof n=="function"&&(n=await n(e,a)),{config:n,path:r}},"loadPackemConfig");var Ge=Object.defineProperty,Ue=h((t,s)=>Ge(t,"name",{value:s,configurable:!0}),"e$1");const Je=Ue(async(t,s)=>{switch(t){case"none":return{};case"react":{const{createReactPreset:e}=await import("../config/preset/react.js");t=e();break}case"solid":{const{createSolidPreset:e}=await import("../config/preset/solid.js");t=e();break}case"svelte":{const{createSveltePreset:e}=await import("../config/preset/svelte.js");t=e();break}case"vue":{const{createVuePreset:e}=await import("../config/preset/vue.js");t=e();break}default:typeof t=="string"&&(t=await s.import(t)||{})}return typeof t=="function"&&(t=t()),t},"loadPreset");var ze=Object.defineProperty,C=h((t,s)=>ze(t,"name",{value:s,configurable:!0}),"r");const Ke=C(t=>{t.addCommand({description:"Demonstrate options required",execute:C(async({logger:s,options:e})=>{let a="build";e.watch?a="watch":e.jit&&(a="jit");const o={};let r;if(e.env)for(const c of e.env)c.key==="NODE_ENV"?r=c.value:o[`process.env.${c.key}`]=JSON.stringify(c.value);r===void 0&&(e.production?r=V:e.development&&(r=ce));const n=[];if(e.external)for(const c of e.external)n.push(c.split(","));const i=B(L(),e.dir??"."),l=de(i,{debug:e.debug}),{config:p,path:m}=await Fe(l,i,r,a,e.config??void 0);s.debug("Using packem config found at",m);const g=await Je(p.preset??"none",l);e.minify&&e.sourcemap===void 0&&(e.sourcemap=!0);try{await pe(i,a,r,s,e.debug,le(p,ue,g,{analyze:e.analyze,cjsInterop:e.cjsInterop,clean:e.clean,dtsOnly:e.dtsOnly,externals:n,killSignal:e.killSignal,minify:e.minify===void 0?r===V:e.minify,onSuccess:e.onSuccess,rollup:{esbuild:{target:e.target},license:{path:e.license},metafile:e.metafile,replace:{values:o},resolveExternals:e.noExternal?{builtins:!1,deps:!1,devDeps:!1,optDeps:!1,peerDeps:!1}:{}},runtime:e.runtime,sourcemap:e.metafile||e.analyze||e.sourcemap,unbundle:e.unbundle,validation:e.validation===!1?!1:{},...e.typedoc?{typedoc:{format:"html"}}:{}}),e.tsconfig??void 0)}catch(c){s.error(c),Q(1)}},"execute"),name:"build",options:[{defaultValue:".",description:"The directory to build",name:"dir",type:String},{alias:"t",description:"Environments to support. `target` in tsconfig.json is automatically added. Defaults to the current Node.js version.",name:"target"},{description:"Use a custom config file",name:"config",type:String},{description:"Path to the tsconfig.json file",name:"tsconfig",type:String},{description:"Minify the output",name:"minify",type:Boolean},{description:"Generate sourcemaps (experimental)",name:"sourcemap",type:Boolean},{conflicts:"jit",description:"Watch for changes",name:"watch",type:Boolean},{conflicts:"watch",description:"Stub the package for JIT compilation",name:"jit",type:Boolean},{description:"Compile-time environment variables (eg. --env.NODE_ENV=production)",multiple:!0,name:"env",type:C(s=>{const[e,a]=s.split("=");return{key:e,value:a}},"type")},{defaultValue:!1,description:"Generate meta file (experimental)",name:"metafile",type:Boolean},{description:"Path to the license file",name:"license",type:String},{conflicts:"watch",description:"Visualize and analyze the bundle",name:"analyze",type:Boolean},{description:"CJS interop mode, can export default and named export, (experimental).",name:"cjsInterop",type:Boolean},{conflicts:"development",description:"Run code in production environment",name:"production",type:Boolean},{conflicts:"production",description:"Run code in development environment",name:"development",type:Boolean},{description:"Do not clean the dist directory before building",name:"no-clean",type:Boolean},{description:"Only generate .d.ts files",name:"dts-only",type:Boolean},{description:"Disable the output validation",name:"no-validation",type:Boolean},{description:"Disable the cache",name:"no-cache",type:Boolean},{description:"Generate type documentation",name:"typedoc",type:Boolean},{description:"Execute command after successful build, specially useful for watch mode",name:"onSuccess",type:String},{description:'Signal to kill child process, "SIGTERM" or "SIGKILL"',name:"killSignal",type:C(s=>{if(s==="SIGTERM"||s==="SIGKILL")return s;throw new Error("Invalid kill signal. Use 'SIGTERM' or 'SIGKILL'.")},"type")},{description:"Specify an external dependency, separate by comma (eg. --external lodash,react,react-dom)",multiple:!0,name:"external",typeLabel:"string[]"},{description:"do not bundle external dependencies",name:"no-external",type:Boolean},{description:"Specify the build runtime (nodejs, browser).",name:"runtime",type:C(s=>{if(s==="node"||s==="browser")return s;throw new Error("Invalid runtime. Use 'node' or 'browser'.")},"type")},{description:"Enable unbundle mode to preserve source file structure instead of bundling into a single file",name:"unbundle",type:Boolean}]})},"createBuildCommand");var We=Object.defineProperty,x=h((t,s)=>We(t,"name",{value:s,configurable:!0}),"f");const Xe=x(t=>{t.addCommand({description:"Initialize packem configuration",execute:x(async({logger:s,options:e})=>{if(Z("Welcome to packem setup"),O(S(e.dir,"packem.config.mjs"))){s.info("Packem project already initialized, you can use `packem build` to build your project");return}const a=B(L(),e.dir??"."),o=S(a,"package.json");if(!O(o))throw new Error("No package.json found in the directory");const r=await G(o,{resolveCatalogs:!0}),n=[];r.dependencies&&n.push(...Object.keys(r.dependencies)),r.devDependencies&&n.push(...Object.keys(r.devDependencies));const i=!!(r.devDependencies?.typescript??r.dependencies?.typescript),l=[];if(e.typescript===void 0&&!i?(e.typescript=await w({message:"Do you want to install TypeScript?"}),e.typescript&&l.push("typescript@latest")):N.message(`TypeScript version ${r.devDependencies?.typescript??r.dependencies?.typescript} is already installed`),!O(S(a,"tsconfig.json"))){const d=await w({message:"Do you want to use generate a tsconfig.json?"}),u=await w({message:"Do you want to run your code in the DOM?"});if(d){const k=E();k.start("Generating tsconfig.json"),ie(S(a,"tsconfig.json"),{compilerOptions:{esModuleInterop:!0,skipLibCheck:!0,target:"es2022",allowJs:!0,resolveJsonModule:!0,moduleDetection:"force",isolatedModules:!0,verbatimModuleSyntax:!0,strict:!0,noUncheckedIndexedAccess:!0,noImplicitOverride:!0,module:"NodeNext",outDir:"dist",sourceMap:!0,declaration:!0,lib:u?["es2022","dom","dom.iterable"]:["es2022"]}}),k.stop("")}}if(e.runtime===void 0&&(e.runtime=await v({message:"Pick a build runtime",options:[{label:"Node",value:"node"},{label:"Browser",value:"browser"}]})),n.includes("esbuild")?e.transformer="esbuild":n.includes("@swc/core")?e.transformer="swc":n.includes("sucrase")&&(e.transformer="sucrase"),e.transformer===void 0?(e.transformer=await v({message:"Pick a transformer",options:[{label:"esbuild",value:"esbuild"},{label:"swc",value:"swc"},{label:"Sucrase",value:"sucrase"},{label:"OXC",value:"oxc"}]}),e.transformer&&e.transformer!=="oxc"&&!n.includes(e.transformer)&&await w({message:`Do you want to install ${e.transformer}?`})&&l.push(e.transformer==="swc"?"@swc/core":e.transformer)):N.message(`Transformer ${e.transformer} is already installed.`),e.isolatedDeclarationTransformer===void 0&&(e.isolatedDeclarationTransformer=await w({message:"Do you want to use an isolated declaration types?",initialValue:!1})),e.isolatedDeclarationTransformer===void 0&&(e.isolatedDeclarationTransformer=await v({message:"Pick a isolated declaration transformer",options:[{label:"Typescript",value:"typescript"},{label:"swc",value:"swc"},{label:"OXC",value:"oxc"},{label:"None",value:void 0}]}),e.isolatedDeclarationTransformer!==void 0)){let d;switch(e.isolatedDeclarationTransformer){case"oxc":{d="oxc-transform";break}case"swc":{d="@swc/core";break}case"typescript":{d="typescript";break}default:F("Invalid isolated declaration transformer")}d!==void 0&&!n.includes(d)&&await w({message:`Do you want to install ${d}?`})&&l.push(d)}e.css===void 0&&(e.css=await w({message:"Do you want to use css in your project?",initialValue:!1}));const p=[];if(e.css){const d=await v({message:"Pick a css loader",options:[{label:"PostCSS",value:"postcss"},{hint:"experimental",label:"Lightning CSS",value:"lightningcss"}]});p.push(d);let u=await q({message:"Pick your loaders",options:[{label:"Sass",value:"sass"},{label:"Stylus",value:"stylus"},{label:"Less",value:"less"}],required:!1});if(u.includes("sass")){const k=await v({message:"Pick a sass loader",options:[{label:"Sass embedded",value:"sass-embedded",hint:"recommended"},{label:"Sass",value:"sass"},{label:"Node Sass",value:"node-sass",hint:"legacy"}]});k!=="sass"&&(u=u.filter(W=>W!=="sass"),u.push(k))}if(p.push(...u),await w({message:`Do you want to install "${p.join('", "')}"?`}))for(const k of p)l.push(...K[k]);p.push("sourceMap")}e.cssMinifier===void 0&&(e.cssMinifier=await w({message:"Do you want to minify your css?",initialValue:!1}));let m;e.cssMinifier&&(m=await v({message:"Pick a css minifier",options:[{label:"CSSNano",value:"cssnano"},{label:"Lightning CSS",value:"lightningcss"}]}),p.includes("lightningcss")||await w({message:`Do you want to install "${m}"?`})&&l.push(m));let g="",c="";if(e.isolatedDeclarationTransformer&&(c+=`,
36
+ isolatedDeclarationTransformer`),(e.css||e.cssMinifier)&&(c+=`,
37
+ rollup: {
38
+ css: {`),e.css){const d=p.map(u=>((u==="sass-embedded"||u==="node-sass")&&(u="sass"),`${u}Loader`)).join(", ");c+=`
39
+ loaders: [${d}],`}if(e.cssMinifier&&m&&(c+=`
40
+ minifier: ${m}Minifier,`),(e.css||e.cssMinifier)&&(c+=`
41
+ }
42
+ }`),i||r.type==="module"){let d="";if(e.isolatedDeclarationTransformer&&(d+=`import isolatedDeclarationTransformer from "@visulima/packem/dts/isolated/transformer/${e.isolatedDeclarationTransformer}";
43
+ `),e.css)for(let u of p)(u==="sass-embedded"||u==="node-sass")&&(u="sass"),d+=`import ${u}Loader from "@visulima/packem/css/loader/${u.toLowerCase()}";
44
+ `;e.cssMinifier&&m&&(d+=`import ${m}Minifier from "@visulima/packem/css/minifier/${m.toLowerCase()}";
45
+ `),g=`import { defineConfig } from "@visulima/packem/config";
46
+ import transformer from "@visulima/packem/transformer/${e.transformer}";
47
+ ${d}
1059
48
  export default defineConfig({
1060
- runtime: "${options.runtime}",
1061
- transformer${packemConfig}
49
+ runtime: "${e.runtime}",
50
+ transformer${c}
1062
51
  });
1063
- `;
1064
- } else {
1065
- let imports = "";
1066
- if (options.isolatedDeclarationTransformer) {
1067
- imports += `const isolatedDeclarationTransformer = require("@visulima/packem/dts/isolated/transformer/${options.isolatedDeclarationTransformer}");
1068
- `;
1069
- }
1070
- if (options.css) {
1071
- for (let loader of cssLoaders) {
1072
- if (loader === "sass-embedded" || loader === "node-sass") {
1073
- loader = "sass";
1074
- }
1075
- imports += `const ${loader}Loader = require("@visulima/packem/css/loader/${loader.toLowerCase()}");
1076
- `;
1077
- }
1078
- }
1079
- if (options.cssMinifier && cssMinifier) {
1080
- imports += `const ${cssMinifier}Minifier = require("@visulima/packem/css/minifier/${cssMinifier.toLowerCase()}");
1081
- `;
1082
- }
1083
- template = `const { defineConfig } = require("@visulima/packem/config");
1084
- const transformer = require("@visulima/packem/transformer/${options.transformer}");
1085
- ${imports}
52
+ `}else{let d="";if(e.isolatedDeclarationTransformer&&(d+=`const isolatedDeclarationTransformer = require("@visulima/packem/dts/isolated/transformer/${e.isolatedDeclarationTransformer}");
53
+ `),e.css)for(let u of p)(u==="sass-embedded"||u==="node-sass")&&(u="sass"),d+=`const ${u}Loader = require("@visulima/packem/css/loader/${u.toLowerCase()}");
54
+ `;e.cssMinifier&&m&&(d+=`const ${m}Minifier = require("@visulima/packem/css/minifier/${m.toLowerCase()}");
55
+ `),g=`const { defineConfig } = require("@visulima/packem/config");
56
+ const transformer = require("@visulima/packem/transformer/${e.transformer}");
57
+ ${d}
1086
58
  module.exports = defineConfig({
1087
- runtime: ${options.runtime},
1088
- transformer${packemConfig}
59
+ runtime: ${e.runtime},
60
+ transformer${c}
1089
61
  });
1090
- `;
1091
- }
1092
- const s = spinner();
1093
- const extension = hasTypescript ? "ts" : "js";
1094
- if (packagesToInstall.length > 0) {
1095
- s.start("Installing packages");
1096
- await installPackage(packagesToInstall, {
1097
- cwd: rootDirectory,
1098
- dev: true,
1099
- silent: true
1100
- });
1101
- s.stop("Installed packages");
1102
- }
1103
- s.start(`Creating packem.config.${extension}`);
1104
- writeFileSync(join(rootDirectory, `packem.config.${extension}`), template);
1105
- s.stop(`Created packem.config.${extension}`);
1106
- outro("Now you can run `packem build` to build your project");
1107
- },
1108
- name: "init",
1109
- options: [
1110
- {
1111
- defaultValue: ".",
1112
- description: "The directory to initialize",
1113
- name: "dir",
1114
- type: String
1115
- },
1116
- {
1117
- description: "Choose a transformer",
1118
- name: "transformer",
1119
- type: (value) => {
1120
- if (typeof value === "string" && ["esbuild", "sucrase", "swc"].includes(value)) {
1121
- return value;
1122
- }
1123
- throw new Error("Invalid transformer, please choose one of 'swc', 'sucrase' or 'esbuild'");
1124
- }
1125
- },
1126
- {
1127
- description: "Choose a isolated declaration transformer",
1128
- name: "isolated-declaration-transformer",
1129
- type: (value) => {
1130
- if (typeof value === "string" && ["none", "oxc", "swc", "typescript"].includes(value)) {
1131
- return value;
1132
- }
1133
- throw new Error("Invalid isolated declaration isolated declaration, please choose one of 'none', 'oxc', 'swc' or 'typescript'");
1134
- }
1135
- },
1136
- {
1137
- description: "Use CSS",
1138
- name: "css",
1139
- type: Boolean
1140
- },
1141
- {
1142
- description: "Use CSS minifier",
1143
- name: "css-minifier",
1144
- type: Boolean
1145
- },
1146
- {
1147
- Description: "Use TypeScript",
1148
- name: "typescript",
1149
- type: Boolean
1150
- },
1151
- {
1152
- // defaultValue: "browser",
1153
- description: "Specify the build runtime (nodejs, browser).",
1154
- name: "runtime",
1155
- type: (input) => {
1156
- if (input === "node" || input === "browser") {
1157
- return input;
1158
- }
1159
- throw new Error("Invalid runtime. Use 'node' or 'browser'.");
1160
- }
1161
- }
1162
- ]
1163
- });
1164
- };
1165
-
1166
- const migrate = async ({ cwd, dryRun, logger }) => {
1167
- if (dryRun) {
1168
- logger.info("Dry run enabled. No changes will be made.");
1169
- } else {
1170
- const rl = createInterface({
1171
- input: process.stdin,
1172
- output: process.stdout
1173
- });
1174
- logger.warn(
1175
- `
62
+ `}const f=E(),b=i?"ts":"js";l.length>0&&(f.start("Installing packages"),await D(l,{cwd:a,dev:!0,silent:!0}),f.stop("Installed packages")),f.start(`Creating packem.config.${b}`),oe(S(a,`packem.config.${b}`),g),f.stop(`Created packem.config.${b}`),ee("Now you can run `packem build` to build your project")},"execute"),name:"init",options:[{defaultValue:".",description:"The directory to initialize",name:"dir",type:String},{description:"Choose a transformer",name:"transformer",type:x(s=>{if(typeof s=="string"&&["esbuild","sucrase","swc"].includes(s))return s;throw new Error("Invalid transformer, please choose one of 'swc', 'sucrase' or 'esbuild'")},"type")},{description:"Choose a isolated declaration transformer",name:"isolated-declaration-transformer",type:x(s=>{if(typeof s=="string"&&["none","oxc","swc","typescript"].includes(s))return s;throw new Error("Invalid isolated declaration isolated declaration, please choose one of 'none', 'oxc', 'swc' or 'typescript'")},"type")},{description:"Use CSS",name:"css",type:Boolean},{description:"Use CSS minifier",name:"css-minifier",type:Boolean},{Description:"Use TypeScript",name:"typescript",type:Boolean},{description:"Specify the build runtime (nodejs, browser).",name:"runtime",type:x(s=>{if(s==="node"||s==="browser")return s;throw new Error("Invalid runtime. Use 'node' or 'browser'.")},"type")}]})},"createInitCommand");var _e=Object.defineProperty,$=h((t,s)=>_e(t,"name",{value:s,configurable:!0}),"a");const Ye=$(async({cwd:t,dryRun:s,logger:e})=>{if(s)e.info("Dry run enabled. No changes will be made.");else{const o=ge({input:j.stdin,output:j.stdout});e.warn(`
1176
63
 
1177
64
  Before proceeding, review the migration guide at https://www.visulima.com/docs/package/packem, as this process will modify your files.
1178
- Uncommitted changes will be lost. Use the --dry-run flag to preview changes without applying them.`
1179
- );
1180
- const input = await rl.question(`Continue? (Y/n) `);
1181
- rl.close();
1182
- const confirm = input.toLowerCase() === "y" || input === "";
1183
- if (!confirm) {
1184
- logger.error("Migration cancelled.");
1185
- process.exitCode = 1;
1186
- return;
1187
- }
1188
- }
1189
- if (cwd)
1190
- process.chdir(cwd);
1191
- let migrated = false;
1192
- if (await migratePackageJson(dryRun, logger)) {
1193
- migrated = true;
1194
- }
1195
- if (await migrateConfigFiles(dryRun, logger)) {
1196
- migrated = true;
1197
- }
1198
- if (migrated) {
1199
- logger.success("Migration completed. Remember to run install command with your package manager.");
1200
- } else {
1201
- logger.error("No migration performed.");
1202
- process.exitCode = 1;
1203
- }
1204
- };
1205
- const DEP_MIGRATIONS = {
1206
- // From bunchee
1207
- bunchee: "@visulima/packem",
1208
- // From tsup
1209
- tsup: "@visulima/packem",
1210
- "tsup-node": "@visulima/packem",
1211
- // From unbuild
1212
- unbuild: "@visulima/packem"
1213
- // Add more bundlers as needed
1214
- };
1215
- const DEP_FIELDS = {
1216
- dependencies: `^${pkg.version}`,
1217
- devDependencies: `^${pkg.version}`,
1218
- peerDependencies: "*"
1219
- };
1220
- const migratePackageJson = async (dryRun, logger) => {
1221
- if (!existsSync("package.json")) {
1222
- logger.error("No package.json found");
1223
- return false;
1224
- }
1225
- const pkgRaw = await readFile$1("package.json", "utf8");
1226
- const pkg2 = JSON.parse(pkgRaw);
1227
- let found = false;
1228
- for (const [field, semver] of Object.entries(DEP_FIELDS)) {
1229
- for (const [oldDep, newDep] of Object.entries(DEP_MIGRATIONS)) {
1230
- if (pkg2[field]?.[oldDep]) {
1231
- logger.info(`Migrating \`${field}\` from ${oldDep} to ${newDep}.`);
1232
- found = true;
1233
- pkg2[field] = renameKey(pkg2[field], oldDep, newDep, semver);
1234
- }
1235
- }
1236
- }
1237
- if (pkg2.scripts) {
1238
- for (const key of Object.keys(pkg2.scripts)) {
1239
- for (const [oldCmd, newCmd] of Object.entries(DEP_MIGRATIONS)) {
1240
- if (pkg2.scripts[key].includes(oldCmd)) {
1241
- logger.info(`Migrating \`${key}\` script from ${oldCmd} to packem`);
1242
- found = true;
1243
- pkg2.scripts[key] = pkg2.scripts[key].replaceAll(new RegExp(String.raw`\b${oldCmd}\b`, "g"), "packem").replaceAll(new RegExp(String.raw`\b${oldCmd}-node\b`, "g"), "packem");
1244
- }
1245
- }
1246
- if (pkg2.scripts[key].includes("tsup")) {
1247
- logger.info(`Migrating \`${key}\` script from tsup to packem`);
1248
- found = true;
1249
- pkg2.scripts[key] = pkg2.scripts[key].replaceAll(/\btsup(?:-node)?/g, "packem build").replaceAll(/\bbuild\b/g, "build");
1250
- }
1251
- if (pkg2.scripts[key].includes("unbuild")) {
1252
- logger.info(`Migrating \`${key}\` script from unbuild to packem`);
1253
- found = true;
1254
- pkg2.scripts[key] = pkg2.scripts[key].replaceAll(/\bunbuild\b/g, "packem build");
1255
- }
1256
- if (pkg2.scripts[key].includes("bunchee")) {
1257
- logger.info(`Migrating \`${key}\` script from bunchee to packem`);
1258
- found = true;
1259
- pkg2.scripts[key] = pkg2.scripts[key].replaceAll(/\bbunchee\b/g, "packem build");
1260
- }
1261
- }
1262
- }
1263
- const configFields = ["tsup", "unbuild", "bunchee"];
1264
- for (const field of configFields) {
1265
- if (pkg2[field]) {
1266
- logger.info(`Found \`${field}\` config field in package.json. Consider moving to packem.config.ts`);
1267
- }
1268
- }
1269
- if (!found) {
1270
- logger.warn("No migratable bundler dependencies found in package.json");
1271
- return false;
1272
- }
1273
- const pkgString = `${JSON.stringify(pkg2, null, pkgRaw.includes(" ") ? " " : 2)}
1274
- `;
1275
- if (dryRun) {
1276
- logger.info("[dry-run] package.json changes:");
1277
- logger.info("Old content:");
1278
- console.info(pkgRaw);
1279
- logger.info("New content:");
1280
- console.info(pkgString);
1281
- } else {
1282
- await writeFile$1("package.json", pkgString);
1283
- logger.success("Migrated `package.json`");
1284
- }
1285
- return true;
1286
- };
1287
- const CONFIG_FILES = [
1288
- // tsup configs
1289
- "tsup.config.ts",
1290
- "tsup.config.cts",
1291
- "tsup.config.mts",
1292
- "tsup.config.js",
1293
- "tsup.config.cjs",
1294
- "tsup.config.mjs",
1295
- "tsup.config.json",
1296
- // unbuild configs
1297
- "build.config.ts",
1298
- "build.config.cts",
1299
- "build.config.mts",
1300
- "build.config.js",
1301
- "build.config.cjs",
1302
- "build.config.mjs",
1303
- // bunchee configs
1304
- "bunchee.config.ts",
1305
- "bunchee.config.cts",
1306
- "bunchee.config.mts",
1307
- "bunchee.config.js",
1308
- "bunchee.config.cjs",
1309
- "bunchee.config.mjs"
1310
- ];
1311
- const migrateConfigFiles = async (dryRun, logger) => {
1312
- let found = false;
1313
- for (const file of CONFIG_FILES) {
1314
- if (!existsSync(file))
1315
- continue;
1316
- logger.info(`Found config file \`${file}\`. Consider creating packem.config.ts instead.`);
1317
- logger.warn(`Manual migration required for config files. See https://www.visulima.com/docs/package/packem`);
1318
- found = true;
1319
- }
1320
- if (!found) {
1321
- logger.warn("No bundler config files found");
1322
- }
1323
- return found;
1324
- };
1325
- const renameKey = (object, oldKey, newKey, newValue) => {
1326
- const newObject = {};
1327
- for (const key of Object.keys(object)) {
1328
- if (key === oldKey) {
1329
- newObject[newKey] = newValue || object[oldKey];
1330
- } else {
1331
- newObject[key] = object[key];
1332
- }
1333
- }
1334
- return newObject;
1335
- };
1336
- const createMigrateCommand = (cli) => {
1337
- cli.addCommand({
1338
- description: "Migrate from other bundlers (tsup, unbuild, bunchee, etc.) to packem",
1339
- execute: async ({ logger, options }) => {
1340
- await migrate({
1341
- cwd: options.cwd,
1342
- dryRun: options.dryRun,
1343
- logger
1344
- });
1345
- },
1346
- name: "migrate",
1347
- options: [
1348
- {
1349
- defaultValue: ".",
1350
- description: "The directory to migrate",
1351
- name: "cwd",
1352
- type: String
1353
- },
1354
- {
1355
- description: "Preview changes without applying them",
1356
- name: "dry-run",
1357
- type: Boolean
1358
- }
1359
- ]
1360
- });
1361
- };
1362
-
1363
- try {
1364
- if (!require("node:module")?.enableCompileCache?.()) {
1365
- require("v8-compile-cache");
1366
- }
1367
- } catch {
1368
- }
1369
- const index = createCerebro("packem", {
1370
- logger: await createPailLogger({
1371
- reporters: [
1372
- new SimpleReporter({
1373
- error: {
1374
- hideErrorCauseCodeView: true,
1375
- hideErrorCodeView: true,
1376
- hideErrorErrorsCodeView: true
1377
- }
1378
- })
1379
- ],
1380
- scope: "packem"
1381
- }),
1382
- packageName: name,
1383
- packageVersion: version
1384
- });
1385
- createInitCommand(index);
1386
- createBuildCommand(index);
1387
- createAddCommand(index);
1388
- createMigrateCommand(index);
1389
- void index.run({
1390
- shouldExitProcess: false
1391
- });
65
+ Uncommitted changes will be lost. Use the --dry-run flag to preview changes without applying them.`);const r=await o.question("Continue? (Y/n) ");if(o.close(),!(r.toLowerCase()==="y"||r==="")){e.error("Migration cancelled."),j.exitCode=1;return}}t&&j.chdir(t);let a=!1;await Qe(s,e)&&(a=!0),await es(s,e)&&(a=!0),a?e.success("Migration completed. Remember to run install command with your package manager."):(e.error("No migration performed."),j.exitCode=1)},"migrate"),A={bunchee:"@visulima/packem",tsup:"@visulima/packem","tsup-node":"@visulima/packem",unbuild:"@visulima/packem"},He={dependencies:`^${R.version}`,devDependencies:`^${R.version}`,peerDependencies:"*"},Qe=$(async(t,s)=>{if(!U("package.json"))return s.error("No package.json found"),!1;const e=await me("package.json","utf8"),a=JSON.parse(e);let o=!1;for(const[i,l]of Object.entries(He))for(const[p,m]of Object.entries(A))a[i]?.[p]&&(s.info(`Migrating \`${i}\` from ${p} to ${m}.`),o=!0,a[i]=ss(a[i],p,m,l));if(a.scripts)for(const i of Object.keys(a.scripts)){for(const[l,p]of Object.entries(A))a.scripts[i].includes(l)&&(s.info(`Migrating \`${i}\` script from ${l} to packem`),o=!0,a.scripts[i]=a.scripts[i].replaceAll(new RegExp(String.raw`\b${l}\b`,"g"),"packem").replaceAll(new RegExp(String.raw`\b${l}-node\b`,"g"),"packem"));a.scripts[i].includes("tsup")&&(s.info(`Migrating \`${i}\` script from tsup to packem`),o=!0,a.scripts[i]=a.scripts[i].replaceAll(/\btsup(?:-node)?/g,"packem build").replaceAll(/\bbuild\b/g,"build")),a.scripts[i].includes("unbuild")&&(s.info(`Migrating \`${i}\` script from unbuild to packem`),o=!0,a.scripts[i]=a.scripts[i].replaceAll(/\bunbuild\b/g,"packem build")),a.scripts[i].includes("bunchee")&&(s.info(`Migrating \`${i}\` script from bunchee to packem`),o=!0,a.scripts[i]=a.scripts[i].replaceAll(/\bbunchee\b/g,"packem build"))}const r=["tsup","unbuild","bunchee"];for(const i of r)a[i]&&s.info(`Found \`${i}\` config field in package.json. Consider moving to packem.config.ts`);if(!o)return s.warn("No migratable bundler dependencies found in package.json"),!1;const n=`${JSON.stringify(a,null,e.includes(" ")?" ":2)}
66
+ `;return t?(s.info("[dry-run] package.json changes:"),s.info("Old content:"),console.info(e),s.info("New content:"),console.info(n)):(await fe("package.json",n),s.success("Migrated `package.json`")),!0},"migratePackageJson"),Ze=["tsup.config.ts","tsup.config.cts","tsup.config.mts","tsup.config.js","tsup.config.cjs","tsup.config.mjs","tsup.config.json","build.config.ts","build.config.cts","build.config.mts","build.config.js","build.config.cjs","build.config.mjs","bunchee.config.ts","bunchee.config.cts","bunchee.config.mts","bunchee.config.js","bunchee.config.cjs","bunchee.config.mjs"],es=$(async(t,s)=>{let e=!1;for(const a of Ze)U(a)&&(s.info(`Found config file \`${a}\`. Consider creating packem.config.ts instead.`),s.warn("Manual migration required for config files. See https://www.visulima.com/docs/package/packem"),e=!0);return e||s.warn("No bundler config files found"),e},"migrateConfigFiles"),ss=$((t,s,e,a)=>{const o={};for(const r of Object.keys(t))r===s?o[e]=a||t[s]:o[r]=t[r];return o},"renameKey"),ts=$(t=>{t.addCommand({description:"Migrate from other bundlers (tsup, unbuild, bunchee, etc.) to packem",execute:$(async({logger:s,options:e})=>{await Ye({cwd:e.cwd,dryRun:e.dryRun,logger:s})},"execute"),name:"migrate",options:[{defaultValue:".",description:"The directory to migrate",name:"cwd",type:String},{description:"Preview changes without applying them",name:"dry-run",type:Boolean}]})},"createMigrateCommand");try{require("node:module")?.enableCompileCache?.()||require("v8-compile-cache")}catch{}const P=_("packem",{logger:await Y({reporters:[new H({error:{hideErrorCauseCodeView:!0,hideErrorCodeView:!0,hideErrorErrorsCodeView:!0}})],scope:"packem"}),packageName:ye,packageVersion:J});Xe(P);Ke(P);Re(P);ts(P);P.run({shouldExitProcess:!1});