@vixt/core 0.5.17 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,239 +1,401 @@
1
- import { loadConfig } from 'c12';
2
- import fs from 'fs-extra';
3
- import path, { resolve, normalize } from 'pathe';
4
- import { env, cwd } from 'node:process';
5
- import { cac } from 'cac';
6
- import { findUpSync } from 'find-up';
7
- import { loadEnv as loadEnv$1 } from 'vite';
8
- import defu from 'defu';
9
- import { pathToFileURL } from 'mlly';
10
- import 'tsx/esm';
11
- import Checker from 'vite-plugin-checker';
1
+ import { loadConfig } from "c12";
2
+ import fs from "fs-extra";
3
+ import path, { normalize, resolve } from "pathe";
4
+ import process, { cwd, env } from "node:process";
5
+ import { cac } from "cac";
6
+ import { findUpSync } from "find-up";
7
+ import { loadEnv as loadEnv$1, mergeConfig, parseAst } from "vite";
8
+ import defu from "defu";
9
+ import { createJiti } from "jiti";
10
+ import { pathToFileURL } from "mlly";
11
+ import Legacy from "@vitejs/plugin-legacy";
12
+ import Analyzer from "vite-bundle-analyzer";
13
+ import Ssl from "@vitejs/plugin-basic-ssl";
14
+ import Checker from "vite-plugin-checker";
12
15
 
16
+ //#region src/node/env.ts
17
+ function loadCLIOptions() {
18
+ return cac().parse().options ?? {};
19
+ }
20
+ function loadMode() {
21
+ const { mode, m } = loadCLIOptions();
22
+ return mode || m || env.NODE_ENV;
23
+ }
24
+ /**
25
+ * Load workspace and cwd env variables by default
26
+ */
27
+ function loadEnv(mode, envDir, prefixes) {
28
+ mode = mode || loadMode();
29
+ return {
30
+ MODE: mode,
31
+ DEV: env.NODE_ENV !== "production",
32
+ PROD: env.NODE_ENV === "production",
33
+ ...loadWorkspaceEnv(mode, prefixes),
34
+ ...loadEnv$1(mode, envDir || cwd(), prefixes)
35
+ };
36
+ }
37
+ /**
38
+ * find the workspace dir
39
+ */
40
+ function findUpWorkspaceDir() {
41
+ const workspaceManifestLocation = findUpSync(["pnpm-workspace.yaml", "pnpm-workspace.yml"]);
42
+ return workspaceManifestLocation && path.dirname(workspaceManifestLocation);
43
+ }
44
+ /**
45
+ * Load workspace env variables
46
+ */
47
+ function loadWorkspaceEnv(mode, prefixes) {
48
+ const workspaceDir = findUpWorkspaceDir();
49
+ return workspaceDir ? loadEnv$1(mode, workspaceDir, prefixes) : {};
50
+ }
51
+
52
+ //#endregion
53
+ //#region src/node/config.ts
13
54
  function defineVixtConfig(input) {
14
- return input;
55
+ return input;
15
56
  }
16
57
  async function loadVixtConfig(opts) {
17
- const result = await loadConfig({
18
- name: "vixt",
19
- rcFile: false,
20
- ...opts
21
- });
22
- const { config, cwd } = result;
23
- config.rootDir ??= cwd;
24
- config.buildDir ??= resolve(config.rootDir, ".vixt");
25
- config.buildTypesDir ??= resolve(config.buildDir, "types");
26
- config.buildLayersDir ??= resolve(config.buildDir, "layers");
27
- config.buildImportsDir ??= resolve(config.buildDir, "imports");
28
- config.srcDir ??= resolve(config.rootDir, "src");
29
- return result;
58
+ const result = await loadConfig({
59
+ name: "vixt",
60
+ rcFile: false,
61
+ ...opts
62
+ });
63
+ const { config, cwd: cwd$1 } = result;
64
+ config.rootDir ??= cwd$1;
65
+ config.buildDir ??= resolve(config.rootDir, ".vixt");
66
+ config.buildTypesDir ??= resolve(config.buildDir, "types");
67
+ config.buildLayersDir ??= resolve(config.buildDir, "layers");
68
+ config.buildImportsDir ??= resolve(config.buildDir, "imports");
69
+ config.workspaceDir ??= findUpWorkspaceDir();
70
+ config.srcDir ??= resolve(config.rootDir, "src");
71
+ config.modulesDir ??= resolve(config.srcDir, "modules");
72
+ config.pluginsDir ??= resolve(config.srcDir, "plugins");
73
+ return result;
30
74
  }
31
75
  function applyLayers(layers, config) {
32
- const { rootDir, buildLayersDir } = config;
33
- return layers.filter((e) => e.cwd).map((layer) => {
34
- const meta = layer.config?.meta ?? {};
35
- const layerName = meta.name || layer.cwd.split("/").pop();
36
- if (!isSamePath(layer.cwd, resolve(rootDir))) {
37
- meta.alias = `#/layers/${layerName}`;
38
- }
39
- if (layer.cwd?.includes("node_modules")) {
40
- const newCwd = resolve(buildLayersDir, layerName);
41
- fs.removeSync(newCwd);
42
- fs.copySync(layer.cwd, newCwd, {
43
- filter: (src) => {
44
- const nodeModulesPath = resolve(layer.cwd, "node_modules");
45
- const tsConfigPath = resolve(layer.cwd, "tsconfig.json");
46
- return !isSamePath(src, nodeModulesPath) && !isSamePath(src, tsConfigPath);
47
- }
48
- });
49
- layer.cwd = newCwd;
50
- }
51
- layer.config ??= {};
52
- layer.config.rootDir ??= layer.cwd;
53
- layer.config.srcDir ??= resolve(layer.config.rootDir, "src");
54
- return { ...layer, meta };
55
- });
76
+ const { rootDir, buildLayersDir } = config;
77
+ return layers.filter((e) => e.cwd).map((layer) => {
78
+ const meta = layer.config?.meta ?? {};
79
+ const layerName = meta.name || layer.cwd.split("/").pop();
80
+ if (!isSamePath(layer.cwd, resolve(rootDir))) meta.alias = `#/layers/${layerName}`;
81
+ if (layer.cwd?.includes("node_modules")) {
82
+ const newCwd = resolve(buildLayersDir, layerName);
83
+ fs.removeSync(newCwd);
84
+ fs.copySync(layer.cwd, newCwd, { filter: (src) => {
85
+ const nodeModulesPath = resolve(layer.cwd, "node_modules");
86
+ const tsConfigPath = resolve(layer.cwd, "tsconfig.json");
87
+ return !isSamePath(src, nodeModulesPath) && !isSamePath(src, tsConfigPath);
88
+ } });
89
+ layer.cwd = newCwd;
90
+ }
91
+ layer.config ??= {};
92
+ layer.config.rootDir ??= layer.cwd;
93
+ layer.config.srcDir ??= resolve(layer.config.rootDir, "src");
94
+ layer.config.modulesDir ??= resolve(layer.config.srcDir, "modules");
95
+ layer.config.pluginsDir ??= resolve(layer.config.srcDir, "plugins");
96
+ return {
97
+ ...layer,
98
+ meta
99
+ };
100
+ });
56
101
  }
57
102
  function isSamePath(a, b) {
58
- return normalize(a) === normalize(b);
103
+ return normalize(a) === normalize(b);
59
104
  }
60
105
  function resolveLayersDirs(layers = []) {
61
- const dirs = {};
62
- for (const layer of layers) {
63
- const srcPath = layer.config.srcDir;
64
- const isExist = fs.existsSync(srcPath);
65
- const contents = isExist ? fs.readdirSync(srcPath) : [];
66
- for (const content of contents) {
67
- const fileOrDirPath = resolve(srcPath, content);
68
- if (fs.statSync(fileOrDirPath).isDirectory()) {
69
- dirs[content] ??= [];
70
- dirs[content].push(fileOrDirPath);
71
- }
72
- }
73
- }
74
- return dirs;
75
- }
76
-
77
- function loadEnv(mode, envDir, prefixes) {
78
- const parsedArgv = cac().parse();
79
- mode = mode || parsedArgv.options.mode || parsedArgv.options.m || env.NODE_ENV;
80
- return {
81
- MODE: mode,
82
- DEV: env.NODE_ENV !== "production",
83
- PROD: env.NODE_ENV === "production",
84
- ...loadWorkspaceEnv(mode, prefixes),
85
- ...loadEnv$1(mode, envDir || cwd(), prefixes)
86
- };
87
- }
88
- function findUpWorkspaceDir() {
89
- const workspaceManifestLocation = findUpSync(["pnpm-workspace.yaml", "pnpm-workspace.yml"]);
90
- return workspaceManifestLocation && path.dirname(workspaceManifestLocation);
91
- }
92
- function loadWorkspaceEnv(mode, prefixes) {
93
- const workspaceDir = findUpWorkspaceDir();
94
- return workspaceDir ? loadEnv$1(mode, workspaceDir, prefixes) : {};
106
+ const dirs = {};
107
+ for (const layer of layers) {
108
+ const srcPath = layer.config.srcDir;
109
+ const contents = fs.existsSync(srcPath) ? fs.readdirSync(srcPath) : [];
110
+ for (const content of contents) {
111
+ const fileOrDirPath = resolve(srcPath, content);
112
+ if (fs.statSync(fileOrDirPath).isDirectory()) {
113
+ dirs[content] ??= [];
114
+ dirs[content].push(fileOrDirPath);
115
+ }
116
+ }
117
+ }
118
+ return dirs;
95
119
  }
120
+ const VixtClientAutoImports = { "@vixt/core/client": [
121
+ "defineAppConfig",
122
+ "defineVixtPlugin",
123
+ "useAppConfig",
124
+ "useVixtApp"
125
+ ] };
96
126
 
127
+ //#endregion
128
+ //#region src/node/module.ts
97
129
  function defineVitePlugin(pluginFn) {
98
- return pluginFn;
130
+ return pluginFn;
99
131
  }
100
132
  function defineVixtModule(definition) {
101
- if (typeof definition == "function")
102
- return defineVixtModule({ setup: definition });
103
- const module = definition;
104
- function getOptions(inlineOptions, vixt) {
105
- const configKey = module.meta?.configKey || module.meta?.name;
106
- const configOptions = configKey ? vixt.options[configKey] : {};
107
- const defaultOptions = typeof module.defaults === "function" ? module.defaults(vixt) : module.defaults;
108
- const resolvedOptions = defu(inlineOptions, configOptions, defaultOptions);
109
- if (configKey) {
110
- vixt.options[configKey] = resolvedOptions;
111
- }
112
- return resolvedOptions;
113
- }
114
- function normalizedModule(inlineOptions, vixt) {
115
- const options = getOptions(inlineOptions, vixt);
116
- return module.setup?.(options, vixt);
117
- }
118
- normalizedModule.getMeta = () => module.meta;
119
- normalizedModule.getOptions = getOptions;
120
- return normalizedModule;
133
+ if (typeof definition == "function") return defineVixtModule({ setup: definition });
134
+ const module = definition;
135
+ function getOptions(inlineOptions, vixt) {
136
+ const configKey = module.meta?.configKey || module.meta?.name;
137
+ const resolvedOptions = defu(inlineOptions, configKey ? vixt.options[configKey] : {}, typeof module.defaults === "function" ? module.defaults(vixt) : module.defaults);
138
+ if (configKey) vixt.options[configKey] = resolvedOptions;
139
+ return resolvedOptions;
140
+ }
141
+ function normalizedModule(inlineOptions, vixt) {
142
+ const options = getOptions(inlineOptions, vixt);
143
+ return module.setup?.(options, vixt);
144
+ }
145
+ normalizedModule.getMeta = () => module.meta;
146
+ normalizedModule.getOptions = getOptions;
147
+ return normalizedModule;
121
148
  }
122
149
  function installModule(module, inlineOptions, vixt) {
123
- return module(inlineOptions, vixt);
150
+ return module(inlineOptions, vixt);
124
151
  }
125
152
  async function applyLayerModules(layers) {
126
- const { modules: modulesDirs = [] } = resolveLayersDirs(layers);
127
- const modules = [];
128
- for (const m of modulesDirs.reverse()) {
129
- if (fs.existsSync(m)) {
130
- const files = fs.readdirSync(m);
131
- for (const f of files.filter((f2) => !f2.includes(".") || /\.[jt]s$/.test(f2))) {
132
- try {
133
- const fileURL = pathToFileURL(path.resolve(m, f));
134
- const module = await import(
135
- /* @vite-ignore */
136
- fileURL
137
- ).then((m2) => m2.default);
138
- modules.push(module);
139
- } catch (error) {
140
- console.error("[VixtModule Error]:", error);
141
- }
142
- }
143
- }
144
- }
145
- return modules;
153
+ const { modules: modulesDirs = [] } = resolveLayersDirs(layers);
154
+ const modules = [];
155
+ const jiti = createJiti(layers[0]?.cwd ?? process.cwd(), { moduleCache: false });
156
+ for (const m of modulesDirs.reverse()) if (fs.existsSync(m)) {
157
+ const files = fs.readdirSync(m);
158
+ for (const f of files) try {
159
+ const fileURL = pathToFileURL(path.resolve(m, f));
160
+ const module = await jiti.import(fileURL, { default: true });
161
+ modules.push(module);
162
+ } catch {}
163
+ }
164
+ return modules;
146
165
  }
147
166
 
148
- const name$1 = "vixt:config";
149
- const config = defineVixtModule({
150
- meta: { name: name$1 },
151
- setup(_, vixt) {
152
- let env;
153
- return {
154
- name: name$1,
155
- enforce: "pre",
156
- config(config2) {
157
- const { rootDir, buildDir, srcDir, app } = vixt.options;
158
- const defaultAlias = {
159
- "@": srcDir,
160
- "~": srcDir,
161
- "@@": rootDir,
162
- "~~": rootDir
163
- };
164
- for (const layer of vixt._layers) {
165
- if (layer.meta?.alias) {
166
- defaultAlias[layer.meta.alias] = layer.cwd;
167
- }
168
- }
169
- defaultAlias["#"] = buildDir;
170
- env = loadEnv(config2.mode, config2.envDir, config2.envPrefix);
171
- const defineEnv = Object.fromEntries(
172
- Object.entries(env).filter(([k]) => !["MODE", "DEV", "PROD"].includes(k)).map(([k, v]) => [`import.meta.env.${k}`, JSON.stringify(v)])
173
- );
174
- return {
175
- root: rootDir,
176
- base: app?.baseURL,
177
- resolve: {
178
- alias: defaultAlias
179
- },
180
- define: defineEnv
181
- };
182
- },
183
- configResolved(config2) {
184
- Object.assign(config2.env, { ...env, ...config2.env });
185
- vixt.options.vite = config2;
186
- },
187
- configureServer(server) {
188
- const mode = server.config.mode;
189
- const watchFiles = [];
190
- const configFiles = vixt._layers.map((layer) => layer.configFile).filter((e) => !e.includes("node_modules"));
191
- const modulesDirs = vixt._layers.map((layer) => path.resolve(layer.config.srcDir, "modules")).filter((e) => !e.includes("node_modules"));
192
- watchFiles.push(...configFiles, ...modulesDirs);
193
- const workspaceManifestLocation = findUpSync(["pnpm-workspace.yaml", "pnpm-workspace.yml"]);
194
- if (workspaceManifestLocation) {
195
- const workspaceDir = path.dirname(workspaceManifestLocation);
196
- const envFiles = [`${workspaceDir}/.env`, `${workspaceDir}/.env.local`, `${workspaceDir}/.env.${mode}`, `${workspaceDir}/.env.${mode}.local`];
197
- watchFiles.push(...envFiles);
198
- }
199
- server.watcher.add(watchFiles);
200
- server.watcher.on("all", (_2, file) => {
201
- const match = watchFiles.some((e) => path.normalize(file).match(e));
202
- if (match)
203
- server.restart();
204
- });
205
- }
206
- };
207
- }
167
+ //#endregion
168
+ //#region src/node/modules/alias.ts
169
+ const name$8 = "vixt:alias";
170
+ var alias_default = defineVixtModule({
171
+ meta: {
172
+ name: name$8,
173
+ configKey: "alias"
174
+ },
175
+ defaults(vixt) {
176
+ const { rootDir, buildDir, srcDir } = vixt.options;
177
+ const alias = {
178
+ "@": srcDir,
179
+ "~": srcDir,
180
+ "@@": rootDir,
181
+ "~~": rootDir
182
+ };
183
+ for (const layer of vixt._layers) if (layer.meta?.alias) alias[layer.meta.alias] = layer.cwd;
184
+ alias["#"] = buildDir;
185
+ return alias;
186
+ },
187
+ setup(options) {
188
+ return {
189
+ name: name$8,
190
+ enforce: "pre",
191
+ config() {
192
+ return { resolve: { alias: options } };
193
+ }
194
+ };
195
+ }
208
196
  });
209
197
 
198
+ //#endregion
199
+ //#region src/node/modules/app.ts
200
+ function resolveHead(tag, attrs) {
201
+ const defaultInjectTo = ["script", "noscript"].includes(tag) ? "body" : void 0;
202
+ const { children, injectTo = defaultInjectTo, ..._attrs } = attrs;
203
+ return {
204
+ tag,
205
+ attrs: _attrs,
206
+ children,
207
+ injectTo
208
+ };
209
+ }
210
+ function isEmptyCode(code) {
211
+ if (!code) return true;
212
+ try {
213
+ return !parseAst(code, { jsx: true }).body.length;
214
+ } catch {
215
+ return true;
216
+ }
217
+ }
218
+ function resolveLoadingTemplate(options, vixt) {
219
+ const { loadingTemplate } = options;
220
+ if (loadingTemplate && fs.existsSync(loadingTemplate)) return fs.readFileSync(loadingTemplate, "utf-8");
221
+ for (const layer of vixt._layers) {
222
+ const layerLoadingTemplate = path.resolve(layer.cwd, "loading.html");
223
+ if (fs.existsSync(layerLoadingTemplate)) return fs.readFileSync(layerLoadingTemplate, "utf-8");
224
+ }
225
+ }
226
+ function resolveEntryCode(options, vixt) {
227
+ const { entryCode, entryFile } = options;
228
+ for (const layer of vixt._layers) {
229
+ const layerEntryPath = path.resolve(layer.config.srcDir, entryFile);
230
+ const code = fs.existsSync(layerEntryPath) && fs.readFileSync(layerEntryPath, "utf-8") || "";
231
+ if (!isEmptyCode(code)) return code;
232
+ }
233
+ return entryCode;
234
+ }
235
+ const name$7 = "vixt:app";
236
+ var app_default = defineVixtModule({
237
+ meta: {
238
+ name: name$7,
239
+ configKey: "app"
240
+ },
241
+ defaults: {
242
+ rootId: "app",
243
+ rootTag: "div",
244
+ baseURL: "/",
245
+ css: []
246
+ },
247
+ setup(options, vixt) {
248
+ const { srcDir } = vixt.options;
249
+ const { entryFile, rootTag, rootId, head } = options;
250
+ const relativeEntryPath = `/${path.basename(srcDir)}/${entryFile}`;
251
+ const absoluteEntryPath = path.resolve(srcDir, entryFile);
252
+ const order = "pre";
253
+ return {
254
+ name: name$7,
255
+ enforce: order,
256
+ load: {
257
+ order,
258
+ handler(id) {
259
+ if (id === relativeEntryPath) return resolveEntryCode(options, vixt);
260
+ }
261
+ },
262
+ transform: {
263
+ order,
264
+ handler(code, id) {
265
+ if (id === absoluteEntryPath && isEmptyCode(code)) return resolveEntryCode(options, vixt);
266
+ }
267
+ },
268
+ transformIndexHtml: {
269
+ order,
270
+ handler() {
271
+ const tags = Object.entries(head ?? {}).map(([tag, attrs]) => attrs.map((attr) => resolveHead(tag, attr))).flat();
272
+ const loadingTemplate = resolveLoadingTemplate(options, vixt);
273
+ return [
274
+ {
275
+ tag: rootTag,
276
+ attrs: { id: rootId },
277
+ children: loadingTemplate,
278
+ injectTo: "body"
279
+ },
280
+ {
281
+ tag: "script",
282
+ attrs: {
283
+ type: "module",
284
+ src: relativeEntryPath
285
+ },
286
+ injectTo: "body"
287
+ },
288
+ ...tags
289
+ ];
290
+ }
291
+ }
292
+ };
293
+ }
294
+ });
295
+
296
+ //#endregion
297
+ //#region src/node/modules/build.ts
298
+ const name$6 = "vixt:build";
299
+ var build_default = defineVixtModule({
300
+ meta: {
301
+ name: name$6,
302
+ configKey: "build"
303
+ },
304
+ setup(options) {
305
+ const analyzeOptions = {
306
+ enabled: !!options.analyze,
307
+ ...typeof options.analyze === "object" ? options.analyze : {}
308
+ };
309
+ const legacyOptions = {
310
+ enabled: !!options.legacy,
311
+ ...typeof options.legacy === "object" ? options.legacy : {}
312
+ };
313
+ return [analyzeOptions.enabled && Analyzer(analyzeOptions), legacyOptions.enabled && Legacy(legacyOptions)];
314
+ }
315
+ });
316
+
317
+ //#endregion
318
+ //#region src/node/modules/dev-server.ts
319
+ const name$5 = "vixt:dev-server";
320
+ var dev_server_default = defineVixtModule({
321
+ meta: {
322
+ name: name$5,
323
+ configKey: "devServer"
324
+ },
325
+ defaults(vixt) {
326
+ const watchFiles = [];
327
+ const configFiles = vixt._layers.map((layer) => layer.configFile).filter((e) => !e.includes("node_modules"));
328
+ const modulesDirs = vixt._layers.map((layer) => layer.config.modulesDir).filter((e) => !e.includes("node_modules"));
329
+ watchFiles.push(...configFiles, ...modulesDirs);
330
+ const workspaceDir = findUpWorkspaceDir();
331
+ if (workspaceDir) {
332
+ const mode = loadMode();
333
+ const envFiles = [
334
+ `${workspaceDir}/.env`,
335
+ `${workspaceDir}/.env.local`,
336
+ `${workspaceDir}/.env.${mode}`,
337
+ `${workspaceDir}/.env.${mode}.local`
338
+ ];
339
+ watchFiles.push(...envFiles);
340
+ }
341
+ return { watch: watchFiles };
342
+ },
343
+ setup(options) {
344
+ const sslOptions = {
345
+ enabled: !!options.https,
346
+ ...typeof options.https === "object" ? options.https : {}
347
+ };
348
+ const watchFiles = options.watch ?? [];
349
+ let timer;
350
+ function schedule(fn) {
351
+ clearTimeout(timer);
352
+ timer = setTimeout(fn, 500);
353
+ }
354
+ return [{
355
+ name: name$5,
356
+ enforce: "pre",
357
+ config() {
358
+ const { port, host, cors } = options;
359
+ return { server: {
360
+ port,
361
+ host,
362
+ cors
363
+ } };
364
+ },
365
+ configureServer(server) {
366
+ server.watcher.add(watchFiles);
367
+ server.watcher.on("all", (_, file) => {
368
+ watchFiles.some((e) => path.normalize(file).match(e)) && schedule(() => server.restart());
369
+ });
370
+ }
371
+ }, sslOptions.enabled && Ssl(sslOptions)];
372
+ }
373
+ });
374
+
375
+ //#endregion
376
+ //#region src/node/modules/typescript.ts
210
377
  function generateTsConfig(options, vixt) {
211
- const { buildDir } = vixt.options;
212
- const codePath = path.resolve(buildDir, "tsconfig.json");
213
- const code = JSON.stringify(options.tsConfig, null, 2);
214
- fs.outputFileSync(codePath, code);
378
+ const { buildDir } = vixt.options;
379
+ const codePath = path.resolve(buildDir, "tsconfig.json");
380
+ const code = JSON.stringify(options.tsConfig, null, 2);
381
+ fs.outputFileSync(codePath, code);
215
382
  }
216
383
  function generateVixtDts(options, vixt) {
217
- const { buildDir } = vixt.options;
218
- const codePath = path.resolve(buildDir, "vixt.d.ts");
219
- const code = options.references?.map((reference) => {
220
- if (typeof reference === "string") {
221
- return `/// <reference path="${reference}" />`;
222
- } else if (typeof reference === "object" && reference.path && reference.content) {
223
- fs.outputFileSync(path.resolve(buildDir, reference.path), reference.content);
224
- return `/// <reference path="${reference.path}" />`;
225
- } else {
226
- return "";
227
- }
228
- }).concat("export {}").join("\n");
229
- if (code)
230
- fs.outputFileSync(codePath, code);
384
+ const { buildDir } = vixt.options;
385
+ const codePath = path.resolve(buildDir, "vixt.d.ts");
386
+ const code = options.references?.map((reference) => {
387
+ if (typeof reference === "string") return `/// <reference path="${reference}" />`;
388
+ else if (typeof reference === "object" && reference.path && reference.content) {
389
+ fs.outputFileSync(path.resolve(buildDir, reference.path), reference.content);
390
+ return `/// <reference path="${reference.path}" />`;
391
+ } else return "";
392
+ }).concat("export {}").join("\n");
393
+ code && fs.outputFileSync(codePath, code);
231
394
  }
232
395
  function genarateShim(options, vixt) {
233
- if (!options.shim)
234
- return;
235
- const { buildTypesDir } = vixt.options;
236
- const code = `
396
+ if (!options.shim) return;
397
+ const { buildTypesDir } = vixt.options;
398
+ const code = `
237
399
  declare module '*.vue' {
238
400
  import type { DefineComponent } from 'vue'
239
401
 
@@ -241,217 +403,241 @@ declare module '*.vue' {
241
403
  export default component
242
404
  }
243
405
  `;
244
- const codePath = path.resolve(buildTypesDir, "vue-shim.d.ts");
245
- fs.outputFileSync(codePath, code);
406
+ const codePath = path.resolve(buildTypesDir, "vue-shim.d.ts");
407
+ fs.outputFileSync(codePath, code);
246
408
  }
247
- function generateEnvDts(env, vixt) {
248
- const { buildTypesDir } = vixt.options;
249
- const codePath = path.resolve(buildTypesDir, "vite-env.d.ts");
250
- const values = Object.entries(env).map(([key, value]) => `/** ${key}=${value} */
251
- ${key}: ${typeof value}`).join("\n ");
252
- const code = `interface ImportMeta {
409
+ function generateEnvDts(env$1, vixt) {
410
+ const { buildTypesDir } = vixt.options;
411
+ const codePath = path.resolve(buildTypesDir, "vite-env.d.ts");
412
+ const code = `interface ImportMeta {
253
413
  readonly env: ImportMetaEnv
254
414
  }
255
415
  interface ImportMetaEnv {
256
- ${values}
416
+ ${Object.entries(env$1).map(([key, value]) => `/** ${key}=${value} */\n ${key}: ${typeof value}`).join("\n ")}
257
417
  }
258
418
  `;
259
- fs.outputFileSync(codePath, code);
419
+ fs.outputFileSync(codePath, code);
260
420
  }
261
- const name = "vixt:typescript";
262
- const typescript = defineVixtModule({
263
- meta: { name, configKey: "typescript" },
264
- defaults(vixt) {
265
- const { rootDir, srcDir } = vixt.options;
266
- const rootAlias = {};
267
- if (rootDir)
268
- rootAlias["@@/*"] = rootAlias["~~/*"] = [`${rootDir}/*`];
269
- const srcAlias = {};
270
- if (srcDir)
271
- srcAlias["@/*"] = srcAlias["~/*"] = [`${srcDir}/*`];
272
- const layersDirs = [];
273
- const layersAlias = {};
274
- for (const layer of vixt._layers) {
275
- layersDirs.push(layer.cwd);
276
- if (layer.meta?.alias)
277
- layersAlias[`${layer.meta.alias}/*`] = [`${layer.cwd}/*`];
278
- }
279
- return {
280
- tsConfig: {
281
- extends: "@vue/tsconfig/tsconfig.dom.json",
282
- compilerOptions: {
283
- baseUrl: rootDir,
284
- paths: { "#/*": ["./*"], ...layersAlias, ...rootAlias, ...srcAlias },
285
- types: ["vite/client"]
286
- },
287
- include: ["./**/*", ...layersDirs]
288
- },
289
- typeCheck: {
290
- enableBuild: false,
291
- overlay: { initialIsOpen: false }
292
- }
293
- };
294
- },
295
- setup(options, vixt) {
296
- return [
297
- {
298
- name,
299
- configResolved(config) {
300
- generateTsConfig(options, vixt);
301
- generateVixtDts(options, vixt);
302
- genarateShim(options, vixt);
303
- generateEnvDts(config.env, vixt);
304
- }
305
- },
306
- Checker(options.typeCheck ?? {})
307
- ];
308
- }
421
+ const name$4 = "vixt:typescript";
422
+ var typescript_default = defineVixtModule({
423
+ meta: {
424
+ name: name$4,
425
+ configKey: "typescript"
426
+ },
427
+ defaults(vixt) {
428
+ const { rootDir, alias } = vixt.options;
429
+ const paths = {};
430
+ for (const [ak, av] of Object.entries(alias ?? {})) {
431
+ const stats = fs.existsSync(av) ? fs.statSync(av) : null;
432
+ paths[ak] = [av];
433
+ if (stats?.isDirectory()) paths[`${ak}/*`] = [`${av}/*`];
434
+ }
435
+ const include = ["./**/*", ...vixt._layers.map((e) => e.cwd)];
436
+ return {
437
+ tsConfig: {
438
+ extends: "@vue/tsconfig/tsconfig.dom.json",
439
+ compilerOptions: {
440
+ baseUrl: rootDir,
441
+ paths,
442
+ types: ["vite/client"]
443
+ },
444
+ include
445
+ },
446
+ typeCheck: {
447
+ enableBuild: false,
448
+ overlay: { initialIsOpen: false }
449
+ }
450
+ };
451
+ },
452
+ setup(options, vixt) {
453
+ return [{
454
+ name: name$4,
455
+ configResolved(config) {
456
+ generateTsConfig(options, vixt);
457
+ generateVixtDts(options, vixt);
458
+ genarateShim(options, vixt);
459
+ generateEnvDts(config.env, vixt);
460
+ }
461
+ }, Checker(options.typeCheck ?? {})];
462
+ }
309
463
  });
310
464
 
311
- function generateAppConfig(vixt) {
312
- const { buildImportsDir } = vixt.options;
313
- let appConfigsImportTemplate = "";
314
- let appConfigsMergeTemplate = "";
315
- let i = 0;
316
- for (const layer of vixt._layers) {
317
- const appConfigPath = path.resolve(layer.config.srcDir, "app.config.ts");
318
- if (fs.existsSync(appConfigPath)) {
319
- const appConfigName = `__app_config_${i}`;
320
- appConfigsImportTemplate += `import ${appConfigName} from '${appConfigPath}'
321
- `;
322
- appConfigsMergeTemplate += `${appConfigName}, `;
323
- i++;
324
- }
325
- }
326
- const globalAppConfigKey = "__VIXT_APP_CONFIG";
327
- const appConfigTemplate = `
465
+ //#endregion
466
+ //#region src/node/modules/virtual-app-config.ts
467
+ const name$3 = "virtual:vixt:app-config";
468
+ const virtualModuleId$2 = name$3;
469
+ const resolvedVirtualModuleId$2 = `\0${virtualModuleId$2}`;
470
+ var virtual_app_config_default = defineVixtModule({
471
+ meta: { name: name$3 },
472
+ setup(_, vixt) {
473
+ let appConfigsImportTemplate = "";
474
+ let appConfigsMergeTemplate = "";
475
+ let i = 0;
476
+ for (const layer of vixt._layers) {
477
+ const appConfigPath = path.resolve(layer.config.srcDir, "app.config.ts");
478
+ if (fs.existsSync(appConfigPath)) {
479
+ const appConfigName = `__app_config_${i}`;
480
+ appConfigsImportTemplate += `import ${appConfigName} from '${appConfigPath}'\n`;
481
+ appConfigsMergeTemplate += `${appConfigName}, `;
482
+ i++;
483
+ }
484
+ }
485
+ const { baseURL = "/", rootId = "app" } = vixt.options.app ?? {};
486
+ return {
487
+ name: name$3,
488
+ resolveId(id) {
489
+ if (id === virtualModuleId$2) return resolvedVirtualModuleId$2;
490
+ },
491
+ load(id) {
492
+ if (id === resolvedVirtualModuleId$2) return `
328
493
  import { defu } from 'defu'
329
494
  ${appConfigsImportTemplate}
330
- const appConfig = defu(${appConfigsMergeTemplate}{})
331
- globalThis.${globalAppConfigKey} = appConfig
495
+ const appConfig = defu(${appConfigsMergeTemplate}{ baseURL: '${baseURL}', rootId: '${rootId}' })
496
+ export default appConfig
332
497
  `;
333
- fs.outputFileSync(path.resolve(buildImportsDir, `app.config.ts`), `// Generated by Vixt
334
- // @ts-nocheck
335
- import type { VixtAppConfig } from '@vixt/core/client'
336
-
337
- export const useAppConfig = () => globalThis.${globalAppConfigKey} as VixtAppConfig
338
- `);
339
- return appConfigTemplate;
340
- }
341
-
342
- function generateClient(vixt) {
343
- const { buildImportsDir } = vixt.options;
344
- fs.outputFileSync(
345
- path.resolve(buildImportsDir, `client.ts`),
346
- `// Generated by Vixt
347
- export { defineAppConfig, defineVixtPlugin } from '@vixt/core/client'
348
- `
349
- );
350
- }
351
-
352
- function generateCss(options) {
353
- const cssTemplate = options?.css?.map((css) => `import '${css}'`).join("\n") ?? "";
354
- return cssTemplate;
355
- }
498
+ }
499
+ };
500
+ }
501
+ });
356
502
 
357
- function resolveHeadTag(tag, attrs) {
358
- const attrsStr = Object.entries(attrs).filter(([k]) => k !== "children").map(([k, v]) => `${k}="${v}"`).join(" ");
359
- return attrs?.children ? `<${tag} ${attrsStr}>${attrs.children}</${tag}>` : `<${tag} ${attrsStr} />`;
360
- }
361
- function generateIndexHtml(options, vixt) {
362
- const { buildDir, rootDir, srcDir } = vixt.options;
363
- const indexHtmlPath = path.resolve(rootDir, "index.html");
364
- if (!fs.existsSync(indexHtmlPath))
365
- fs.outputFileSync(indexHtmlPath, `<!-- Generated by Vixt -->
366
- <!-- This file transform from '${path.basename(buildDir)}/index.html' -->
367
- `);
368
- const { head = {}, rootTag, rootId, entryFile } = options;
369
- const heads = Object.entries(head);
370
- const headTemplate = heads.filter(([k]) => k !== "noscript").map(([tag, attrs]) => attrs.map((e) => resolveHeadTag(tag, e)).reverse()).flat().join("\n");
371
- const noscriptTemplate = heads.filter(([k]) => k === "noscript").map(([tag, attrs]) => attrs.map((e) => resolveHeadTag(tag, e)).reverse()).flat().join("\n");
372
- let { loadingTemplate = "" } = options;
373
- if (!loadingTemplate) {
374
- for (const layer of vixt._layers) {
375
- const loadingTemplatePath = path.resolve(layer.cwd, "loading.html");
376
- if (fs.existsSync(loadingTemplatePath)) {
377
- loadingTemplate = fs.readFileSync(loadingTemplatePath, "utf-8");
378
- break;
379
- }
380
- }
381
- }
382
- const entryFilePath = /&\.|\//.test(entryFile ?? "") ? entryFile : `${srcDir.replace(rootDir, "")}/${entryFile}`;
383
- const code = `<!DOCTYPE html>
384
- <html>
385
- <head>
386
- ${headTemplate}
387
- </head>
388
- <body>
389
- <${rootTag} id="${rootId}">
390
- ${loadingTemplate}
391
- </${rootTag}>
392
- <script type="module" src="${entryFilePath}"><\/script>
393
- ${noscriptTemplate}
394
- </body>
395
- </html>
396
- `;
397
- fs.outputFileSync(path.resolve(buildDir, "index.html"), code);
398
- return code;
399
- }
503
+ //#endregion
504
+ //#region src/node/modules/virtual-css.ts
505
+ const name$2 = "virtual:vixt:css";
506
+ const virtualModuleId$1 = name$2;
507
+ const resolvedVirtualModuleId$1 = `\0${virtualModuleId$1}`;
508
+ var virtual_css_default = defineVixtModule({
509
+ meta: { name: name$2 },
510
+ setup(_, vixt) {
511
+ const cssTemplate = vixt.options.app?.css?.map((css) => `import '${css}'`).join("\n") ?? "";
512
+ return {
513
+ name: name$2,
514
+ resolveId(id) {
515
+ if (id === virtualModuleId$1) return resolvedVirtualModuleId$1;
516
+ },
517
+ load(id) {
518
+ if (id === resolvedVirtualModuleId$1) return cssTemplate;
519
+ }
520
+ };
521
+ }
522
+ });
400
523
 
401
- function generatePlugins(vixt) {
402
- const { plugins: pluginsDirs = [] } = resolveLayersDirs(vixt._layers);
403
- let pluginsImportTemplate = "";
404
- let pluginsMergeTemplate = "";
405
- let i = 0;
406
- for (const pluginsDir of pluginsDirs.reverse()) {
407
- const files = fs.existsSync(pluginsDir) ? fs.readdirSync(pluginsDir) : [];
408
- for (const f of files.filter((f2) => /[jt]sx?$/.test(f2))) {
409
- const p = path.resolve(pluginsDir, f);
410
- const pluginName = `__plugin_${i}`;
411
- pluginsImportTemplate += `import ${pluginName} from '${p}'
412
- `;
413
- pluginsMergeTemplate += `${pluginName}, `;
414
- i++;
415
- }
416
- }
417
- const pluginsTemplate = `
524
+ //#endregion
525
+ //#region src/node/modules/virtual-plugins.ts
526
+ const name$1 = "virtual:vixt:plugins";
527
+ const virtualModuleId = name$1;
528
+ const resolvedVirtualModuleId = `\0${virtualModuleId}`;
529
+ var virtual_plugins_default = defineVixtModule({
530
+ meta: { name: name$1 },
531
+ setup(_, vixt) {
532
+ const { plugins: pluginsDirs = [] } = resolveLayersDirs(vixt._layers);
533
+ let pluginsImportTemplate = "";
534
+ let pluginsMergeTemplate = "";
535
+ let i = 0;
536
+ for (const plugin of vixt.options.plugins ?? []) {
537
+ const pluginName = `__plugin_${i}`;
538
+ pluginsImportTemplate += `import ${pluginName} from '${plugin}'\n`;
539
+ pluginsMergeTemplate += `${pluginName}, `;
540
+ i++;
541
+ }
542
+ for (const pluginsDir of pluginsDirs.reverse()) {
543
+ const files = fs.existsSync(pluginsDir) ? fs.readdirSync(pluginsDir) : [];
544
+ for (const f of files.filter((f$1) => /[jt]sx?$/.test(f$1))) {
545
+ const p = path.resolve(pluginsDir, f);
546
+ const pluginName = `__plugin_${i}`;
547
+ pluginsImportTemplate += `import ${pluginName} from '${p}'\n`;
548
+ pluginsMergeTemplate += `${pluginName}, `;
549
+ i++;
550
+ }
551
+ }
552
+ return {
553
+ name: name$1,
554
+ resolveId(id) {
555
+ if (id === virtualModuleId) return resolvedVirtualModuleId;
556
+ },
557
+ load(id) {
558
+ if (id === resolvedVirtualModuleId) return `
418
559
  ${pluginsImportTemplate}
419
560
  const plugins = [${pluginsMergeTemplate}]
420
- function usePlugins(options) {
421
- for (const plugin of plugins) {
422
- typeof plugin === 'function' && plugin(options)
423
- }
424
- }
561
+ export default plugins
425
562
  `;
426
- return pluginsTemplate;
427
- }
563
+ }
564
+ };
565
+ }
566
+ });
567
+
568
+ //#endregion
569
+ //#region src/node/modules/vite.ts
570
+ const name = "vixt:vite";
571
+ var vite_default = defineVixtModule({
572
+ meta: { name },
573
+ setup(_, vixt) {
574
+ let env$1;
575
+ return {
576
+ name,
577
+ enforce: "pre",
578
+ config(config) {
579
+ const { rootDir, app } = vixt.options;
580
+ env$1 = loadEnv(config.mode, config.envDir, config.envPrefix);
581
+ const defineEnv = Object.fromEntries(Object.entries(env$1).filter(([k]) => ![
582
+ "MODE",
583
+ "DEV",
584
+ "PROD"
585
+ ].includes(k)).map(([k, v]) => [`import.meta.env.${k}`, JSON.stringify(v)]));
586
+ return mergeConfig(vixt.options.vite ?? {}, {
587
+ root: rootDir,
588
+ base: app?.baseURL,
589
+ define: defineEnv
590
+ });
591
+ }
592
+ };
593
+ }
594
+ });
595
+
596
+ //#endregion
597
+ //#region src/node/modules/index.ts
598
+ const virtualModuleIds = {
599
+ css: virtual_css_default.getMeta().name,
600
+ appConfig: virtual_app_config_default.getMeta().name,
601
+ plugins: virtual_plugins_default.getMeta().name
602
+ };
603
+ const builtinModules = [
604
+ vite_default,
605
+ alias_default,
606
+ app_default,
607
+ build_default,
608
+ dev_server_default,
609
+ typescript_default,
610
+ virtual_app_config_default,
611
+ virtual_css_default,
612
+ virtual_plugins_default
613
+ ];
428
614
 
615
+ //#endregion
616
+ //#region src/node/vixt.ts
429
617
  async function loadVixt(opts) {
430
- const result = await loadVixtConfig(defu(opts, {
431
- defaults: {
432
- modules: [config, typescript]
433
- }
434
- }));
435
- const parsedArgv = cac().parse();
436
- const isForce = !!parsedArgv.options.force;
437
- if (isForce) {
438
- fs.removeSync(result.config.buildDir);
439
- }
440
- result.layers = applyLayers(result.layers ?? [], result.config);
441
- const layerModules = await applyLayerModules(result.layers ?? []);
442
- const vixt = {
443
- options: result.config,
444
- _layers: result.layers ?? [],
445
- _modules: [...result.config.modules ?? [], ...layerModules]
446
- };
447
- return vixt;
618
+ const result = await loadVixtConfig(opts);
619
+ const cliOptions = loadCLIOptions();
620
+ cliOptions.force && fs.removeSync(result.config.buildDir);
621
+ result.config.debug = !!cliOptions.debug;
622
+ result.config.dev = env.NODE_ENV !== "production";
623
+ result.layers = applyLayers(result.layers ?? [], result.config);
624
+ const layerModules = await applyLayerModules(result.layers ?? []);
625
+ return {
626
+ options: result.config,
627
+ _layers: result.layers ?? [],
628
+ _modules: [
629
+ ...builtinModules,
630
+ ...result.config.modules ?? [],
631
+ ...layerModules
632
+ ]
633
+ };
448
634
  }
449
635
  function createVixtPlugin(loadOptions) {
450
- return defineVitePlugin(async (vixtOptions) => {
451
- const vixt = await loadVixt(defu({ defaults: vixtOptions }, loadOptions));
452
- const plugins = vixt._modules.map((module) => module({}, vixt));
453
- return plugins;
454
- });
636
+ return defineVitePlugin(async (vixtOptions) => {
637
+ const vixt = await loadVixt(defu({ defaults: vixtOptions }, loadOptions));
638
+ return vixt._modules.map((module) => installModule(module, {}, vixt));
639
+ });
455
640
  }
456
641
 
457
- export { applyLayerModules, applyLayers, config, createVixtPlugin, defineVitePlugin, defineVixtConfig, defineVixtModule, findUpWorkspaceDir, generateAppConfig, generateClient, generateCss, generateIndexHtml, generatePlugins, installModule, isSamePath, loadEnv, loadVixt, loadVixtConfig, loadWorkspaceEnv, resolveLayersDirs, typescript };
642
+ //#endregion
643
+ export { VixtClientAutoImports, applyLayerModules, applyLayers, builtinModules, createVixtPlugin, defineVitePlugin, defineVixtConfig, defineVixtModule, findUpWorkspaceDir, installModule, isSamePath, loadCLIOptions, loadEnv, loadMode, loadVixt, loadVixtConfig, loadWorkspaceEnv, resolveLayersDirs, virtualModuleIds };