@ubean/build 0.4.4 → 0.4.6

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.
@@ -0,0 +1,254 @@
1
+ import { resolve } from "pathe";
2
+ import { extractLocaleFromPath } from "@ubean/i18n";
3
+ import { getLogger } from "@ubean/shared/logger";
4
+ import { pathToFileURL } from "node:url";
5
+ //#region src/static-render.ts
6
+ /**
7
+ * 静态 SSG 渲染器(mode: 'ssg' 专用,见 docs/adr/0011-lightweight-ssg-direct-render.md)。
8
+ *
9
+ * 职责:
10
+ * 1. `compilePageRoute` / `matchRoutePattern`:把具象 URL 匹配到页面路由模式
11
+ * (`[param]` → `:param`、`[...slug]` → `**:slug`、`[[param]]` → `:param?`),
12
+ * 提取路由参数 —— 替代 Hono 的路由匹配层
13
+ * 2. `createStaticSsgRenderer`:加载构建产物中的静态 entry(renderStaticPage),
14
+ * 暴露与 `prerender()` 的 fetcher 同构的契约,绕过 Hono 请求管道
15
+ */
16
+ const logger = getLogger("build");
17
+ /** 哨兵路由:prerender 队列中的 404 页标记,产物映射为 `404.html` */
18
+ const STATIC_NOT_FOUND_ROUTE = "/__ubean_404__";
19
+ const CATCH_ALL_SEGMENT = /^\*\*:([A-Za-z_][\w-]*)$/;
20
+ /**
21
+ * vue-router 参数段语法(`definePage({ path })` 覆盖时的 route 形态):
22
+ * - `:param` → 单段
23
+ * - `:param?` → 可选单段
24
+ * - `:param(regex)` → 自定义正则(如 `:id(\\d+)`)
25
+ * - `:param(regex)*` / `:param*` → 可重复(0..n 段,如 `:slug(.*)*` catch-all)
26
+ * - `:param(regex)+` / `:param+` → 可重复(1..n 段)
27
+ */
28
+ const DYNAMIC_SEGMENT = /^:([A-Za-z_][\w-]*)(\(.+\))?([*+?])?$/;
29
+ function escapeRegExp(str) {
30
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
+ }
32
+ /** 归一化 URL path:去尾部斜杠(根路由归一为空串便于匹配) */
33
+ function normalizeUrlPath(path) {
34
+ if (path === "/" || path === "") return "";
35
+ let p = path;
36
+ if (!p.startsWith("/")) p = `/${p}`;
37
+ while (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
38
+ return p;
39
+ }
40
+ /**
41
+ * 编译页面路由模式为正则。
42
+ *
43
+ * 输入 `page.route` 两种形态:
44
+ * 1. scan 产物默认语法(route-path.ts):
45
+ * - `/about`(静态)
46
+ * - `/blog/:slug`(动态)
47
+ * - `/docs/**:path`(catch-all,匹配剩余全部段,也匹配模式自身)
48
+ * - `/users/:id?`(可选段)
49
+ * 2. `definePage({ path })` 覆盖的 vue-router 语法:
50
+ * - `/blog/:slug(.*)*`(自定义正则 + 可重复 = catch-all)
51
+ * - `/users/:id(\\d+)`(自定义正则)
52
+ */
53
+ function compilePageRoute(page) {
54
+ const segments = normalizeUrlPath(page.route).split("/").filter(Boolean);
55
+ let source = "^";
56
+ const paramNames = [];
57
+ let isCatchAll = false;
58
+ let staticSegments = 0;
59
+ for (const seg of segments) {
60
+ const catchAll = CATCH_ALL_SEGMENT.exec(seg);
61
+ if (catchAll) {
62
+ paramNames.push(catchAll[1]);
63
+ isCatchAll = true;
64
+ source += "(?:/(.+))?";
65
+ continue;
66
+ }
67
+ const dynamic = DYNAMIC_SEGMENT.exec(seg);
68
+ if (dynamic) {
69
+ const [, name, custom, modifier] = dynamic;
70
+ paramNames.push(name);
71
+ const inner = custom ? custom.slice(1, -1) : "[^/]+";
72
+ if (modifier === "*" || modifier === "+") {
73
+ isCatchAll = true;
74
+ source += modifier === "*" ? `(?:/(${inner}(?:/${inner})*))?` : `/(${inner}(?:/${inner})*)`;
75
+ } else if (modifier === "?") source += `(?:/(${inner}))?`;
76
+ else source += `/(${inner})`;
77
+ continue;
78
+ }
79
+ staticSegments++;
80
+ source += `/${escapeRegExp(seg)}`;
81
+ }
82
+ source += "/?$";
83
+ return {
84
+ page,
85
+ regex: new RegExp(source),
86
+ paramNames,
87
+ isCatchAll,
88
+ staticSegments
89
+ };
90
+ }
91
+ /**
92
+ * 将具象 URL path 匹配到页面路由模式,返回命中的页面与提取的参数。
93
+ *
94
+ * 匹配顺序(确定性):静态段多者优先 → catch-all 最后 → 同分保持传入顺序。
95
+ * 参数值经 `decodeURIComponent` 解码(对齐 Hono `c.req.param()` 行为)。
96
+ */
97
+ function matchRoutePattern(pages, path) {
98
+ const ordered = pages.map((p) => "regex" in p ? p : compilePageRoute(p)).map((c, i) => ({
99
+ c,
100
+ i
101
+ })).sort((a, b) => Number(a.c.isCatchAll) - Number(b.c.isCatchAll) || b.c.staticSegments - a.c.staticSegments || a.i - b.i).map(({ c }) => c);
102
+ const target = normalizeUrlPath(path);
103
+ for (const c of ordered) {
104
+ const m = c.regex.exec(target);
105
+ if (!m) continue;
106
+ const params = {};
107
+ c.paramNames.forEach((name, idx) => {
108
+ const raw = m[idx + 1];
109
+ if (raw === void 0) return;
110
+ try {
111
+ params[name] = decodeURIComponent(raw);
112
+ } catch {
113
+ params[name] = raw;
114
+ }
115
+ });
116
+ return {
117
+ page: c.page,
118
+ params
119
+ };
120
+ }
121
+ return null;
122
+ }
123
+ function dedupeRoutes(routes) {
124
+ return [...new Set(routes)];
125
+ }
126
+ /**
127
+ * 按路由策略将收集到的路由展开为全语言 URL 列表。
128
+ *
129
+ * | strategy | 展开规则 |
130
+ * | --- | --- |
131
+ * | `no_prefix` | 不展开(每 route 渲染 1 次) |
132
+ * | `prefix_except_default` | default 无前缀 + 其余 locale 带前缀 |
133
+ * | `prefix` | 全部 locale 带前缀(无前缀版本不生成——fetcher 对其 404) |
134
+ * | `prefix_and_default` | 全部 locale 带前缀 + default 额外无前缀版本 |
135
+ *
136
+ * 特殊输入:
137
+ * - 404 哨兵路由不展开(静态托管平台仅认单份 `404.html`)
138
+ * - 已带 locale 前缀的 URL(crawlLinks 发现)保持原样,避免 `/zh/zh/about`
139
+ */
140
+ function expandRoutesForLocales(routes, i18n) {
141
+ const i18nEnabled = i18n != null && i18n.enabled !== false;
142
+ const localeCodes = i18nEnabled ? (i18n.locales || []).map((l) => typeof l === "string" ? l : l.code) : [];
143
+ if (!i18nEnabled || localeCodes.length === 0) return dedupeRoutes(routes);
144
+ const strategy = i18n.strategy || "prefix_except_default";
145
+ if (strategy === "no_prefix") return dedupeRoutes(routes);
146
+ const defaultLocale = i18n.defaultLocale || localeCodes[0] || "";
147
+ const expanded = [];
148
+ for (const route of routes) {
149
+ if (route === "/__ubean_404__") {
150
+ expanded.push(route);
151
+ continue;
152
+ }
153
+ const { locale } = extractLocaleFromPath(route, localeCodes);
154
+ if (locale) {
155
+ expanded.push(route);
156
+ continue;
157
+ }
158
+ const suffix = route === "/" || route === "" ? "" : route;
159
+ switch (strategy) {
160
+ case "prefix":
161
+ for (const code of localeCodes) expanded.push(`/${code}${suffix}`);
162
+ break;
163
+ case "prefix_and_default":
164
+ expanded.push(route || "/");
165
+ for (const code of localeCodes) expanded.push(`/${code}${suffix}`);
166
+ break;
167
+ default:
168
+ expanded.push(route || "/");
169
+ for (const code of localeCodes) {
170
+ if (code === defaultLocale) continue;
171
+ expanded.push(`/${code}${suffix}`);
172
+ }
173
+ }
174
+ }
175
+ return dedupeRoutes(expanded);
176
+ }
177
+ /**
178
+ * 加载构建产物中的静态 entry(`dist/server/entry.mjs`),返回静态渲染器。
179
+ *
180
+ * 失败(entry 缺失 / 无 renderStaticPage 导出 / 加载异常)返回 `undefined`,
181
+ * 由调用方降级(warn + placeholder prerender)。
182
+ */
183
+ async function createStaticSsgRenderer(cwd, manifest, init) {
184
+ let mod;
185
+ try {
186
+ const entryPath = resolve(cwd, manifest.serverDir, "entry.mjs");
187
+ mod = await import(pathToFileURL(entryPath).href);
188
+ } catch (err) {
189
+ logger.warn(`Failed to load static SSG entry: ${err instanceof Error ? err.message : String(err)}. Falling back.`);
190
+ return;
191
+ }
192
+ if (typeof mod.renderStaticPage !== "function") {
193
+ logger.warn("Static SSG entry does not export renderStaticPage; falling back.");
194
+ return;
195
+ }
196
+ const renderStaticPage = mod.renderStaticPage;
197
+ const compiled = init.pages.map(compilePageRoute);
198
+ const i18nEnabled = init.i18n != null && init.i18n.enabled !== false;
199
+ const localeCodes = i18nEnabled ? (init.i18n?.locales || []).map((l) => typeof l === "string" ? l : l.code) : [];
200
+ const strategy = i18nEnabled ? init.i18n?.strategy || "prefix_except_default" : "no_prefix";
201
+ const defaultLocale = i18nEnabled && init.i18n?.defaultLocale || "";
202
+ const usePrefix = i18nEnabled && localeCodes.length > 0 && strategy !== "no_prefix";
203
+ return {
204
+ renderStaticPage,
205
+ expandRoutes: (routes) => expandRoutesForLocales(routes, {
206
+ enabled: i18nEnabled,
207
+ strategy,
208
+ defaultLocale,
209
+ locales: localeCodes
210
+ }),
211
+ fetcher: async (url) => {
212
+ const u = new URL(url, "http://ubean.local");
213
+ const pathname = u.pathname;
214
+ const search = u.search;
215
+ if (pathname === "/__ubean_404__") {
216
+ if (!init.notFoundPage) return {
217
+ html: "",
218
+ statusCode: 404
219
+ };
220
+ return renderStaticPage({
221
+ pageName: "NotFound",
222
+ params: {},
223
+ url: `/404${search}`,
224
+ locale: defaultLocale
225
+ });
226
+ }
227
+ let pathToMatch = pathname;
228
+ let locale = defaultLocale;
229
+ if (usePrefix) {
230
+ const { locale: extracted, pathWithoutLocale } = extractLocaleFromPath(pathname, localeCodes);
231
+ if (extracted) {
232
+ locale = extracted;
233
+ pathToMatch = pathWithoutLocale;
234
+ } else if (strategy === "prefix") return {
235
+ html: "",
236
+ statusCode: 404
237
+ };
238
+ }
239
+ const match = matchRoutePattern(compiled, pathToMatch);
240
+ if (!match) return {
241
+ html: "",
242
+ statusCode: 404
243
+ };
244
+ return renderStaticPage({
245
+ pageName: match.page.name,
246
+ params: match.params,
247
+ url: `${pathname}${search}`,
248
+ locale
249
+ });
250
+ }
251
+ };
252
+ }
253
+ //#endregion
254
+ export { STATIC_NOT_FOUND_ROUTE, compilePageRoute, createStaticSsgRenderer, expandRoutesForLocales, matchRoutePattern };
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ResolvedConfig } from "@ubean/config";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/vite.d.ts
4
- interface UbeanPluginOptions {
4
+ export interface UbeanPluginOptions {
5
5
  /**
6
6
  * 已解析的 ubean 配置。如果未提供,插件会按以下顺序获取:
7
7
  * 1. 尝试从全局缓存读取(`loadUbeanConfig` 已被 CLI 调用时会有缓存)
@@ -36,6 +36,5 @@ interface UbeanPluginOptions {
36
36
  * ubeanPlugin({ config: resolvedConfig })
37
37
  * ```
38
38
  */
39
- declare function ubeanPlugin(options?: UbeanPluginOptions): Plugin;
40
- //#endregion
41
- export { UbeanPluginOptions, ubeanPlugin };
39
+ export declare function ubeanPlugin(options?: UbeanPluginOptions): Plugin;
40
+ //#endregion
@@ -1,6 +1,6 @@
1
1
  import { a as useVirtualRegistry, n as defineVirtualModule } from "./virtual-registry-BWkaQHXN.js";
2
2
  import { c as getCssImports, i as ssrSingletonDevPolicy, s as getComponentResolvers } from "./ssr-singleton-CEQi_H6-.js";
3
- import { E as toArray, T as resolveComponentsConfig, b as getAutoImportPresets, w as resolveAutoImportsConfig } from "./codegen-BqqGw4Dv.js";
3
+ import { E as toArray, T as resolveComponentsConfig, b as getAutoImportPresets, w as resolveAutoImportsConfig } from "./codegen-B3oGeRtK.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { join, resolve } from "pathe";
6
6
  import { scanProject } from "@ubean/scan";
@@ -162,15 +162,17 @@ function _mergeAppConfig(base, ...configs) {
162
162
  for (const cfg of [base, ...configs]) {
163
163
  if (cfg?.router?.setup) setups.push(cfg.router.setup);
164
164
  }
165
- if (setups.length === 1) {
166
- result.router = { setup: setups[0] };
167
- } else if (setups.length > 1) {
168
- result.router = {
169
- setup: (router) => {
170
- for (const s of setups) s(router);
171
- }
172
- };
165
+ // scrollBehavior 为函数不可合并,后者覆盖(shared 之后定义的 client/server 生效)。
166
+ let scrollBehavior;
167
+ for (const cfg of [base, ...configs]) {
168
+ if (cfg?.router?.scrollBehavior !== undefined) scrollBehavior = cfg.router.scrollBehavior;
169
+ }
170
+ const router = {};
171
+ if (setups.length > 0) {
172
+ router.setup = setups.length === 1 ? setups[0] : (r) => { for (const s of setups) s(r); };
173
173
  }
174
+ if (scrollBehavior !== undefined) router.scrollBehavior = scrollBehavior;
175
+ if (setups.length > 0 || scrollBehavior !== undefined) result.router = router;
174
176
  return result;
175
177
  }
176
178
 
@@ -233,7 +235,7 @@ export async function createApp() {
233
235
  viewTransitions: config.viewTransitions,
234
236
  initialPage: initialPage || undefined,
235
237
  hydrate: !!initialPage,
236
- routerSetup: config.router?.setup,
238
+ router: config.router,
237
239
  loadingComponent,
238
240
  errorComponent,
239
241
  // appRoot 已在 resolveAppConfig 中合并(src/App.vue 默认 + defineApp 显式覆盖)
@@ -318,7 +320,7 @@ export async function createSSRApp(initialPage) {
318
320
  resolveLayoutComponent,
319
321
  defaultLayout,
320
322
  head,
321
- routerSetup: config.router?.setup,
323
+ router: config.router,
322
324
  loadingComponent,
323
325
  errorComponent,
324
326
  // appRoot 已在 resolveAppConfig 中合并(src/App.vue 默认 + defineApp 显式覆盖),
@@ -628,7 +630,8 @@ function ubeanVite(options) {
628
630
  const UBEAN_BUILTIN_COMPONENTS = [
629
631
  "Link",
630
632
  "Head",
631
- "PageView"
633
+ "PageView",
634
+ "ClientOnly"
632
635
  ];
633
636
  function ubeanComponentsResolver(componentName) {
634
637
  if (UBEAN_BUILTIN_COMPONENTS.includes(componentName)) return {
package/dist/vue.d.ts CHANGED
@@ -7,8 +7,8 @@ interface UbeanViteOptions {
7
7
  config: ResolvedConfig;
8
8
  ssr?: boolean;
9
9
  }
10
- declare const VUE_PLUGIN_INCLUDE: RegExp[];
11
- declare function ubeanVite(options: UbeanViteOptions): Plugin[];
10
+ export declare const VUE_PLUGIN_INCLUDE: RegExp[];
11
+ export declare function ubeanVite(options: UbeanViteOptions): Plugin[];
12
12
  //#endregion
13
13
  //#region src/vue-virtual-modules.d.ts
14
14
  /**
@@ -21,9 +21,9 @@ declare function ubeanVite(options: UbeanViteOptions): Plugin[];
21
21
  * `requiresAuth` / `head` / `definePage({ meta })` 透传字段(超集,
22
22
  * 使 `createMatcherGuard()` 与 SPA head guard 在框架模式下同样可用)。
23
23
  */
24
- declare function createVuePagesVirtualModule(pages: ScannedPageRoute[], layouts: ScannedLayout[], notFoundPage?: ScannedPageRoute, loadingPage?: ScannedPageRoute, errorPage?: ScannedPageRoute, localeVueParam?: string): VirtualModule;
25
- declare function createVueAppEntryVirtualModule(appEntry?: ScannedAppEntry): VirtualModule;
26
- declare function createClientEntryVirtualModule(): VirtualModule;
27
- declare function createServerEntryVirtualModule(serverEntry?: ScannedServerEntry): VirtualModule;
24
+ export declare function createVuePagesVirtualModule(pages: ScannedPageRoute[], layouts: ScannedLayout[], notFoundPage?: ScannedPageRoute, loadingPage?: ScannedPageRoute, errorPage?: ScannedPageRoute, localeVueParam?: string): VirtualModule;
25
+ export declare function createVueAppEntryVirtualModule(appEntry?: ScannedAppEntry): VirtualModule;
26
+ export declare function createClientEntryVirtualModule(): VirtualModule;
27
+ export declare function createServerEntryVirtualModule(serverEntry?: ScannedServerEntry): VirtualModule;
28
28
  //#endregion
29
- export { type UbeanViteOptions, VUE_PLUGIN_INCLUDE, createClientEntryVirtualModule, createServerEntryVirtualModule, createVueAppEntryVirtualModule, createVuePagesVirtualModule, ubeanVite as default, ubeanVite };
29
+ export { type UbeanViteOptions, ubeanVite as default };
package/dist/vue.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as createVueAppEntryVirtualModule, i as createServerEntryVirtualModule, n as ubeanVite, o as createVuePagesVirtualModule, r as createClientEntryVirtualModule, t as VUE_PLUGIN_INCLUDE } from "./vue-DzQKpjU3.js";
1
+ import { a as createVueAppEntryVirtualModule, i as createServerEntryVirtualModule, n as ubeanVite, o as createVuePagesVirtualModule, r as createClientEntryVirtualModule, t as VUE_PLUGIN_INCLUDE } from "./vue-DcydGsvy.js";
2
2
  export { VUE_PLUGIN_INCLUDE, createClientEntryVirtualModule, createServerEntryVirtualModule, createVueAppEntryVirtualModule, createVuePagesVirtualModule, ubeanVite as default, ubeanVite };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ubean/build",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "Vite plugins, production build, SSG prerender, type codegen, and Server Actions plugin for ubean",
5
5
  "files": [
6
6
  "dist"
@@ -30,6 +30,10 @@
30
30
  "types": "./dist/prerender.d.ts",
31
31
  "import": "./dist/prerender.js"
32
32
  },
33
+ "./static-render": {
34
+ "types": "./dist/static-render.d.ts",
35
+ "import": "./dist/static-render.js"
36
+ },
33
37
  "./codegen": {
34
38
  "types": "./dist/codegen/index.d.ts",
35
39
  "import": "./dist/codegen/index.js"
@@ -41,17 +45,17 @@
41
45
  },
42
46
  "dependencies": {
43
47
  "@intlify/unplugin-vue-i18n": "11.2.5",
44
- "@ubean/client": "0.4.4",
45
- "@ubean/config": "0.4.4",
46
- "@ubean/i18n": "0.4.4",
47
- "@ubean/islands": "0.4.4",
48
- "@ubean/markdown": "0.4.4",
49
- "@ubean/pages": "0.4.4",
50
- "@ubean/preset": "0.4.4",
51
- "@ubean/routes": "0.4.4",
52
- "@ubean/scan": "0.4.4",
53
- "@ubean/shared": "0.4.4",
54
- "@ubean/vue": "0.4.4",
48
+ "@ubean/client": "0.4.6",
49
+ "@ubean/config": "0.4.6",
50
+ "@ubean/i18n": "0.4.6",
51
+ "@ubean/islands": "0.4.6",
52
+ "@ubean/markdown": "0.4.6",
53
+ "@ubean/pages": "0.4.6",
54
+ "@ubean/preset": "0.4.6",
55
+ "@ubean/routes": "0.4.6",
56
+ "@ubean/scan": "0.4.6",
57
+ "@ubean/shared": "0.4.6",
58
+ "@ubean/vue": "0.4.6",
55
59
  "@vitejs/plugin-vue": "^6.0.8",
56
60
  "openapi-typescript": "^7.13.0",
57
61
  "pathe": "^2.0.3",
@@ -65,12 +69,12 @@
65
69
  "devDependencies": {
66
70
  "@types/node": "^26.5.0",
67
71
  "hono": "4.13.7",
68
- "typescript": "7.0.2",
69
- "vite": "npm:@voidzero-dev/vite-plus-core@0.3.0",
70
- "vite-plus": "0.3.0"
72
+ "typescript": "npm:typescript-native-bridge@latest",
73
+ "vite": "npm:@voidzero-dev/vite-plus-core@0.3.1",
74
+ "vite-plus": "0.3.1"
71
75
  },
72
76
  "peerDependencies": {
73
- "vite": "npm:@voidzero-dev/vite-plus-core@0.3.0"
77
+ "vite": "npm:@voidzero-dev/vite-plus-core@0.3.1"
74
78
  },
75
79
  "peerDependenciesMeta": {
76
80
  "vite": {