@univa/core 0.0.6 → 0.0.8

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.js CHANGED
@@ -1,336 +1,496 @@
1
+ // src/config/index.ts
2
+ function defineConfig(config) {
3
+ return config;
4
+ }
5
+
1
6
  // src/plugins/index.ts
2
7
  import Uni from "@uni-helper/plugin-uni";
3
- import UniHelperLayouts from "@uni-helper/vite-plugin-uni-layouts";
4
- import UniOptimization from "@uni-ku/bundle-optimizer";
5
- import UnivaRoot from "@univa/root";
6
- import UniPolyfill from "vite-plugin-uni-polyfill";
8
+ import VitePluginUniComponents from "@uni-helper/vite-plugin-uni-components";
9
+ import { VitePluginUniLayouts } from "@uni-helper/vite-plugin-uni-layouts";
10
+ import UniKuRoot from "@uni-ku/root";
11
+ import UnoCSS from "unocss/vite";
12
+ import AutoImport from "unplugin-auto-import/vite";
7
13
 
8
14
  // src/constant.ts
9
- var DTS_DIR = "./.univa";
10
- var COMPONENT_ASYNC_ROOT = "components-async";
15
+ var ID = "univa";
16
+ var UNIVA_DIR_NAME = `.${ID}`;
17
+ var ROOT_NAME = `${ID}.root`;
11
18
 
12
- // src/plugins/autoImport.ts
13
- import AutoImport from "unplugin-auto-import/vite";
14
- function createAutoImportPlugin(options) {
15
- const defaultAutoImportOptions = {
16
- imports: [
17
- "vue",
18
- "pinia",
19
- "uni-app",
20
- {
21
- from: "@univa/core/hooks",
22
- imports: ["usePageContext"]
23
- }
24
- ],
25
- dirs: [
26
- "src/hooks/**",
27
- "!src/hooks/**/_*/**",
28
- "src/store/**",
29
- "!src/store/**/_*/**",
30
- "src/constants/**"
31
- ],
32
- vueTemplate: true,
33
- dts: `${DTS_DIR}/auto-imports.d.ts`
34
- };
35
- const userAutoImportOptions = typeof options.autoImport === "object" ? options.autoImport : {};
36
- const mergedOptions = {
37
- ...defaultAutoImportOptions,
38
- ...userAutoImportOptions
39
- };
40
- if (userAutoImportOptions.imports) {
41
- const userImports = Array.isArray(userAutoImportOptions.imports) ? userAutoImportOptions.imports : [userAutoImportOptions.imports];
42
- mergedOptions.imports = [...defaultAutoImportOptions.imports, ...userImports];
19
+ // src/utils/fs.ts
20
+ import { existsSync, mkdirSync } from "fs";
21
+ import { join } from "path";
22
+ function ensureDir(dir) {
23
+ if (!existsSync(dir)) {
24
+ mkdirSync(dir, { recursive: true });
43
25
  }
44
- if (userAutoImportOptions.dirs) {
45
- const userDirs = Array.isArray(userAutoImportOptions.dirs) ? userAutoImportOptions.dirs : [userAutoImportOptions.dirs];
46
- mergedOptions.dirs = [...defaultAutoImportOptions.dirs, ...userDirs];
26
+ }
27
+ function getUnivaDir(cwd) {
28
+ return join(cwd, UNIVA_DIR_NAME);
29
+ }
30
+ function ensureUnivaDir(cwd) {
31
+ const dir = getUnivaDir(cwd);
32
+ ensureDir(dir);
33
+ return dir;
34
+ }
35
+
36
+ // src/utils/logger.ts
37
+ var debugMode = false;
38
+ function setDebug(enabled) {
39
+ debugMode = enabled;
40
+ }
41
+ function log(message, ...args) {
42
+ if (debugMode) {
43
+ console.log(`[${ID}]`, message, ...args);
47
44
  }
48
- return AutoImport(mergedOptions);
49
45
  }
50
46
 
51
- // src/plugins/components.ts
52
- import UniHelperComponents from "@uni-helper/vite-plugin-uni-components";
53
- function createComponentsPlugin(options) {
54
- const defaultComponentsOptions = {
55
- dirs: ["src/components", "src/components-biz"],
56
- exclude: ["**/components/**/*.*"],
57
- directoryAsNamespace: true,
58
- globalNamespaces: ["components", "common"],
59
- dts: `${DTS_DIR}/components.d.ts`
60
- };
61
- const userComponentsOptions = typeof options.components === "object" ? options.components : {};
62
- const mergedOptions = {
63
- ...defaultComponentsOptions,
64
- ...userComponentsOptions
47
+ // src/plugins/context.ts
48
+ import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
49
+ import { join as join4 } from "path";
50
+ import { slash } from "@antfu/utils";
51
+ import { loadConfig } from "c12";
52
+ import { createJiti } from "jiti";
53
+
54
+ // src/utils/merge.ts
55
+ import { createDefu } from "defu";
56
+ var mergeWithArrayOverride = createDefu((originObj, key, updates) => {
57
+ if (Array.isArray(originObj[key]) && Array.isArray(updates)) {
58
+ originObj[key] = updates;
59
+ return true;
60
+ }
61
+ });
62
+
63
+ // src/plugins/manifest.ts
64
+ import { existsSync as existsSync2, readFileSync, writeFileSync } from "fs";
65
+ import { join as join2, resolve } from "path";
66
+ import process2 from "process";
67
+ import { ensureManifestJsonExists } from "@uni-helper/vite-plugin-uni-manifest";
68
+ import { watchConfig } from "c12";
69
+ import { normalizePath } from "vite";
70
+ function resolveOptions(userOptions) {
71
+ return {
72
+ minify: false,
73
+ insertFinalNewline: false,
74
+ cwd: process2.env.VITE_ROOT_DIR,
75
+ merge: true,
76
+ ...userOptions
65
77
  };
66
- if (userComponentsOptions.dirs) {
67
- const userDirs = Array.isArray(userComponentsOptions.dirs) ? userComponentsOptions.dirs : [userComponentsOptions.dirs];
68
- mergedOptions.dirs = [...defaultComponentsOptions.dirs, ...userDirs];
78
+ }
79
+ function writeManifestJson(config = {}, opts) {
80
+ const path = resolveManifestJsonPath();
81
+ let mergeContent = {};
82
+ if (opts?.merge && existsSync2(path)) {
83
+ try {
84
+ const content2 = readFileSync(path, "utf-8");
85
+ mergeContent = JSON.parse(content2);
86
+ } catch (error) {
87
+ log(`manifest.json parse error: ${error}`);
88
+ }
89
+ }
90
+ const content = JSON.stringify(opts?.merge ? mergeWithArrayOverride(config, mergeContent) : config, null, opts?.minify ? 0 : 2) + (opts?.insertFinalNewline ? "\n" : "");
91
+ if (existsSync2(path) && readFileSync(path, "utf-8") === content) {
92
+ return;
69
93
  }
70
- if (userComponentsOptions.exclude) {
71
- const userExclude = Array.isArray(userComponentsOptions.exclude) ? userComponentsOptions.exclude : [userComponentsOptions.exclude];
72
- mergedOptions.exclude = [...defaultComponentsOptions.exclude, ...userExclude];
94
+ writeFileSync(path, content);
95
+ }
96
+ function resolveManifestJsonPath() {
97
+ return normalizePath(
98
+ resolve(process2.env.UNI_INPUT_DIR || `${process2.cwd()}/src`, "manifest.json")
99
+ );
100
+ }
101
+ var ManifestContext = class {
102
+ options;
103
+ unwatch;
104
+ constructor(options) {
105
+ this.options = resolveOptions(options);
106
+ }
107
+ /**
108
+ * Start watching config sources and perform initial write.
109
+ * Must be called after construction.
110
+ */
111
+ async setup() {
112
+ log(`manifest cwd: ${this.options.cwd}`);
113
+ const { config, unwatch } = await watchConfig({
114
+ cwd: this.options.cwd,
115
+ name: "manifest",
116
+ rcFile: false,
117
+ packageJson: false,
118
+ onUpdate: (config2) => {
119
+ writeManifestJson(config2.newConfig.config, this.options);
120
+ }
121
+ });
122
+ writeManifestJson(config, this.options);
123
+ this.unwatch = unwatch;
73
124
  }
74
- if (userComponentsOptions.globalNamespaces) {
75
- const userGlobalNamespaces = Array.isArray(userComponentsOptions.globalNamespaces) ? userComponentsOptions.globalNamespaces : [userComponentsOptions.globalNamespaces];
76
- mergedOptions.globalNamespaces = [...defaultComponentsOptions.globalNamespaces, ...userGlobalNamespaces];
125
+ };
126
+ function VitePluginUniManifest(userOptions = {}) {
127
+ let ctx;
128
+ return {
129
+ name: "vite-plugin-uni-manifest",
130
+ // Run before other plugins to ensure manifest.json is ready
131
+ enforce: "pre",
132
+ async configResolved() {
133
+ ensureManifestJsonExists();
134
+ ctx = new ManifestContext(userOptions);
135
+ await ctx.setup();
136
+ },
137
+ buildEnd: () => ctx?.unwatch()
138
+ };
139
+ }
140
+ function generateManifestConfigContent(content = {}) {
141
+ return `// Auto-generated by @univa/core
142
+ export default ${JSON.stringify(content, null, 2)}
143
+ `;
144
+ }
145
+ function generateManifestConfigFile(content = {}, root) {
146
+ const configPath = getManifestConfigPath(root);
147
+ const newContent = generateManifestConfigContent(content);
148
+ if (existsSync2(configPath)) {
149
+ const existingContent = readFileSync(configPath, "utf-8");
150
+ if (existingContent === newContent) {
151
+ return;
152
+ }
77
153
  }
78
- return UniHelperComponents(mergedOptions);
154
+ writeFileSync(configPath, newContent, "utf-8");
79
155
  }
80
-
81
- // src/plugins/manifest.ts
82
- import { VitePluginUniManifest } from "@univa/manifest";
83
- function createManifestPlugin(options) {
156
+ function getManifestConfigPath(root) {
157
+ return join2(getUnivaDir(root), "manifest.config.ts");
158
+ }
159
+ function createManifestPlugin(userOptions = {}) {
84
160
  return VitePluginUniManifest({
85
- rewrite: (config) => {
86
- return options?.manifest || config;
87
- }
161
+ cwd: join2(process2.env.VITE_ROOT_DIR || "", UNIVA_DIR_NAME),
162
+ ...userOptions
88
163
  });
89
164
  }
90
165
 
91
166
  // src/plugins/pages.ts
92
- import UniHelperPages from "@uni-helper/vite-plugin-uni-pages";
93
- function _pathToName(path, partToReplace = "", prefix = "") {
94
- const parts = path.replace(/\.\w+$/, "").split("/").filter(Boolean);
95
- const toPascalCase = (parts2) => {
96
- return parts2.map(
97
- (part) => part.split("-").map((subPart) => subPart.charAt(0).toUpperCase() + subPart.slice(1)).join("")
98
- ).join("");
99
- };
100
- if (!partToReplace) {
101
- return toPascalCase(parts);
102
- }
103
- const indexToReplace = parts.findIndex((part) => part.toLowerCase() === partToReplace.toLowerCase());
104
- if (indexToReplace === -1) {
105
- return prefix + toPascalCase(parts);
106
- }
107
- parts[indexToReplace] = prefix;
108
- return toPascalCase(parts);
167
+ import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
168
+ import { join as join3 } from "path";
169
+ import { VitePluginUniPages } from "@uni-helper/vite-plugin-uni-pages";
170
+ function getPagesConfigPath(root) {
171
+ return join3(getUnivaDir(root), "pages-config.ts");
109
172
  }
110
- function processPageName(ctx) {
111
- ctx.pageMetaData.forEach((page) => {
112
- if (page.name) {
173
+ function generatePagesConfigContent(content) {
174
+ const { pages, subPackages, ...rest } = content;
175
+ void pages;
176
+ void subPackages;
177
+ return `// Auto-generated by @univa/core
178
+ // \u6765\u6E90\uFF1Auniva.config.ts \u7684 pages \u5B57\u6BB5
179
+ export default ${JSON.stringify(rest, null, 2)}
180
+ `;
181
+ }
182
+ function generatePagesConfigFile(content, root) {
183
+ const pagesConfigPath = getPagesConfigPath(root);
184
+ const newContent = generatePagesConfigContent(content);
185
+ if (existsSync3(pagesConfigPath)) {
186
+ const existingContent = readFileSync2(pagesConfigPath, "utf-8");
187
+ if (existingContent === newContent) {
113
188
  return;
114
189
  }
115
- page.name = _pathToName(page.path, "pages");
116
- });
117
- ctx.subPageMetaData.forEach((subPackage) => {
118
- const root = subPackage.root;
119
- const isAsyncComponent = root.startsWith(COMPONENT_ASYNC_ROOT);
120
- subPackage.pages.forEach((page) => {
121
- if (page.name) {
122
- return;
123
- }
124
- if (!page.path) {
125
- console.warn(`[vite-plugin-uni-pages] Page path is missing in subPackage: ${root}`);
126
- return;
127
- }
128
- if (isAsyncComponent) {
129
- page.layout = false;
130
- }
131
- page.name = _pathToName(`${root}/${page.path}`, "pages-sub", "Sub");
132
- });
190
+ }
191
+ writeFileSync2(pagesConfigPath, newContent, "utf-8");
192
+ }
193
+ function createPagesPlugin(pluginOptions) {
194
+ const result = VitePluginUniPages({
195
+ dts: `${UNIVA_DIR_NAME}/uni-pages.d.ts`,
196
+ exclude: ["**/components/**/*.*"],
197
+ configSource: `${UNIVA_DIR_NAME}/pages-config.ts`,
198
+ ...pluginOptions
133
199
  });
200
+ return Array.isArray(result) ? result : [result];
134
201
  }
135
- function processTabBar(ctx) {
136
- const tabBar = ctx.pagesGlobConfig?.tabBar;
137
- if (!tabBar) {
138
- return;
202
+
203
+ // src/plugins/context.ts
204
+ var APP_KU_VUE_TEMPLATE = `<!-- Auto-generated by @univa/core -->
205
+ <template>
206
+ <KuRootView />
207
+ </template>
208
+ `;
209
+ var UnivaContext = class {
210
+ _server;
211
+ config;
212
+ configPath;
213
+ root;
214
+ constructor(options) {
215
+ this.root = options.root;
139
216
  }
140
- const tabBarMode = ctx.pagesGlobConfig?.tabBarMode || "NATIVE";
141
- if (tabBarMode === "CUSTOM") {
142
- tabBar.custom = true;
217
+ /**
218
+ * 确保虚拟根组件文件存在
219
+ *
220
+ * UniKuRoot 插件依赖 src 下的虚拟根组件文件(默认 App.ku.vue)。
221
+ * 若不存在则生成最小模板,避免插件注入 import 时解析失败。
222
+ *
223
+ * 必须在 Vite 启动前调用(Univa() 初始化阶段),
224
+ * 否则在 configResolved 阶段创建 src 下新文件会触发 watcher add 事件,
225
+ * 导致 Vite 重编译与 VitePluginUniPages 的 pages.json 写入冲突(EPERM)。
226
+ */
227
+ ensureRootComponent(fileName) {
228
+ const srcDir = this.config?.srcDir || "src";
229
+ const rootFileName = this.config?.overrides?.root?.rootFileName || fileName;
230
+ const rootComponentPath = join4(this.root, srcDir, rootFileName);
231
+ if (existsSync4(rootComponentPath)) {
232
+ return;
233
+ }
234
+ writeFileSync3(rootComponentPath, APP_KU_VUE_TEMPLATE, "utf-8");
235
+ log(`\u5DF2\u751F\u6210\u865A\u62DF\u6839\u7EC4\u4EF6\uFF1A${slash(rootComponentPath)}`);
143
236
  }
144
- const rawTabBarList = [];
145
- if (tabBar.list && tabBar.list.length > 0) {
146
- tabBar.list = tabBar.list.map((item) => {
147
- rawTabBarList.push({ ...item });
148
- const filtered = { ...item };
149
- if (!filtered.iconPath?.startsWith("static/")) {
150
- delete filtered.iconPath;
151
- }
152
- if (!filtered.selectedIconPath?.startsWith("static/")) {
153
- delete filtered.selectedIconPath;
154
- }
155
- return filtered;
156
- });
237
+ /**
238
+ * 同步加载用户配置(univa.config.ts)
239
+ */
240
+ loadUserConfigSync() {
241
+ const jiti = createJiti(this.root);
242
+ const configFile = join4(this.root, `${ID}.config`);
243
+ try {
244
+ const configModule = jiti(configFile);
245
+ const userConfig = configModule?.default || configModule;
246
+ this.config = mergeWithArrayOverride({}, userConfig);
247
+ this.configPath = jiti.resolve(configFile);
248
+ } catch {
249
+ }
157
250
  }
158
- const clonedTabBar = { ...tabBar };
159
- if (clonedTabBar.list) {
160
- clonedTabBar.list = rawTabBarList;
251
+ /**
252
+ * 异步加载用户配置(c12 支持更多格式与合并能力)
253
+ */
254
+ async loadUserConfigAsync() {
255
+ const { config: userConfig, configFile } = await loadConfig({
256
+ name: ID,
257
+ cwd: this.root,
258
+ defaults: this.config || {},
259
+ merger: mergeWithArrayOverride
260
+ });
261
+ this.config = userConfig;
262
+ this.configPath = configFile || "";
161
263
  }
162
- return clonedTabBar;
163
- }
164
- function resolveUserPagesConfig(config) {
165
- if (!config.tabBar) {
166
- return config;
264
+ /**
265
+ * 设置 Vite 开发服务器
266
+ */
267
+ setupViteServer(server) {
268
+ if (this._server === server)
269
+ return;
270
+ this._server = server;
271
+ this.setupWatcher(server.watcher);
167
272
  }
168
- return config;
169
- }
170
- function createPagesPlugin(options) {
171
- const pages = options.pages || {};
172
- const MODULE_ID_VIRTUAL = "virtual:univa-pages";
173
- const RESOLVED_MODULE_ID_VIRTUAL = `\0${MODULE_ID_VIRTUAL}`;
174
- const virtualData = {
175
- pages: [],
176
- subPackages: [],
177
- tabBar: null
178
- };
179
- const virtualModule = () => {
180
- const pages2 = `export const pages = ${virtualData.pages};`;
181
- const subPackages = `export const subPackages = ${virtualData.subPackages};`;
182
- const tabBar = `export const tabBar = ${JSON.stringify(virtualData.tabBar)};`;
183
- return [pages2, subPackages, tabBar].join("\n");
184
- };
185
- const tabbarPlugin = {
186
- name: "vite-plugin-univa-pages",
187
- enforce: "pre",
188
- resolveId(id) {
189
- if (id === MODULE_ID_VIRTUAL) {
190
- return RESOLVED_MODULE_ID_VIRTUAL;
273
+ /**
274
+ * 设置文件监听器
275
+ *
276
+ * 监听 univa.config.ts 变化,重新生成 .univa/pages.ts
277
+ */
278
+ setupWatcher(watcher) {
279
+ if (!this.configPath) {
280
+ return;
281
+ }
282
+ watcher.add(this.configPath);
283
+ watcher.on("change", async (filePath) => {
284
+ filePath = slash(filePath);
285
+ const configPath = slash(this.configPath || "");
286
+ if (filePath !== configPath) {
287
+ return;
191
288
  }
192
- },
193
- load(id) {
194
- if (id === RESOLVED_MODULE_ID_VIRTUAL) {
195
- return virtualModule();
289
+ await this.updateConfig();
290
+ this.onUpdate();
291
+ });
292
+ }
293
+ async updateConfig() {
294
+ await this.loadUserConfigAsync();
295
+ this.updateGeneratedFiles();
296
+ }
297
+ /**
298
+ * 更新生成的文件
299
+ *
300
+ * 读取 univa.config.ts 的 pages 字段(应用级配置),
301
+ * 生成 .univa/pages-config.ts 供 VitePluginUniPages 消费。
302
+ *
303
+ * 注意:不在此处生成 src/App.ku.vue,避免在 configResolved 阶段
304
+ * 创建 src 下新文件触发 watcher add 事件,导致 Vite 重编译
305
+ * 与 VitePluginUniPages 的 pages.json 写入冲突(EPERM)。
306
+ * App.ku.vue 的生成在 Univa() 初始化阶段完成。
307
+ */
308
+ updateGeneratedFiles() {
309
+ const pagesConfig = this.config?.pages;
310
+ if (pagesConfig) {
311
+ generatePagesConfigFile(pagesConfig, this.root);
312
+ }
313
+ const manifestConfig = this.config?.manifest;
314
+ if (manifestConfig) {
315
+ generateManifestConfigFile(manifestConfig, this.root);
316
+ }
317
+ const pagesTsPath = getPagesConfigPath(this.root);
318
+ const emptyContent = `// Auto-generated by @univa/core
319
+ export default {}
320
+ `;
321
+ if (!existsSync4(pagesTsPath)) {
322
+ writeFileSync3(pagesTsPath, emptyContent, "utf-8");
323
+ } else if (!pagesConfig) {
324
+ if (readFileSync3(pagesTsPath, "utf-8") !== emptyContent) {
325
+ writeFileSync3(pagesTsPath, emptyContent, "utf-8");
196
326
  }
197
327
  }
198
- };
199
- return [
200
- tabbarPlugin,
201
- UniHelperPages({
202
- configSource: pages.config ? {
203
- files: "vite.config",
204
- rewrite: () => resolveUserPagesConfig(pages.config)
205
- } : {
206
- files: "pages.config"
207
- },
208
- subPackages: [
209
- ...pages.subPackages || []
210
- ],
211
- exclude: [
212
- ...pages?.exclude || [],
213
- "**/components/**/*.*"
214
- ],
215
- onAfterMergePageMetaData(ctx) {
216
- processPageName(ctx);
217
- virtualData.tabBar = processTabBar(ctx);
218
- },
219
- onAfterWriteFile(ctx) {
220
- virtualData.pages = ctx.resolveRoutes();
221
- virtualData.subPackages = ctx.resolveSubRoutes();
222
- },
223
- dts: `${DTS_DIR}/pages.d.ts`
224
- })
225
- ];
226
- }
227
- function definePagesConfig(config) {
228
- return config;
229
- }
328
+ }
329
+ /**
330
+ * 更新回调
331
+ * 触发 HMR
332
+ */
333
+ onUpdate() {
334
+ if (!this._server) {
335
+ return;
336
+ }
337
+ this._server.ws.send({
338
+ type: "full-reload"
339
+ });
340
+ }
341
+ };
230
342
 
231
- // src/plugins/unocss.ts
232
- import { presetUni } from "@uni-helper/unocss-preset-uni";
233
- import presetLegacyCompat from "@unocss/preset-legacy-compat";
234
- import { presetIcons, transformerDirectives, transformerVariantGroup } from "unocss";
235
- import UnoCSS from "unocss/vite";
236
- function createUnocssPlugin() {
237
- return UnoCSS({
238
- presets: [
239
- presetUniva()
240
- ]
241
- });
242
- }
243
- function presetUniva() {
343
+ // src/plugins/options.ts
344
+ var DEFAULT_DIRS = {
345
+ pages: "pages",
346
+ subPackages: ["pages-sub/*"],
347
+ layouts: "layouts"
348
+ };
349
+ var DEFAULT_IMPORTS = {
350
+ apis: ["vue", "uni-app", "composables/**", "stores/**", "hooks/**", "constants/**"],
351
+ components: ["components/**", "components-biz/**"]
352
+ };
353
+ function resolveOptions2(userOptions) {
354
+ const srcDir = userOptions.srcDir || "src";
355
+ const dirs = {
356
+ pages: userOptions.dirs?.pages ?? DEFAULT_DIRS.pages,
357
+ subPackages: userOptions.dirs?.subPackages ?? DEFAULT_DIRS.subPackages,
358
+ layouts: userOptions.dirs?.layouts ?? DEFAULT_DIRS.layouts
359
+ };
360
+ const imports = {
361
+ apis: userOptions.imports?.apis ?? DEFAULT_IMPORTS.apis,
362
+ components: userOptions.imports?.components ?? DEFAULT_IMPORTS.components
363
+ };
244
364
  return {
245
- name: "univa-preset",
246
- presets: [
247
- presetUni({
248
- attributify: false
249
- }),
250
- presetIcons({
251
- scale: 1.2,
252
- warn: true,
253
- extraProperties: {
254
- "display": "inline-block",
255
- "vertical-align": "middle"
256
- }
257
- }),
258
- // 处理低端安卓机的样式问题,eg: `rgb(255 0 0)` -> `rgb(255, 0, 0)`
259
- presetLegacyCompat({
260
- commaStyleColorFunction: true,
261
- legacyColorSpace: true
262
- })
263
- ],
264
- shortcuts: [
265
- ["border-s", "border border-solid"],
266
- ["wh-full", "w-full h-full"],
267
- ["f-c-c", "flex justify-center items-center"],
268
- ["f-col-c", "flex-col justify-center items-center"],
269
- ["flex-items", "flex items-center"],
270
- ["flex-justify", "flex justify-center"],
271
- ["flex-col", "flex flex-col"]
272
- ],
273
- transformers: [
274
- transformerDirectives(),
275
- transformerVariantGroup()
276
- ],
277
- rules: [
278
- [
279
- "p-safe",
280
- {
281
- padding: "env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)"
282
- }
283
- ],
284
- ["pt-safe", { "padding-top": "env(safe-area-inset-top)" }],
285
- ["pb-safe", { "padding-bottom": "env(safe-area-inset-bottom)" }]
286
- ]
365
+ srcDir,
366
+ dirs,
367
+ imports,
368
+ overrides: userOptions.overrides
287
369
  };
288
370
  }
289
371
 
290
372
  // src/plugins/index.ts
291
- function createUnivaPlugins(options) {
292
- const pluginFactory = {
293
- plugins: [
294
- ...createPagesPlugin(options),
295
- UniHelperLayouts()
296
- ],
297
- register(condition, plugin) {
298
- if (condition) {
299
- this.plugins.push(plugin);
300
- }
373
+ var context;
374
+ function createCorePlugin() {
375
+ return {
376
+ name: "vite-plugin-univa",
377
+ enforce: "pre",
378
+ async configResolved() {
379
+ await context.loadUserConfigAsync();
380
+ context.updateGeneratedFiles();
381
+ },
382
+ configureServer(server) {
383
+ context.setupViteServer(server);
301
384
  }
302
385
  };
303
- pluginFactory.register(options.appRoot !== false, UnivaRoot({
386
+ }
387
+ function isPresetName(from) {
388
+ if (/[*?[\]{}]/.test(from))
389
+ return false;
390
+ if (/^@[\w.-]+\/[\w.-]+$/.test(from))
391
+ return true;
392
+ if (/[/\\]/.test(from))
393
+ return false;
394
+ return true;
395
+ }
396
+ function resolveApiSources(sources, srcDir) {
397
+ const presets = [];
398
+ const dirs = [];
399
+ for (const source of sources) {
400
+ if (typeof source !== "string") {
401
+ presets.push(source);
402
+ } else if (source.startsWith("!")) {
403
+ dirs.push(`!${srcDir}/${source.slice(1)}`);
404
+ } else if (isPresetName(source)) {
405
+ presets.push(source);
406
+ } else {
407
+ dirs.push(`${srcDir}/${source}`);
408
+ }
409
+ }
410
+ return { presets, dirs };
411
+ }
412
+ function createUnivaPlugins(resolved) {
413
+ const plugins = [];
414
+ const { srcDir } = resolved;
415
+ plugins.push(createCorePlugin());
416
+ plugins.push(...createPagesPlugin({
417
+ dir: `${srcDir}/${resolved.dirs.pages}`,
418
+ subPackages: resolved.dirs.subPackages.map((p) => `${srcDir}/${p}`),
419
+ ...resolved.overrides?.pages
420
+ }));
421
+ plugins.push(VitePluginUniLayouts({
422
+ layoutDir: `${srcDir}/${resolved.dirs.layouts}`,
423
+ ...resolved.overrides?.layouts
424
+ }));
425
+ plugins.push(UniKuRoot({
304
426
  enabledVirtualHost: true,
305
- rootFileName: "App.univa",
306
427
  enabledGlobalRef: true,
307
- autoCreateRoot: true,
428
+ rootFileName: ROOT_NAME,
308
429
  excludePages: [
309
- `${COMPONENT_ASYNC_ROOT}/**/*.*`
310
- ]
430
+ "components-async/**/*.*"
431
+ ],
432
+ ...resolved.overrides?.root
433
+ }));
434
+ plugins.push(VitePluginUniComponents({
435
+ dirs: resolved.imports.components.map((c) => `${srcDir}/${c}`),
436
+ dts: `${UNIVA_DIR_NAME}/components.d.ts`,
437
+ globalNamespaces: ["components", "common"],
438
+ directoryAsNamespace: true,
439
+ ...resolved.overrides?.components
311
440
  }));
312
- pluginFactory.register(true, createManifestPlugin(options));
313
- pluginFactory.register(options.components !== false, createComponentsPlugin(options));
314
- pluginFactory.register(true, UniOptimization());
315
- pluginFactory.register(true, Uni());
316
- pluginFactory.register(true, createUnocssPlugin());
317
- pluginFactory.register(options.autoImport !== false, createAutoImportPlugin(options));
318
- pluginFactory.register(true, UniPolyfill());
319
- return pluginFactory.plugins;
441
+ plugins.push(createManifestPlugin({
442
+ ...resolved.overrides?.manifest
443
+ }));
444
+ plugins.push(...Uni());
445
+ plugins.push(...UnoCSS());
446
+ const { presets, dirs } = resolveApiSources(resolved.imports.apis, srcDir);
447
+ const autoImportPlugin = AutoImport({
448
+ imports: presets,
449
+ dirs,
450
+ dts: `${UNIVA_DIR_NAME}/auto-imports.d.ts`,
451
+ ...resolved.overrides?.autoImport
452
+ });
453
+ if (Array.isArray(autoImportPlugin)) {
454
+ plugins.push(...autoImportPlugin);
455
+ } else {
456
+ plugins.push(autoImportPlugin);
457
+ }
458
+ return plugins;
320
459
  }
321
-
322
- // src/index.ts
323
- function Univa(config) {
324
- return createUnivaPlugins({
325
- components: config?.components ?? true,
326
- autoImport: config?.autoImport ?? true,
327
- appRoot: config?.appRoot ?? true,
328
- pages: config?.pages,
329
- manifest: config?.manifest
460
+ function Univa() {
461
+ context = new UnivaContext({
462
+ root: process.cwd()
330
463
  });
464
+ ensureUnivaDir(context.root);
465
+ context.loadUserConfigSync();
466
+ setDebug(context.config?.debug ?? false);
467
+ context.ensureRootComponent(`${ROOT_NAME}.vue`);
468
+ const resolved = resolveOptions2(context.config || {});
469
+ log("\u5DF2\u52A0\u8F7D\u914D\u7F6E\uFF1A", context.configPath || "\u9ED8\u8BA4\u914D\u7F6E");
470
+ return createUnivaPlugins(resolved);
331
471
  }
472
+ var plugins_default = Univa;
473
+
474
+ // src/index.ts
475
+ import { presetUni } from "@uni-helper/unocss-preset-uni";
476
+ import { camelCase, kebabCase, pascalCase } from "@uni-helper/vite-plugin-uni-components";
477
+ import { default as default2 } from "@uni-helper/vite-plugin-uni-components";
478
+ import { VitePluginUniLayouts as VitePluginUniLayouts2 } from "@uni-helper/vite-plugin-uni-layouts";
479
+ import { PageContext, VitePluginUniPages as VitePluginUniPages2 } from "@uni-helper/vite-plugin-uni-pages";
480
+ import { default as default3 } from "@uni-ku/root";
481
+ import { default as default4 } from "unplugin-auto-import/vite";
332
482
  export {
333
- Univa,
334
- definePagesConfig,
335
- presetUniva
483
+ default4 as AutoImport,
484
+ PageContext,
485
+ default3 as UniKuRoot,
486
+ plugins_default as Univa,
487
+ default2 as VitePluginUniComponents,
488
+ VitePluginUniLayouts2 as VitePluginUniLayouts,
489
+ VitePluginUniPages2 as VitePluginUniPages,
490
+ camelCase,
491
+ createUnivaPlugins,
492
+ defineConfig,
493
+ kebabCase,
494
+ pascalCase,
495
+ presetUni
336
496
  };