@octohash/vite-config 0.2.2 → 0.2.4

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,629 @@
1
+ import { isPackageExists } from 'local-pkg';
2
+ import { defineConfig as defineConfig$1, mergeConfig } from 'vite';
3
+ import { existsSync } from 'node:fs';
4
+ import path, { join, resolve, isAbsolute } from 'node:path';
5
+ import process from 'node:process';
6
+ import deepmerge from 'deepmerge';
7
+ import { findUp } from 'find-up';
8
+ import { readPackageJSON } from 'pkg-types';
9
+ import fsp from 'node:fs/promises';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { visualizer } from 'rollup-plugin-visualizer';
12
+ import { EOL } from 'node:os';
13
+ import dayjs from 'dayjs';
14
+ import Vue from '@vitejs/plugin-vue';
15
+ import VueJsx from '@vitejs/plugin-vue-jsx';
16
+ import Dts from 'vite-plugin-dts';
17
+
18
+ function getProjectType() {
19
+ const htmlPath = join(process.cwd(), "index.html");
20
+ return existsSync(htmlPath) ? "app" : "lib";
21
+ }
22
+ async function loadMergedPackageJson() {
23
+ const root = process.cwd();
24
+ const rootPkgJsonPath = await findUp("pnpm-lock.yaml", {
25
+ cwd: root,
26
+ type: "file"
27
+ });
28
+ const rootPkgJson = rootPkgJsonPath ? await readPackageJSON(rootPkgJsonPath) : {};
29
+ const pkgJson = await readPackageJSON(root);
30
+ return deepmerge(rootPkgJson, pkgJson);
31
+ }
32
+ function extractAuthorInfo(pkgJson) {
33
+ const { author } = pkgJson;
34
+ const isObject = typeof author === "object";
35
+ const name = isObject ? author.name : author;
36
+ const email = isObject ? author.email : void 0;
37
+ const url = isObject ? author.url : void 0;
38
+ return {
39
+ name,
40
+ email,
41
+ url
42
+ };
43
+ }
44
+ async function loadConditionPlugins(conditionPlugins) {
45
+ const plugins = [];
46
+ for (const conditionPlugin of conditionPlugins) {
47
+ if (conditionPlugin.condition) {
48
+ const realPlugins = await conditionPlugin.plugins();
49
+ plugins.push(...realPlugins);
50
+ }
51
+ }
52
+ return plugins.flat();
53
+ }
54
+ function resolveSubOptions(options, key) {
55
+ return typeof options[key] === "boolean" ? {} : options[key] || {};
56
+ }
57
+
58
+ const PACKAGE_ROOT = fileURLToPath(new URL(".", import.meta.url));
59
+ const VUE_PACKAGES = ["vue", "nuxt", "vitepress"];
60
+
61
+ const INJECT_SCRIPT = `
62
+ <script data-app-loading="inject-js">
63
+ ;(function () {
64
+ const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
65
+ const setting = localStorage.getItem('vueuse-color-scheme') || 'auto'
66
+ if (setting === 'dark' || (prefersDark && setting !== 'light'))
67
+ document.documentElement.classList.toggle('dark', true)
68
+ })()
69
+ <\/script>
70
+ `;
71
+ async function AppLoadingPlugin(options) {
72
+ const {
73
+ rootContainer = "app",
74
+ title = "",
75
+ filePath = path.join(PACKAGE_ROOT, "./default-loading.html")
76
+ } = options || {};
77
+ const loadingHtml = await getLoadingRawByHtmlTemplate(filePath);
78
+ return {
79
+ name: "vite-plugin-app-loading",
80
+ enforce: "pre",
81
+ transformIndexHtml: {
82
+ order: "pre",
83
+ handler: (html) => {
84
+ const rootContainerPattern = new RegExp(`<div id="${rootContainer}"\\s*></div>`, "i");
85
+ if (!rootContainerPattern.test(html)) {
86
+ return html;
87
+ }
88
+ const processedLoadingHtml = loadingHtml.replace(
89
+ "[app-loading-title]",
90
+ title
91
+ );
92
+ const injectedContent = `${INJECT_SCRIPT}${processedLoadingHtml}`;
93
+ return html.replace(
94
+ rootContainerPattern,
95
+ `<div id="${rootContainer}">${injectedContent}</div>`
96
+ );
97
+ }
98
+ }
99
+ };
100
+ }
101
+ async function getLoadingRawByHtmlTemplate(filePath) {
102
+ return await fsp.readFile(filePath, "utf8");
103
+ }
104
+
105
+ const scopeUrl = fileURLToPath(new URL(".", import.meta.url));
106
+ const isCwdInScope = isPackageExists("@octohash/vite-config");
107
+ function isPackageInScope(name) {
108
+ return isPackageExists(name, { paths: [scopeUrl] });
109
+ }
110
+ async function ensurePackages(packages) {
111
+ if (process.env.CI || process.stdout.isTTY === false || isCwdInScope === false)
112
+ return;
113
+ const nonExistingPackages = packages.filter((i) => i && !isPackageInScope(i));
114
+ if (nonExistingPackages.length === 0)
115
+ return;
116
+ const p = await import('@clack/prompts');
117
+ const result = await p.confirm({
118
+ message: `${nonExistingPackages.length === 1 ? "Package is" : "Packages are"} required for this config: ${nonExistingPackages.join(", ")}. Do you want to install them?`
119
+ });
120
+ if (result)
121
+ await import('@antfu/install-pkg').then((i) => i.installPackage(nonExistingPackages, { dev: true }));
122
+ }
123
+
124
+ async function LicensePlugin(options) {
125
+ const licenseText = await generateLicenseText(options || {});
126
+ return {
127
+ name: "vite-plugin-license",
128
+ enforce: "post",
129
+ apply: "build",
130
+ generateBundle: {
131
+ order: "post",
132
+ handler: (_options, bundle) => {
133
+ for (const [, fileContent] of Object.entries(bundle)) {
134
+ if (fileContent.type === "chunk" && fileContent.isEntry) {
135
+ const chunkContent = fileContent;
136
+ const content = chunkContent.code;
137
+ const updatedContent = `${licenseText}${EOL}${content}`;
138
+ fileContent.code = updatedContent;
139
+ }
140
+ }
141
+ }
142
+ }
143
+ };
144
+ }
145
+ async function generateLicenseText(options) {
146
+ const pkgJson = await loadMergedPackageJson();
147
+ const { name: authorName, email: authorEmail, url: authorUrl } = extractAuthorInfo(pkgJson);
148
+ const {
149
+ name = pkgJson.name,
150
+ author = authorName,
151
+ version = pkgJson.version,
152
+ description = pkgJson.description,
153
+ homepage = pkgJson.homepage ?? authorUrl,
154
+ license,
155
+ contact = authorEmail,
156
+ copyright = {
157
+ holder: authorName,
158
+ year: (/* @__PURE__ */ new Date()).getFullYear()
159
+ }
160
+ } = options ?? {};
161
+ const date = dayjs().format("YYYY-MM-DD");
162
+ const lines = [];
163
+ lines.push("/*!");
164
+ if (name)
165
+ lines.push(` * ${name}`);
166
+ if (version)
167
+ lines.push(` * Version: ${version}`);
168
+ if (author)
169
+ lines.push(` * Author: ${author}`);
170
+ if (license)
171
+ lines.push(` * License: ${license}`);
172
+ if (description)
173
+ lines.push(` * Description: ${description}`);
174
+ if (homepage)
175
+ lines.push(` * Homepage: ${homepage}`);
176
+ if (contact)
177
+ lines.push(` * Contact: ${contact}`);
178
+ if (copyright?.holder)
179
+ lines.push(` * Copyright (C) ${copyright.year} ${copyright.holder}`);
180
+ if (date)
181
+ lines.push(` * Date: ${date}`);
182
+ lines.push(" */");
183
+ return lines.join("\n");
184
+ }
185
+
186
+ async function loadCommonPlugins(options) {
187
+ const {
188
+ isBuild,
189
+ visualizer: visualizer$1 = false,
190
+ license = true,
191
+ federation
192
+ } = options;
193
+ ensurePackages([
194
+ federation ? "@originjs/vite-plugin-federation" : void 0
195
+ ]);
196
+ return await loadConditionPlugins([
197
+ {
198
+ condition: isBuild && !!visualizer$1,
199
+ plugins: () => [
200
+ visualizer(
201
+ typeof visualizer$1 === "boolean" ? {
202
+ filename: "./node_modules/.cache/visualizer/stats.html",
203
+ gzipSize: true,
204
+ open: true
205
+ } : visualizer$1
206
+ )
207
+ ]
208
+ },
209
+ {
210
+ condition: isBuild && !!license,
211
+ plugins: async () => [
212
+ await LicensePlugin(
213
+ typeof license === "boolean" ? void 0 : license
214
+ )
215
+ ]
216
+ },
217
+ {
218
+ condition: !!federation,
219
+ plugins: async () => {
220
+ const module = await import('@originjs/vite-plugin-federation');
221
+ return [
222
+ module.default(federation)
223
+ ];
224
+ }
225
+ }
226
+ ]);
227
+ }
228
+
229
+ const shimsSubpath = `dist/es-module-shims.js`;
230
+ const providerShimsMap = {
231
+ "jspm.io": `https://ga.jspm.io/npm:es-module-shims@{version}/${shimsSubpath}`,
232
+ "jsdelivr": `https://cdn.jsdelivr.net/npm/es-module-shims@{version}/${shimsSubpath}`,
233
+ "unpkg": `https://unpkg.com/es-module-shims@{version}/${shimsSubpath}`,
234
+ "esm.sh": `https://esm.sh/es-module-shims@{version}/${shimsSubpath}`
235
+ };
236
+ async function ImportMapPlugin(options = {}) {
237
+ await ensurePackages(["vite-plugin-jspm"]);
238
+ const module = await import('vite-plugin-jspm');
239
+ const {
240
+ defaultProvider = "jspm.io",
241
+ include = [],
242
+ exclude = []
243
+ } = options;
244
+ const [scan, mapping, post] = await module.default({
245
+ ...options,
246
+ pollyfillProvider: (version) => providerShimsMap[defaultProvider]?.replace("{version}", version)
247
+ });
248
+ const _resolveId = scan.resolveId;
249
+ scan.resolveId = function(id, importer, ctx) {
250
+ if (include.length && !include.includes(id) || exclude.length && exclude.includes(id)) {
251
+ return null;
252
+ }
253
+ return typeof _resolveId === "function" ? _resolveId.call(this, id, importer, ctx) : null;
254
+ };
255
+ const _load = mapping.load;
256
+ mapping.load = function(id) {
257
+ if (include.length && !include.includes(id)) {
258
+ return null;
259
+ }
260
+ return typeof _load === "function" ? _load.call(this, id) : null;
261
+ };
262
+ return [scan, mapping, post];
263
+ }
264
+
265
+ async function MetadataPlugin(options) {
266
+ const { extendMetadata = {} } = options ?? {};
267
+ const pkgJson = await loadMergedPackageJson();
268
+ const { name, description, homepage, license, version } = pkgJson;
269
+ const { name: authorName, email: authorEmail, url: authorUrl } = extractAuthorInfo(pkgJson);
270
+ const buildTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
271
+ return {
272
+ name: "vite-plugin-metadata",
273
+ enforce: "post",
274
+ config: () => {
275
+ return {
276
+ define: {
277
+ __VITE_APP_METADATA__: JSON.stringify({
278
+ authorName,
279
+ authorEmail,
280
+ authorUrl,
281
+ buildTime,
282
+ name,
283
+ description,
284
+ homepage,
285
+ license,
286
+ version,
287
+ ...extendMetadata
288
+ })
289
+ }
290
+ };
291
+ }
292
+ };
293
+ }
294
+
295
+ async function loadVuePlugins(projectType, options) {
296
+ const { isBuild } = options;
297
+ const isApp = projectType === "app";
298
+ const {
299
+ devtools = false,
300
+ i18n = false,
301
+ imports = isApp,
302
+ components = isApp,
303
+ pages = isApp
304
+ } = resolveSubOptions(options, "vue");
305
+ await ensurePackages([
306
+ devtools ? "vite-plugin-vue-devtools" : void 0,
307
+ i18n ? "@intlify/unplugin-vue-i18n" : void 0
308
+ ]);
309
+ return loadConditionPlugins([
310
+ {
311
+ condition: true,
312
+ plugins: () => [
313
+ Vue(),
314
+ VueJsx()
315
+ ]
316
+ },
317
+ {
318
+ condition: !isBuild && !!devtools,
319
+ plugins: async () => {
320
+ const module = await import('vite-plugin-vue-devtools');
321
+ return [
322
+ module.default(
323
+ typeof devtools === "boolean" ? void 0 : devtools
324
+ )
325
+ ];
326
+ }
327
+ },
328
+ {
329
+ condition: !!i18n,
330
+ plugins: async () => {
331
+ const module = await import('@intlify/unplugin-vue-i18n/vite');
332
+ return [
333
+ module.default(
334
+ typeof i18n === "boolean" ? {
335
+ compositionOnly: true,
336
+ fullInstall: true,
337
+ runtimeOnly: true
338
+ } : i18n
339
+ )
340
+ ];
341
+ }
342
+ },
343
+ {
344
+ condition: isApp && !!imports,
345
+ plugins: async () => {
346
+ const module = await import('unplugin-auto-import/vite');
347
+ return [
348
+ module.default(
349
+ typeof imports === "boolean" ? {
350
+ dts: "src/typings/auto-imports.d.ts",
351
+ imports: await resolveAutoImports(),
352
+ resolvers: await resolveUIComponentResolvers(),
353
+ dirs: [
354
+ "src/composables",
355
+ "src/utils"
356
+ ],
357
+ vueTemplate: true
358
+ } : imports
359
+ )
360
+ ];
361
+ }
362
+ },
363
+ {
364
+ condition: isApp && !!components,
365
+ plugins: async () => {
366
+ const module = await import('unplugin-vue-components/vite');
367
+ return [
368
+ module.default(
369
+ typeof components === "boolean" ? {
370
+ dts: "src/typings/components.d.ts",
371
+ directoryAsNamespace: true
372
+ } : components
373
+ )
374
+ ];
375
+ }
376
+ },
377
+ {
378
+ condition: isApp && !!pages,
379
+ plugins: async () => {
380
+ const module = await import('unplugin-vue-router/vite');
381
+ return [
382
+ module.default(
383
+ typeof pages === "boolean" ? {
384
+ dts: "src/typings/typed-router.d.ts"
385
+ } : pages
386
+ )
387
+ ];
388
+ }
389
+ }
390
+ ]);
391
+ }
392
+ async function resolveAutoImports() {
393
+ const imports = ["vue"];
394
+ if (isPackageExists("vue-router"))
395
+ imports.push("vue-router");
396
+ if (isPackageExists("pinia"))
397
+ imports.push("pinia");
398
+ if (isPackageExists("@vueuse/core"))
399
+ imports.push("@vueuse/core");
400
+ if (isPackageExists("vue-i18n"))
401
+ imports.push("vue-i18n");
402
+ return imports;
403
+ }
404
+ async function resolveUIComponentResolvers() {
405
+ const resolvers = [];
406
+ if (isPackageExists("ant-design-vue")) {
407
+ const { AntDesignVueResolver } = await import('unplugin-vue-components/resolvers');
408
+ resolvers.push(
409
+ AntDesignVueResolver({
410
+ importStyle: "css-in-js",
411
+ prefix: ""
412
+ })
413
+ );
414
+ }
415
+ if (isPackageExists("element-plus")) {
416
+ const { ElementPlusResolver } = await import('unplugin-vue-components/resolvers');
417
+ resolvers.push(...ElementPlusResolver());
418
+ }
419
+ if (isPackageExists("naive-ui")) {
420
+ const { NaiveUiResolver } = await import('unplugin-vue-components/resolvers');
421
+ resolvers.push(NaiveUiResolver());
422
+ }
423
+ if (isPackageExists("vant")) {
424
+ const { VantResolver } = await import('unplugin-vue-components/resolvers');
425
+ resolvers.push(VantResolver());
426
+ }
427
+ return resolvers;
428
+ }
429
+
430
+ async function loadAppPlugins(options) {
431
+ const {
432
+ isBuild,
433
+ dynamicBase,
434
+ appLoading = true,
435
+ metadata = true,
436
+ importMap = false,
437
+ vue
438
+ } = options;
439
+ const plugins = await loadCommonPlugins(options);
440
+ plugins.push(await loadConditionPlugins([
441
+ {
442
+ condition: !!dynamicBase,
443
+ plugins: async () => {
444
+ const module = await import('vite-plugin-dynamic-base');
445
+ return [
446
+ module.dynamicBase({
447
+ publicPath: dynamicBase,
448
+ transformIndexHtml: true
449
+ })
450
+ ];
451
+ }
452
+ },
453
+ {
454
+ condition: !!appLoading,
455
+ plugins: async () => [
456
+ await AppLoadingPlugin(
457
+ typeof appLoading === "boolean" ? void 0 : appLoading
458
+ )
459
+ ]
460
+ },
461
+ {
462
+ condition: !!metadata,
463
+ plugins: async () => {
464
+ return [
465
+ await MetadataPlugin(
466
+ typeof metadata === "boolean" ? void 0 : metadata
467
+ )
468
+ ];
469
+ }
470
+ },
471
+ {
472
+ condition: isBuild && !!importMap,
473
+ plugins: () => {
474
+ return [
475
+ ImportMapPlugin(
476
+ typeof importMap === "boolean" ? void 0 : importMap
477
+ )
478
+ ];
479
+ }
480
+ }
481
+ ]));
482
+ if (vue)
483
+ plugins.push(await loadVuePlugins("app", options));
484
+ return plugins;
485
+ }
486
+
487
+ async function getCommonConfig(options) {
488
+ const { alias = {} } = options;
489
+ const resolvedAlias = Object.entries(alias).reduce((acc, [key, value]) => {
490
+ acc[key] = isAbsolute(value) ? value : resolve(process.cwd(), value);
491
+ return acc;
492
+ }, {});
493
+ return {
494
+ resolve: {
495
+ alias: {
496
+ "@": resolve(process.cwd(), "./src"),
497
+ ...resolvedAlias
498
+ }
499
+ },
500
+ build: {
501
+ chunkSizeWarningLimit: 2e3,
502
+ reportCompressedSize: false,
503
+ sourcemap: false
504
+ }
505
+ };
506
+ }
507
+
508
+ function defineAppConfig(options) {
509
+ return defineConfig$1(async (config) => {
510
+ const { dynamicBase, vite = {} } = options;
511
+ const { command } = config;
512
+ const isBuild = command === "build";
513
+ const plugins = await loadAppPlugins({
514
+ ...options,
515
+ isBuild
516
+ });
517
+ const appConfig = {
518
+ base: dynamicBase ? "/__dynamic_base__/" : "/",
519
+ plugins,
520
+ build: {
521
+ target: "es2015",
522
+ rollupOptions: {
523
+ output: {
524
+ assetFileNames: "[ext]/[name]-[hash].[ext]",
525
+ chunkFileNames: "js/[name]-[hash].js",
526
+ entryFileNames: "jse/index-[name]-[hash].js"
527
+ }
528
+ }
529
+ },
530
+ esbuild: {
531
+ drop: isBuild ? [
532
+ // 'console',
533
+ "debugger"
534
+ ] : [],
535
+ legalComments: "none"
536
+ },
537
+ server: {
538
+ host: true
539
+ }
540
+ };
541
+ const mergedCommonConfig = mergeConfig(
542
+ await getCommonConfig(options),
543
+ appConfig
544
+ );
545
+ return mergeConfig(mergedCommonConfig, vite);
546
+ });
547
+ }
548
+
549
+ async function loadLibPlugins(options) {
550
+ const {
551
+ isBuild,
552
+ dts = true,
553
+ vue
554
+ } = options;
555
+ const plugins = await loadCommonPlugins(options);
556
+ plugins.push(await loadConditionPlugins([
557
+ {
558
+ condition: isBuild && !!dts,
559
+ plugins: () => [
560
+ Dts(
561
+ typeof dts === "boolean" ? {
562
+ logLevel: "error"
563
+ } : dts
564
+ )
565
+ ]
566
+ }
567
+ ]));
568
+ if (vue)
569
+ plugins.push(await loadVuePlugins("lib", options));
570
+ return plugins;
571
+ }
572
+
573
+ function defineLibConfig(options) {
574
+ return defineConfig$1(async (config) => {
575
+ const root = process.cwd();
576
+ const { vite = {} } = options;
577
+ const { command } = config;
578
+ const isBuild = command === "build";
579
+ const plugins = await loadLibPlugins({
580
+ ...options,
581
+ isBuild
582
+ });
583
+ const { dependencies = {}, peerDependencies = {} } = await readPackageJSON(root);
584
+ const externalPackages = [
585
+ ...Object.keys(dependencies),
586
+ ...Object.keys(peerDependencies)
587
+ ];
588
+ const libConfig = {
589
+ plugins,
590
+ build: {
591
+ lib: {
592
+ entry: "src/index.ts",
593
+ fileName: () => "index.mjs",
594
+ formats: ["es"]
595
+ },
596
+ rollupOptions: {
597
+ external: (id) => {
598
+ return externalPackages.some(
599
+ (pkg) => id === pkg || id.startsWith(`${pkg}/`)
600
+ );
601
+ }
602
+ }
603
+ }
604
+ };
605
+ const mergedCommonConfig = mergeConfig(
606
+ await getCommonConfig(options),
607
+ libConfig
608
+ );
609
+ return mergeConfig(mergedCommonConfig, vite);
610
+ });
611
+ }
612
+
613
+ function defineConfig(options) {
614
+ const resolved = {
615
+ type: getProjectType(),
616
+ vue: VUE_PACKAGES.some((pkg) => isPackageExists(pkg)),
617
+ ...options
618
+ };
619
+ switch (resolved.type) {
620
+ case "app":
621
+ return defineAppConfig(resolved);
622
+ case "lib":
623
+ return defineLibConfig(resolved);
624
+ default:
625
+ throw new Error(`Unsupported project type: ${resolved.type}`);
626
+ }
627
+ }
628
+
629
+ export { defineConfig };