@void/vue 0.0.0

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,729 @@
1
+ import vue from "@vitejs/plugin-vue";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ import { normalizePath } from "vite";
4
+ import { generateComponentManifest, resolveEffectiveLayoutChain, resolveStaticPageDataBuildOptions, scanPages } from "void/pages";
5
+ import { ISLANDS_CLIENT_ENTRY_ID, ISLANDS_RENDERER_ID, computePagesNeedingClientJS, configureIslandCssServer, needsIslandClientBundle, rebuildIslandCssMap, resolveSpecifier, rewriteCssImportForVirtualModule, watchPagesForRescan } from "void/pages-islands-plugin";
6
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
7
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
8
+ function normalizeWindowsPath(input = "") {
9
+ if (!input) return input;
10
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
11
+ }
12
+ const _UNC_REGEX = /^[/\\]{2}/;
13
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
14
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
15
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
16
+ const normalize = function(path) {
17
+ if (path.length === 0) return ".";
18
+ path = normalizeWindowsPath(path);
19
+ const isUNCPath = path.match(_UNC_REGEX);
20
+ const isPathAbsolute = isAbsolute(path);
21
+ const trailingSeparator = path[path.length - 1] === "/";
22
+ path = normalizeString(path, !isPathAbsolute);
23
+ if (path.length === 0) {
24
+ if (isPathAbsolute) return "/";
25
+ return trailingSeparator ? "./" : ".";
26
+ }
27
+ if (trailingSeparator) path += "/";
28
+ if (_DRIVE_LETTER_RE.test(path)) path += "/";
29
+ if (isUNCPath) {
30
+ if (!isPathAbsolute) return `//./${path}`;
31
+ return `//${path}`;
32
+ }
33
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
34
+ };
35
+ const join = function(...segments) {
36
+ let path = "";
37
+ for (const seg of segments) {
38
+ if (!seg) continue;
39
+ if (path.length > 0) {
40
+ const pathTrailing = path[path.length - 1] === "/";
41
+ const segLeading = seg[0] === "/";
42
+ if (pathTrailing && segLeading) path += seg.slice(1);
43
+ else path += pathTrailing || segLeading ? seg : `/${seg}`;
44
+ } else path += seg;
45
+ }
46
+ return normalize(path);
47
+ };
48
+ function cwd() {
49
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
50
+ return "/";
51
+ }
52
+ const resolve = function(...arguments_) {
53
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
54
+ let resolvedPath = "";
55
+ let resolvedAbsolute = false;
56
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
57
+ const path = index >= 0 ? arguments_[index] : cwd();
58
+ if (!path || path.length === 0) continue;
59
+ resolvedPath = `${path}/${resolvedPath}`;
60
+ resolvedAbsolute = isAbsolute(path);
61
+ }
62
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
63
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
64
+ return resolvedPath.length > 0 ? resolvedPath : ".";
65
+ };
66
+ function normalizeString(path, allowAboveRoot) {
67
+ let res = "";
68
+ let lastSegmentLength = 0;
69
+ let lastSlash = -1;
70
+ let dots = 0;
71
+ let char = null;
72
+ for (let index = 0; index <= path.length; ++index) {
73
+ if (index < path.length) char = path[index];
74
+ else if (char === "/") break;
75
+ else char = "/";
76
+ if (char === "/") {
77
+ if (lastSlash === index - 1 || dots === 1);
78
+ else if (dots === 2) {
79
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
80
+ if (res.length > 2) {
81
+ const lastSlashIndex = res.lastIndexOf("/");
82
+ if (lastSlashIndex === -1) {
83
+ res = "";
84
+ lastSegmentLength = 0;
85
+ } else {
86
+ res = res.slice(0, lastSlashIndex);
87
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
88
+ }
89
+ lastSlash = index;
90
+ dots = 0;
91
+ continue;
92
+ } else if (res.length > 0) {
93
+ res = "";
94
+ lastSegmentLength = 0;
95
+ lastSlash = index;
96
+ dots = 0;
97
+ continue;
98
+ }
99
+ }
100
+ if (allowAboveRoot) {
101
+ res += res.length > 0 ? "/.." : "..";
102
+ lastSegmentLength = 2;
103
+ }
104
+ } else {
105
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
106
+ else res = path.slice(lastSlash + 1, index);
107
+ lastSegmentLength = index - lastSlash - 1;
108
+ }
109
+ lastSlash = index;
110
+ dots = 0;
111
+ } else if (char === "." && dots !== -1) ++dots;
112
+ else dots = -1;
113
+ }
114
+ return res;
115
+ }
116
+ const isAbsolute = function(p) {
117
+ return _IS_ABSOLUTE_RE.test(p);
118
+ };
119
+ const relative = function(from, to) {
120
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
121
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
122
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
123
+ const _fromCopy = [..._from];
124
+ for (const segment of _fromCopy) {
125
+ if (_to[0] !== segment) break;
126
+ _from.shift();
127
+ _to.shift();
128
+ }
129
+ return [..._from.map(() => ".."), ..._to].join("/");
130
+ };
131
+ const dirname = function(p) {
132
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
133
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
134
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
135
+ };
136
+ //#endregion
137
+ //#region src/plugin-islands.ts
138
+ const COMPONENT_EXTENSIONS = [
139
+ ".vue",
140
+ ".tsx",
141
+ ".jsx",
142
+ ".ts",
143
+ ".js"
144
+ ];
145
+ function fileHasCss(filePath) {
146
+ try {
147
+ const code = readFileSync(filePath, "utf-8");
148
+ if (/import\b[^"']*["'][^"']+\.(?:css|scss|sass|less|styl|stylus|pcss|postcss)["']/.test(code)) return true;
149
+ if (/<style\b(?![^>]*\bscoped\b)[^>]*>/.test(code)) return true;
150
+ return false;
151
+ } catch {
152
+ return false;
153
+ }
154
+ }
155
+ function extractCss(filePath) {
156
+ const code = readFileSync(filePath, "utf-8");
157
+ const parts = [];
158
+ const jsRe = /^\s*import\b[^"']*["']([^"']+\.(?:css|scss|sass|less|styl|stylus|pcss|postcss))["']/gm;
159
+ let match;
160
+ while ((match = jsRe.exec(code)) !== null) parts.push(`@import ${JSON.stringify(match[1])};`);
161
+ const styleBlockRe = /<style\b([^>]*)>([\s\S]*?)<\/style>/g;
162
+ while ((match = styleBlockRe.exec(code)) !== null) {
163
+ const attrs = match[1];
164
+ if (/\bscoped\b/.test(attrs)) continue;
165
+ const content = match[2].trim();
166
+ if (content) parts.push(content);
167
+ }
168
+ return parts.join("\n");
169
+ }
170
+ function islandsPlugin(pagesDir) {
171
+ let pageScan = null;
172
+ const root = dirname(pagesDir);
173
+ const islandManifest = /* @__PURE__ */ new Map();
174
+ const islandCssFiles = /* @__PURE__ */ new Set();
175
+ let isDev = false;
176
+ let viteRoot = "";
177
+ const islandCssMap = /* @__PURE__ */ new Map();
178
+ let resolvedConfig = null;
179
+ /** Rebuild islandCssMap from current file contents (re-runs fileHasCss). */
180
+ function rebuildIslandCssMap$1() {
181
+ if (!pageScan) return;
182
+ rebuildIslandCssMap(pageScan, pagesDir, islandCssMap, fileHasCss);
183
+ }
184
+ function computePagesNeedingClientJS$1() {
185
+ if (!pageScan) return /* @__PURE__ */ new Set();
186
+ return computePagesNeedingClientJS(pageScan, pagesDir, resolvedConfig);
187
+ }
188
+ return [{
189
+ name: "void-vue:islands",
190
+ enforce: "pre",
191
+ configResolved(config) {
192
+ resolvedConfig = config;
193
+ viteRoot = config.root;
194
+ isDev = config.command === "serve";
195
+ },
196
+ configureServer(server) {
197
+ configureIslandCssServer(server, islandCssFiles, viteRoot, rebuildIslandCssMap$1);
198
+ watchPagesForRescan(server, pagesDir, root, (scan) => {
199
+ pageScan = scan;
200
+ rebuildIslandCssMap$1();
201
+ });
202
+ },
203
+ async buildStart() {
204
+ if (existsSync(pagesDir)) {
205
+ pageScan = await scanPages(root);
206
+ const importAttrRe = /import\s+\w+\s+from\s+("[^"]+"|'[^']+')\s+with\s*\{\s*island\s*:\s*("[^"]+"|'[^']+')\s*\}/g;
207
+ const filesToScan = [
208
+ ...pageScan.pages.map((p) => ({
209
+ filePath: p.componentPath,
210
+ island: p.island
211
+ })),
212
+ ...pageScan.layouts.map((l) => ({
213
+ filePath: l.filePath,
214
+ island: l.island
215
+ })),
216
+ ...pageScan.namedLayouts.map((nl) => ({
217
+ filePath: nl.filePath,
218
+ island: nl.island
219
+ }))
220
+ ];
221
+ for (const entry of filesToScan) {
222
+ if (!entry.island) continue;
223
+ const filePath = resolve(pagesDir, entry.filePath);
224
+ const code = readFileSync(filePath, "utf-8");
225
+ const importerDir = dirname(filePath);
226
+ importAttrRe.lastIndex = 0;
227
+ let m;
228
+ while ((m = importAttrRe.exec(code)) !== null) {
229
+ const spec = m[1].slice(1, -1);
230
+ const strategy = m[2].slice(1, -1);
231
+ const absPath = resolveSpecifier(spec, importerDir, COMPONENT_EXTENSIONS);
232
+ if (absPath) {
233
+ const islandId = normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, "");
234
+ islandManifest.set(islandId, {
235
+ componentPath: absPath,
236
+ islandId,
237
+ hydrate: strategy
238
+ });
239
+ }
240
+ }
241
+ }
242
+ for (const page of pageScan.pages) {
243
+ if (!page.island) continue;
244
+ if (page.componentPath.endsWith(".vue")) islandCssFiles.add(normalizePath(resolve(pagesDir, page.componentPath)));
245
+ const layoutChain = resolveEffectiveLayoutChain(page, pageScan.layouts, pageScan.namedLayouts);
246
+ for (const layout of layoutChain) islandCssFiles.add(normalizePath(resolve(pagesDir, layout.filePath)));
247
+ }
248
+ rebuildIslandCssMap$1();
249
+ }
250
+ },
251
+ resolveId: {
252
+ filter: { id: /^virtual:void-islands-(renderer|client)$|\.vue\.css$/ },
253
+ handler(source) {
254
+ if (source === ISLANDS_RENDERER_ID || source === ISLANDS_CLIENT_ENTRY_ID) return "\0" + source;
255
+ if (source.endsWith(".css")) {
256
+ const srcPath = normalizePath(source.slice(0, -4));
257
+ if (islandCssFiles.has(srcPath)) return srcPath + ".css";
258
+ if (srcPath.startsWith("/")) {
259
+ const absPath = normalizePath(resolve(viteRoot, srcPath.slice(1)));
260
+ if (islandCssFiles.has(absPath)) return absPath + ".css";
261
+ }
262
+ }
263
+ }
264
+ },
265
+ load: {
266
+ filter: { id: /^\0virtual:void-islands-(renderer|client)$|\.vue\.css$/ },
267
+ handler(id) {
268
+ if (id === "\0" + ISLANDS_RENDERER_ID) {
269
+ if (!pageScan) return "export function renderIslandPage() { throw new Error('No pages found'); }";
270
+ const mdPlugin = resolvedConfig?.plugins?.find((p) => p.name === "void-md");
271
+ const mdScriptIds = new Set(mdPlugin?.api?.getClientScripts?.()?.keys() ?? []);
272
+ const needsJS = computePagesNeedingClientJS$1();
273
+ return generateIslandRenderer(pageScan, pagesDir, isDev, islandCssMap, viteRoot, mdScriptIds, needsJS);
274
+ }
275
+ if (id === "\0" + ISLANDS_CLIENT_ENTRY_ID) {
276
+ if (!pageScan) return "";
277
+ return generateIslandClientEntry(islandManifest, islandCssFiles, isDev);
278
+ }
279
+ if (id.endsWith(".css") && !id.startsWith("\0")) {
280
+ const srcPath = id.slice(0, -4);
281
+ if (islandCssFiles.has(srcPath)) return extractCss(srcPath);
282
+ }
283
+ }
284
+ },
285
+ transform: {
286
+ filter: { id: /\.island\.vue$/ },
287
+ handler(code, id) {
288
+ if (/import\s+\{[^}]*\buseForm\b/.test(code)) this.warn(`islands: useForm cannot be imported in island page '${id}'. Use useIslandForm instead.`);
289
+ const importAttrRe = /import\s+(\w+)\s+from\s+("[^"]+"|'[^']+')\s+with\s*\{\s*island\s*:\s*("[^"]+"|'[^']+')\s*\}/g;
290
+ const importerDir = dirname(id);
291
+ let transformed = code;
292
+ const wrappers = [];
293
+ let idx = 0;
294
+ let match;
295
+ while ((match = importAttrRe.exec(code)) !== null) {
296
+ const name = match[1];
297
+ const specRaw = match[2];
298
+ const strategyRaw = match[3];
299
+ const spec = specRaw.slice(1, -1);
300
+ const strategy = strategyRaw.slice(1, -1);
301
+ const rawName = `_raw_island_${idx++}`;
302
+ const absPath = resolveSpecifier(spec, importerDir, COMPONENT_EXTENSIONS);
303
+ if (absPath) {
304
+ const islandId = normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, "");
305
+ islandManifest.set(islandId, {
306
+ componentPath: absPath,
307
+ islandId,
308
+ hydrate: strategy
309
+ });
310
+ }
311
+ const islandId = absPath ? normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, "") : spec;
312
+ const replacement = `import ${rawName} from ${specRaw}`;
313
+ transformed = transformed.replace(match[0], replacement);
314
+ wrappers.push(`const ${name} = { inheritAttrs: false, render() { const props = this.$attrs; return _h_island("div", { "data-island": ${JSON.stringify(islandId)}, "data-props": JSON.stringify(props), "data-hydrate": ${JSON.stringify(strategy)} }, _h_island(${rawName}, props)); } };`);
315
+ }
316
+ if (wrappers.length > 0) {
317
+ const setupMatch = transformed.match(/<script\b[^>]*\bsetup\b[^>]*>/);
318
+ if (setupMatch) {
319
+ const openEnd = setupMatch.index + setupMatch[0].length;
320
+ const closeIdx = transformed.indexOf("<\/script>", openEnd);
321
+ if (closeIdx !== -1) transformed = transformed.slice(0, openEnd) + "\nimport { h as _h_island } from \"vue\";" + transformed.slice(openEnd, closeIdx) + "\n" + wrappers.join("\n") + "\n" + transformed.slice(closeIdx);
322
+ }
323
+ return {
324
+ code: transformed,
325
+ map: null
326
+ };
327
+ }
328
+ }
329
+ },
330
+ config(_, env) {
331
+ if (!existsSync(pagesDir)) return;
332
+ if (env.command === "serve") return { optimizeDeps: { include: ["vue"] } };
333
+ if (needsIslandClientBundle(pagesDir, /\.island\.vue$/, true)) return { environments: { client: { build: {
334
+ manifest: true,
335
+ rollupOptions: { input: { "islands-client": ISLANDS_CLIENT_ENTRY_ID } }
336
+ } } } };
337
+ }
338
+ }];
339
+ }
340
+ function generateIslandRenderer(scan, pagesDir, isDev, islandCssMap, viteRoot, mdScriptIds, pagesNeedingClientJS) {
341
+ let cssMapCode = "";
342
+ if (isDev && islandCssMap.size > 0) {
343
+ const cssMapObj = {};
344
+ for (const [compId, paths] of islandCssMap) cssMapObj[compId] = paths.map((p) => "/" + normalizePath(relative(viteRoot, p)) + ".css");
345
+ cssMapCode = `const __cssPaths = ${JSON.stringify(cssMapObj)};`;
346
+ }
347
+ const mdScriptIdsCode = `const __mdClientScriptIds = new Set(${JSON.stringify([...mdScriptIds])});`;
348
+ const needsJSCode = `const __pagesNeedingClientJS = new Set(${JSON.stringify([...pagesNeedingClientJS])});`;
349
+ return `
350
+ import { createSSRApp, h, reactive, provide } from "vue";
351
+ import { renderToString } from "vue/server-renderer";
352
+ import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from "void/pages-head";
353
+
354
+ ${generateComponentManifest(scan, pagesDir)}
355
+ ${cssMapCode}
356
+ ${mdScriptIdsCode}
357
+ ${needsJSCode}
358
+
359
+ function escapeAttr(s) {
360
+ return String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
361
+ }
362
+
363
+ export async function renderIslandPage(pageObj, assetTags) {
364
+ const __pageModule = await components[pageObj.component]();
365
+ const PageComponent = __pageModule.default;
366
+ const __frontmatter = __pageModule.frontmatter;
367
+ const layoutIds = layoutTree[pageObj.component] || [];
368
+ const layoutComponents = await Promise.all(
369
+ layoutIds.map(async (id) => (await components[id]()).default)
370
+ );
371
+
372
+ const app = createSSRApp({
373
+ setup() {
374
+ provide("__void_shared", reactive(pageObj.shared || {}));
375
+ provide("__void_errors", reactive(pageObj.errors || {}));
376
+ if (__frontmatter) provide("__void_frontmatter", __frontmatter);
377
+ // No router provided — islands have no Void Router
378
+ return () => {
379
+ let vnode = h(PageComponent, pageObj.props);
380
+ for (let i = layoutComponents.length - 1; i >= 0; i--) {
381
+ const inner = vnode;
382
+ vnode = h(layoutComponents[i], null, { default: () => inner });
383
+ }
384
+ return vnode;
385
+ };
386
+ }
387
+ });
388
+
389
+ const html = await renderToString(app);
390
+ const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : "";
391
+ const headHtml = pageObj.head ? renderHeadToString(pageObj.head) : "";
392
+ const htmlAttrs = pageObj.head ? renderHtmlAttrs(pageObj.head) : "";
393
+ const bodyAttrs = pageObj.head ? renderBodyAttrs(pageObj.head) : "";
394
+
395
+ return \`<!doctype html>
396
+ <html\${htmlAttrs}>
397
+ <head>\${headHtml}\${typeof __cssPaths !== "undefined" ? (__cssPaths[pageObj.component] || []).map(url => '<link rel="stylesheet" href="' + url + '">').join("\\n") : ""}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}</head>
398
+ <body\${bodyAttrs}>
399
+ <div id="app"\${__mdScriptAttr}>\${html}</div>
400
+ \${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""}
401
+ </body>
402
+ </html>\`;
403
+ }
404
+ `;
405
+ }
406
+ function generateIslandClientEntry(manifest, cssFiles, isDev) {
407
+ const entries = [...manifest.values()];
408
+ const uniqueIslands = /* @__PURE__ */ new Map();
409
+ for (const entry of entries) uniqueIslands.set(entry.islandId, entry.componentPath);
410
+ const lines = [];
411
+ lines.push("import { initIslands } from \"void/pages-client\";");
412
+ if (!isDev) {
413
+ const styleRe = /<style\b([^>]*)>/g;
414
+ const cssImportRe = /^\s*import\b[^"']*["']([^"']+\.(?:css|scss|sass|less|styl|stylus|pcss|postcss))["']/gm;
415
+ for (const file of cssFiles) {
416
+ const content = readFileSync(file, "utf-8");
417
+ styleRe.lastIndex = 0;
418
+ let index = 0;
419
+ let match;
420
+ while ((match = styleRe.exec(content)) !== null) {
421
+ const attrs = match[1];
422
+ const scoped = /\bscoped\b/.test(attrs);
423
+ const langMatch = attrs.match(/\blang\s*=\s*["'](\w+)["']/);
424
+ const lang = langMatch ? langMatch[1] : "css";
425
+ let query = `?vue&type=style&index=${index}&lang.${lang}`;
426
+ if (scoped) query += "&scoped=true";
427
+ lines.push(`import ${JSON.stringify(file + query)};`);
428
+ index++;
429
+ }
430
+ cssImportRe.lastIndex = 0;
431
+ while ((match = cssImportRe.exec(content)) !== null) lines.push(rewriteCssImportForVirtualModule(match[0], match[1], file));
432
+ }
433
+ }
434
+ lines.push("const islands = {");
435
+ for (const [id, path] of uniqueIslands) lines.push(` ${JSON.stringify(id)}: () => import(${JSON.stringify(path)}),`);
436
+ lines.push("};");
437
+ lines.push(`
438
+ async function hydrateIsland(el, mod, props) {
439
+ const { createSSRApp, h } = await import("vue");
440
+ const Component = mod.default || mod;
441
+ const app = createSSRApp({ render: () => h(Component, props) });
442
+ app.mount(el);
443
+ el.setAttribute("data-hydrated", "true");
444
+ }
445
+
446
+ initIslands(islands, hydrateIsland);
447
+ `);
448
+ return lines.join("\n");
449
+ }
450
+ //#endregion
451
+ //#region src/plugin-pages.ts
452
+ const RENDERER_ID = "virtual:void-pages-renderer";
453
+ const CLIENT_ENTRY_ID = "virtual:void-pages-client";
454
+ function isVuePageFile(id, pagesDir) {
455
+ if (!id.startsWith(pagesDir + "/")) return false;
456
+ const rel = id.slice(pagesDir.length + 1);
457
+ if (rel.split("/").some((s) => s.startsWith("_"))) return false;
458
+ const basename = rel.slice(rel.lastIndexOf("/") + 1);
459
+ return basename !== "layout.vue" && !basename.endsWith(".island.vue");
460
+ }
461
+ function stripDefinePropsTypeArgument(code) {
462
+ const match = /\bdefineProps\s*</.exec(code);
463
+ if (!match) return null;
464
+ const start = match.index + match[0].length - 1;
465
+ let depth = 0;
466
+ let end = -1;
467
+ let newlineCount = 0;
468
+ for (let i = start; i < code.length; i++) {
469
+ const ch = code[i];
470
+ if (ch === "\n") newlineCount++;
471
+ else if (ch === "<") depth++;
472
+ else if (ch === ">") {
473
+ depth--;
474
+ if (depth === 0) {
475
+ end = i;
476
+ break;
477
+ }
478
+ }
479
+ }
480
+ if (end === -1) return null;
481
+ return code.slice(0, start) + "\n".repeat(newlineCount) + code.slice(end + 1);
482
+ }
483
+ /** Check if the pages directory has any non-island Vue page files. */
484
+ function hasNonIslandPages(dir) {
485
+ try {
486
+ for (const entry of readdirSync(dir, {
487
+ withFileTypes: true,
488
+ recursive: true
489
+ })) {
490
+ if (!entry.isFile()) continue;
491
+ const name = entry.name;
492
+ if (name.startsWith("_") || name.startsWith("layout.")) continue;
493
+ if (name.endsWith(".vue") && !name.includes(".island.")) return true;
494
+ }
495
+ } catch {}
496
+ return false;
497
+ }
498
+ function pagesPlugin(pagesDir, options) {
499
+ let pageScan = null;
500
+ let viteConfig;
501
+ const root = dirname(pagesDir);
502
+ return [{
503
+ name: "void-vue:pages-transform",
504
+ enforce: "pre",
505
+ transform: {
506
+ filter: { id: /\.vue$/ },
507
+ handler(code, id) {
508
+ if (!isVuePageFile(id, pagesDir)) return;
509
+ const transformed = stripDefinePropsTypeArgument(code);
510
+ if (!transformed) return;
511
+ return {
512
+ code: transformed,
513
+ map: { mappings: "" }
514
+ };
515
+ }
516
+ },
517
+ handleHotUpdate: {
518
+ order: "pre",
519
+ handler(ctx) {
520
+ if (!isVuePageFile(ctx.file, pagesDir)) return;
521
+ const read = ctx.read;
522
+ ctx.read = async () => {
523
+ const code = await read();
524
+ return stripDefinePropsTypeArgument(code) ?? code;
525
+ };
526
+ }
527
+ }
528
+ }, {
529
+ name: "void-vue:pages",
530
+ async buildStart() {
531
+ if (existsSync(pagesDir)) pageScan = await scanPages(root);
532
+ },
533
+ resolveId: {
534
+ filter: { id: /^virtual:void-pages-(renderer|client)$/ },
535
+ handler(id) {
536
+ return "\0" + id;
537
+ }
538
+ },
539
+ load: {
540
+ filter: { id: /^\0virtual:void-pages-(renderer|client)$/ },
541
+ handler(id) {
542
+ if (id === "\0" + RENDERER_ID) {
543
+ if (!pageScan) return "export function renderPage() { throw new Error('No pages found'); }";
544
+ return generateRendererModule(pageScan, pagesDir);
545
+ }
546
+ if (id === "\0" + CLIENT_ENTRY_ID) {
547
+ if (!pageScan) return "";
548
+ return generateClientEntry(pageScan, pagesDir, options?.viewTransitions, options?.prefetch, resolveStaticPageDataBuildOptions(root, { publicDir: viteConfig?.publicDir }));
549
+ }
550
+ }
551
+ },
552
+ configResolved(config) {
553
+ viteConfig = config;
554
+ },
555
+ config(_, env) {
556
+ if (!existsSync(pagesDir)) return;
557
+ if (env.command === "serve") return { optimizeDeps: { include: ["vue"] } };
558
+ if (!hasNonIslandPages(pagesDir)) return;
559
+ return { environments: { client: { build: {
560
+ manifest: true,
561
+ rollupOptions: { input: { "pages-client": CLIENT_ENTRY_ID } }
562
+ } } } };
563
+ }
564
+ }];
565
+ }
566
+ function generateRendererModule(scan, pagesDir) {
567
+ return `
568
+ import { createSSRApp, h, reactive, provide } from "vue";
569
+ import { renderToString } from "vue/server-renderer";
570
+ import { createSsrRouter, idleNavigationState } from "void/pages-client";
571
+ import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from "void/pages-head";
572
+ import { serializePageData } from "void/pages-server";
573
+
574
+ ${generateComponentManifest(scan, pagesDir)}
575
+
576
+ function patchProps(comp, props) {
577
+ if (comp.__voidPatched) return;
578
+ comp.props = Object.keys(props);
579
+ comp.__voidPatched = true;
580
+ }
581
+
582
+ export async function renderPage(pageObj, assetTags) {
583
+ const PageComponent = (await components[pageObj.component]()).default;
584
+ const layoutIds = layoutTree[pageObj.component] || [];
585
+ const layoutComponents = await Promise.all(
586
+ layoutIds.map(async (id) => (await components[id]()).default)
587
+ );
588
+
589
+ const app = createSSRApp({
590
+ setup() {
591
+ provide("__void_shared", reactive(pageObj.shared || {}));
592
+ provide("__void_errors", reactive(pageObj.errors || {}));
593
+ provide("__void_router", createSsrRouter(pageObj.url || "/"));
594
+ provide("__void_navigation", idleNavigationState());
595
+ return () => {
596
+ patchProps(PageComponent, pageObj.props);
597
+ let vnode = h(PageComponent, pageObj.props);
598
+ for (let i = layoutComponents.length - 1; i >= 0; i--) {
599
+ const inner = vnode;
600
+ vnode = h(layoutComponents[i], null, { default: () => inner });
601
+ }
602
+ return vnode;
603
+ };
604
+ }
605
+ });
606
+
607
+ const html = await renderToString(app);
608
+ const pageData = serializePageData(pageObj);
609
+ const headHtml = pageObj.head ? renderHeadToString(pageObj.head) : "";
610
+ const htmlAttrs = pageObj.head ? renderHtmlAttrs(pageObj.head) : "";
611
+ const bodyAttrs = pageObj.head ? renderBodyAttrs(pageObj.head) : "";
612
+
613
+ return \`<!doctype html>
614
+ <html\${htmlAttrs}>
615
+ <head>\${headHtml}\${assetTags.css}\${assetTags.preloads}</head>
616
+ <body\${bodyAttrs}>
617
+ <script id="__VOID_PAGE_DATA__" type="application/json">\${pageData}<\/script>
618
+ <div id="app">\${html}</div>
619
+ \${assetTags.body}
620
+ </body>
621
+ </html>\`;
622
+ }
623
+ `;
624
+ }
625
+ function generateClientEntry(scan, pagesDir, viewTransitions, prefetch, staticPageData) {
626
+ return `
627
+ import { createSSRApp, h, reactive, provide, shallowRef, nextTick, ref } from "vue";
628
+ import { createDeferred, resolveDeferred, rejectDeferred } from "@void/vue/deferred";
629
+ import { setActionRouter } from "@void/vue";
630
+ import { createRouterFacade, createVoidRouter, idleNavigationState } from "void/pages-client";
631
+ import { parseCacheFor } from "void/pages-prefetch";
632
+
633
+ ${generateComponentManifest(scan, pagesDir)}
634
+
635
+ const shared = reactive({});
636
+ const errors = reactive({});
637
+ const currentComponent = shallowRef(null);
638
+ const currentLayouts = shallowRef([]);
639
+ const currentProps = shallowRef({});
640
+ const routeUrl = ref(window.location.pathname + window.location.search + window.location.hash);
641
+ const navigation = reactive(idleNavigationState());
642
+
643
+ function patchProps(comp, props) {
644
+ if (comp.__voidPatched) return;
645
+ comp.props = Object.keys(props);
646
+ comp.__voidPatched = true;
647
+ }
648
+
649
+ const { router, initialPageData, initialComponent, initialLayouts, start } =
650
+ await createVoidRouter({
651
+ adapter: {
652
+ createDeferred: () => createDeferred(),
653
+ resolveDeferred(ref, value) { resolveDeferred(ref, value); return ref; },
654
+ rejectDeferred(ref, error) { rejectDeferred(ref, error); return ref; },
655
+ isLoading: (ref) => ref.loading,
656
+ applyUpdate(pageData, comp, layouts) {
657
+ Object.assign(shared, pageData.shared || {});
658
+ for (const key of Object.keys(errors)) delete errors[key];
659
+ Object.assign(errors, pageData.errors || {});
660
+ currentProps.value = pageData.props;
661
+ currentLayouts.value = layouts;
662
+ currentComponent.value = comp;
663
+ return nextTick();
664
+ },
665
+ },
666
+ components, layoutTree, routeMeta, matchRoute,
667
+ staticPageData: ${!!staticPageData?.enabled},
668
+ staticPageDataFastPath: ${!!staticPageData?.fastPath},
669
+ viewTransitions: ${!!viewTransitions},
670
+ prefetchHoverDelay: ${prefetch?.hoverDelay ?? 75},
671
+ prefetchDefaultCacheFor: parseCacheFor(${JSON.stringify(prefetch?.cacheFor ?? "30s")}),
672
+ onRouteChange(url) {
673
+ routeUrl.value = url;
674
+ },
675
+ onNavigationChange(next) {
676
+ navigation.state = next.state;
677
+ navigation.location = next.location;
678
+ navigation.method = next.method;
679
+ },
680
+ });
681
+
682
+ const reactiveRouter = createRouterFacade(router, () => routeUrl.value);
683
+
684
+ setActionRouter(reactiveRouter);
685
+
686
+ Object.assign(shared, initialPageData.shared || {});
687
+ Object.assign(errors, initialPageData.errors || {});
688
+ currentProps.value = initialPageData.props;
689
+ currentComponent.value = initialComponent;
690
+ currentLayouts.value = initialLayouts;
691
+
692
+ const app = createSSRApp({
693
+ setup() {
694
+ provide("__void_shared", shared);
695
+ provide("__void_errors", errors);
696
+ provide("__void_router", reactiveRouter);
697
+ provide("__void_navigation", navigation);
698
+
699
+ return () => {
700
+ if (!currentComponent.value) return null;
701
+ patchProps(currentComponent.value, currentProps.value);
702
+ let vnode = h(currentComponent.value, currentProps.value);
703
+ for (let i = currentLayouts.value.length - 1; i >= 0; i--) {
704
+ const inner = vnode;
705
+ vnode = h(currentLayouts.value[i], null, { default: () => inner });
706
+ }
707
+ return vnode;
708
+ };
709
+ }
710
+ });
711
+
712
+ app.mount("#app");
713
+ document.getElementById("app").setAttribute("data-hydrated", "true");
714
+ export { reactiveRouter as router };
715
+ start();
716
+ `;
717
+ }
718
+ //#endregion
719
+ //#region src/plugin.ts
720
+ function voidVue(options) {
721
+ const pagesDir = join(process.cwd(), "pages");
722
+ return [
723
+ vue(options?.vue),
724
+ ...pagesPlugin(pagesDir, { viewTransitions: options?.viewTransitions }),
725
+ ...islandsPlugin(pagesDir)
726
+ ];
727
+ }
728
+ //#endregion
729
+ export { voidVue };