noofpi 0.0.0-stage → 1.1.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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -2
  3. package/bin/noofpi.mjs +2 -0
  4. package/client.d.ts +79 -0
  5. package/dist/build-63DMFZJY.js +48 -0
  6. package/dist/chunk-2XCZWFIQ.js +253 -0
  7. package/dist/chunk-6OWKWAIW.js +68 -0
  8. package/dist/chunk-ELXCFUA4.js +97 -0
  9. package/dist/chunk-EZPJF4D4.js +314 -0
  10. package/dist/chunk-FIJJ3EGL.js +353 -0
  11. package/dist/chunk-G35DW4NA.js +129 -0
  12. package/dist/chunk-KGZP2RCF.js +51 -0
  13. package/dist/chunk-MTWSTW7V.js +44 -0
  14. package/dist/chunk-MTXQR32N.js +8 -0
  15. package/dist/chunk-NALDZ3PS.js +90 -0
  16. package/dist/chunk-NX6BO7UB.js +284 -0
  17. package/dist/chunk-SSJ2KKBZ.js +996 -0
  18. package/dist/chunk-WX2V6EYH.js +102 -0
  19. package/dist/chunk-X34Y6ESE.js +810 -0
  20. package/dist/chunk-Y3NBZ6DW.js +55 -0
  21. package/dist/chunk-YZAZ7IWK.js +27 -0
  22. package/dist/cli.js +93 -0
  23. package/dist/dev-USSN6KFV.js +149 -0
  24. package/dist/devtools-KTDSD5PR.js +564 -0
  25. package/dist/images-BNwTAi50.d.ts +36 -0
  26. package/dist/index.d.ts +115 -0
  27. package/dist/index.js +15 -0
  28. package/dist/route-rules-COilNsVT.d.ts +127 -0
  29. package/dist/runtime/default-app.js +15 -0
  30. package/dist/runtime/entry-client.js +70 -0
  31. package/dist/runtime/entry-server.js +107 -0
  32. package/dist/runtime/index.d.ts +523 -0
  33. package/dist/runtime/index.js +224 -0
  34. package/dist/runtime/routes.js +14 -0
  35. package/dist/server/bun.js +47 -0
  36. package/dist/server/index.d.ts +109 -0
  37. package/dist/server/index.js +48 -0
  38. package/dist/server/node.js +15 -0
  39. package/dist/start-U6A3PBRI.js +61 -0
  40. package/dist/validation-ClXd_DAW.d.ts +159 -0
  41. package/package.json +101 -4
@@ -0,0 +1,996 @@
1
+ import {
2
+ toPublicConfig,
3
+ toServerConfig,
4
+ variantWidths
5
+ } from "./chunk-NX6BO7UB.js";
6
+ import {
7
+ SSR_OUTLET
8
+ } from "./chunk-MTXQR32N.js";
9
+ import {
10
+ applyHead,
11
+ resolveHead
12
+ } from "./chunk-G35DW4NA.js";
13
+ import {
14
+ filePathToRoute
15
+ } from "./chunk-Y3NBZ6DW.js";
16
+
17
+ // src/fonts/index.ts
18
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
19
+ import path6 from "path";
20
+
21
+ // src/fonts/css.ts
22
+ import path from "path";
23
+ import { normalizePath } from "vite";
24
+ var quote = (value) => JSON.stringify(value);
25
+ function fontStack(family) {
26
+ return [quote(family.name), ...family.fallback].join(", ");
27
+ }
28
+ function generateFontCss(fonts, cssDir, tailwind) {
29
+ const rules = [];
30
+ for (const { family, faces } of fonts) {
31
+ for (const face of faces) {
32
+ const src = face.sources.map(({ file, format }) => {
33
+ const relative = normalizePath(path.relative(cssDir, file));
34
+ const url = relative.startsWith(".") ? relative : `./${relative}`;
35
+ return `url(${quote(url)}) format(${quote(format)})`;
36
+ }).join(", ");
37
+ rules.push(
38
+ [
39
+ "@font-face {",
40
+ ` font-family: ${quote(family.name)};`,
41
+ ` font-style: ${face.style};`,
42
+ ` font-weight: ${face.weight};`,
43
+ ` font-display: ${family.display};`,
44
+ ` src: ${src};`,
45
+ face.unicodeRange ? ` unicode-range: ${face.unicodeRange};` : "",
46
+ "}"
47
+ ].filter(Boolean).join("\n")
48
+ );
49
+ }
50
+ }
51
+ const variables = fonts.map(({ family }) => ` --font-${family.alias}: ${fontStack(family)};`).join("\n");
52
+ const css = rules.join("\n\n") + "\n";
53
+ if (!variables) return { css, theme: "" };
54
+ return tailwind ? { css, theme: `@theme {
55
+ ${variables}
56
+ }
57
+ ` } : { css: `${css}
58
+ :root {
59
+ ${variables}
60
+ }
61
+ `, theme: "" };
62
+ }
63
+
64
+ // src/fonts/providers/google.ts
65
+ import path4 from "path";
66
+
67
+ // src/fonts/providers/cache.ts
68
+ import { createHash } from "crypto";
69
+ import { existsSync } from "fs";
70
+ import { mkdir, readFile, rename, writeFile } from "fs/promises";
71
+ import path2 from "path";
72
+ var TIMEOUT_MS = 3e4;
73
+ function cachePath(context, url, ext) {
74
+ const hash = createHash("sha1").update(url).digest("hex").slice(0, 16);
75
+ return path2.join(context.cacheDir, `${hash}${ext}`);
76
+ }
77
+ async function download(context, url, file, headers) {
78
+ const response = await context.fetch(url, {
79
+ headers,
80
+ signal: AbortSignal.timeout(TIMEOUT_MS)
81
+ });
82
+ if (!response.ok) {
83
+ throw new Error(`${response.status} ${response.statusText} (${url})`);
84
+ }
85
+ await mkdir(context.cacheDir, { recursive: true });
86
+ const temp = `${file}.${process.pid}.tmp`;
87
+ await writeFile(temp, Buffer.from(await response.arrayBuffer()));
88
+ await rename(temp, file);
89
+ }
90
+ var inflight = /* @__PURE__ */ new Map();
91
+ async function cachedFile(context, url, ext, headers) {
92
+ const file = cachePath(context, url, ext);
93
+ if (existsSync(file)) return file;
94
+ let pending = inflight.get(file);
95
+ if (!pending) {
96
+ pending = download(context, url, file, headers).finally(
97
+ () => inflight.delete(file)
98
+ );
99
+ inflight.set(file, pending);
100
+ }
101
+ await pending;
102
+ return file;
103
+ }
104
+ async function cachedText(context, url, headers) {
105
+ return readFile(await cachedFile(context, url, ".css", headers), "utf-8");
106
+ }
107
+
108
+ // src/fonts/providers/format.ts
109
+ import path3 from "path";
110
+ var FORMATS = {
111
+ ".woff2": "woff2",
112
+ ".woff": "woff",
113
+ ".ttf": "truetype",
114
+ ".otf": "opentype"
115
+ };
116
+ function formatOf(file) {
117
+ return FORMATS[path3.extname(file).toLowerCase()];
118
+ }
119
+
120
+ // src/fonts/providers/google.ts
121
+ var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
122
+ function googleCssUrl(family) {
123
+ const weights = family.weights.map((w) => w.replace(" ", "..")).sort((a, b) => parseInt(a) - parseInt(b));
124
+ const italic = family.styles.includes("italic");
125
+ const tuples = [];
126
+ for (const style of ["normal", "italic"]) {
127
+ if (!family.styles.includes(style)) continue;
128
+ for (const weight of weights) {
129
+ tuples.push(italic ? `${style === "italic" ? 1 : 0},${weight}` : weight);
130
+ }
131
+ }
132
+ const name = encodeURIComponent(family.name).replace(/%20/g, "+");
133
+ const axes = italic ? "ital,wght" : "wght";
134
+ return `https://fonts.googleapis.com/css2?family=${name}:${axes}@${tuples.join(";")}&display=swap`;
135
+ }
136
+ function parseGoogleCss(css) {
137
+ const faces = [];
138
+ const block = /(?:\/\*\s*([^*]*?)\s*\*\/\s*)?@font-face\s*\{([^}]*)\}/g;
139
+ for (const match of css.matchAll(block)) {
140
+ const declarations = /* @__PURE__ */ new Map();
141
+ for (const d of match[2].matchAll(/([\w-]+)\s*:\s*([^;]+);?/g)) {
142
+ declarations.set(d[1].toLowerCase(), d[2].trim());
143
+ }
144
+ const sources = [
145
+ ...(declarations.get("src") ?? "").matchAll(
146
+ /url\(\s*(['"]?)([^)'"]+)\1\s*\)(?:\s*format\(\s*['"]?([\w-]+)['"]?\s*\))?/g
147
+ )
148
+ ].map((s) => ({ url: s[2], format: s[3] }));
149
+ if (sources.length === 0) continue;
150
+ faces.push({
151
+ subset: match[1] || void 0,
152
+ weight: declarations.get("font-weight") ?? "400",
153
+ style: declarations.get("font-style") === "italic" ? "italic" : "normal",
154
+ unicodeRange: declarations.get("unicode-range"),
155
+ sources
156
+ });
157
+ }
158
+ return faces;
159
+ }
160
+ var googleProvider = {
161
+ async resolve(family, context) {
162
+ const url = googleCssUrl(family);
163
+ let css;
164
+ try {
165
+ css = await cachedText(context, url, { "user-agent": USER_AGENT });
166
+ } catch (error) {
167
+ throw new Error(
168
+ `[noofpi] Could not load Google font "${family.name}": ${error.message}`,
169
+ { cause: error }
170
+ );
171
+ }
172
+ const all = parseGoogleCss(css);
173
+ const faces = all.filter(
174
+ (face) => !face.subset || family.subsets.length === 0 || family.subsets.includes(face.subset)
175
+ );
176
+ if (faces.length === 0) {
177
+ const available = [...new Set(all.map((f) => f.subset))].join(", ");
178
+ throw new Error(
179
+ `[noofpi] Google font "${family.name}" has no subset matching [${family.subsets.join(", ")}] (available: ${available || "none"})`
180
+ );
181
+ }
182
+ return Promise.all(
183
+ faces.map(async (face) => {
184
+ const sources = await Promise.all(
185
+ face.sources.map(async (source) => {
186
+ const ext = path4.extname(new URL(source.url).pathname) || ".woff2";
187
+ try {
188
+ return {
189
+ file: await cachedFile(context, source.url, ext),
190
+ format: source.format ?? formatOf(ext) ?? "woff2"
191
+ };
192
+ } catch (error) {
193
+ throw new Error(
194
+ `[noofpi] Could not download Google font "${family.name}": ${error.message}`,
195
+ { cause: error }
196
+ );
197
+ }
198
+ })
199
+ );
200
+ return {
201
+ weight: face.weight,
202
+ style: face.style,
203
+ unicodeRange: face.unicodeRange,
204
+ sources
205
+ };
206
+ })
207
+ );
208
+ }
209
+ };
210
+
211
+ // src/fonts/providers/local.ts
212
+ import { existsSync as existsSync2 } from "fs";
213
+ import path5 from "path";
214
+ var localProvider = {
215
+ async resolve(family, { root }) {
216
+ return family.files.map((file) => {
217
+ const full = path5.resolve(root, file.src.replace(/^[\\/]+/, ""));
218
+ const format = formatOf(full);
219
+ if (!format) {
220
+ throw new Error(
221
+ `[noofpi] Local font "${family.name}": unsupported file type "${file.src}" (use woff2, woff, ttf or otf)`
222
+ );
223
+ }
224
+ if (!existsSync2(full)) {
225
+ throw new Error(
226
+ `[noofpi] Local font "${family.name}": file not found "${file.src}" (relative to ${root})`
227
+ );
228
+ }
229
+ return {
230
+ weight: file.weight,
231
+ style: file.style,
232
+ sources: [{ file: full, format }]
233
+ };
234
+ });
235
+ }
236
+ };
237
+
238
+ // src/fonts/providers/index.ts
239
+ var providers = {
240
+ google: googleProvider,
241
+ local: localProvider
242
+ };
243
+
244
+ // src/fonts/index.ts
245
+ var NO_FONTS = { cssFile: void 0, theme: "" };
246
+ async function resolveFonts(root, config, fetchImpl = fetch) {
247
+ if (config.fonts.length === 0) return NO_FONTS;
248
+ const outDir = path6.join(root, ".noofpi");
249
+ const context = {
250
+ root,
251
+ cacheDir: path6.join(outDir, "fonts"),
252
+ fetch: fetchImpl
253
+ };
254
+ const fonts = await Promise.all(
255
+ config.fonts.map(async (family) => ({
256
+ family,
257
+ faces: await providers[family.provider].resolve(family, context)
258
+ }))
259
+ );
260
+ const { css, theme } = generateFontCss(fonts, outDir, config.tailwind);
261
+ const cssFile = path6.join(outDir, "fonts.css");
262
+ await mkdir2(outDir, { recursive: true });
263
+ await writeFile2(cssFile, css);
264
+ return { cssFile, theme };
265
+ }
266
+ var TAILWIND_IMPORT = /@import\s+(["'])tailwindcss(?:\/[^"']*)?\1/;
267
+ function fontThemePlugin(theme) {
268
+ return {
269
+ name: "noofpi:fonts-theme",
270
+ enforce: "pre",
271
+ transform(code, id) {
272
+ if (!id.split("?")[0].endsWith(".css") || !TAILWIND_IMPORT.test(code))
273
+ return;
274
+ return { code: `${code}
275
+ ${theme}`, map: null };
276
+ }
277
+ };
278
+ }
279
+
280
+ // src/vite/template.ts
281
+ function htmlTemplate(entry, stylesheets = []) {
282
+ const links = stylesheets.map((href) => `
283
+ <link rel="stylesheet" href="${href}" />`).join("");
284
+ return `<!doctype html>
285
+ <html lang="en">
286
+ <head>
287
+ <meta charset="UTF-8" />
288
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
289
+ <title>noofpi</title>${links}
290
+ </head>
291
+ <body>
292
+ <div id="app">${SSR_OUTLET}</div>
293
+ <script type="module" src="${entry}"></script>
294
+ </body>
295
+ </html>
296
+ `;
297
+ }
298
+
299
+ // src/vite/presets.ts
300
+ import { existsSync as existsSync3, readFileSync } from "fs";
301
+ import { mkdir as mkdir3, rm, writeFile as writeFile3 } from "fs/promises";
302
+ import path7 from "path";
303
+ var OUTPUT_DIR = ".output";
304
+ var HANDLER = `import { createHandler } from 'noofpi/server';
305
+ import * as mod from 'virtual:noofpi/server';
306
+ import template from 'virtual:noofpi/template';
307
+ const handler = createHandler({ load: async () => mod, getTemplate: async () => template });`;
308
+ var PORT_HOST = (port) => `const port = Number(process.env.PORT ?? ${port});
309
+ const host = process.env.HOST ?? '0.0.0.0';`;
310
+ var PUBLIC_DIR = `const publicDir = fileURLToPath(new URL('../public', import.meta.url));`;
311
+ function presetEntryCode(preset, config) {
312
+ const { port } = config.devServer;
313
+ switch (preset) {
314
+ case "bun":
315
+ return [
316
+ `import { fileURLToPath } from 'node:url';`,
317
+ `import { serveBun } from 'noofpi/server/bun';`,
318
+ HANDLER,
319
+ PUBLIC_DIR,
320
+ PORT_HOST(port),
321
+ `await serveBun({ publicDir, handler, port, host });`
322
+ ].join("\n");
323
+ case "cloudflare-worker":
324
+ return [
325
+ HANDLER,
326
+ `export default { fetch: (request, env) => handler(request, env) };`
327
+ ].join("\n");
328
+ case "cloudflare-pages":
329
+ return [
330
+ HANDLER,
331
+ // Pages serves static files through the ASSETS binding; everything else is a page or an API call
332
+ `const isFile = (request) => (request.method === 'GET' || request.method === 'HEAD') && /\\.[a-z0-9]+$/i.test(new URL(request.url).pathname);`,
333
+ `export default { fetch: (request, env) => isFile(request) && env.ASSETS ? env.ASSETS.fetch(request) : handler(request, env) };`
334
+ ].join("\n");
335
+ default:
336
+ return [
337
+ `import { fileURLToPath } from 'node:url';`,
338
+ `import { createNodeServer, listenNodeServer } from 'noofpi/server/node';`,
339
+ HANDLER,
340
+ PUBLIC_DIR,
341
+ PORT_HOST(port),
342
+ `await listenNodeServer(createNodeServer({ publicDir, handler }), port, host);`
343
+ ].join("\n");
344
+ }
345
+ }
346
+ function readBuiltTemplate(root) {
347
+ const file = path7.join(root, OUTPUT_DIR, "public/index.html");
348
+ if (!existsSync3(file))
349
+ throw new Error("[noofpi] The client build is missing (no index.html).");
350
+ return readFileSync(file, "utf-8");
351
+ }
352
+ function serverBuildConfig(root, preset) {
353
+ const outDir = path7.join(root, OUTPUT_DIR);
354
+ switch (preset) {
355
+ case "cloudflare-worker":
356
+ return {
357
+ ssr: { target: "webworker", noExternal: true },
358
+ build: {
359
+ ssr: true,
360
+ outDir: path7.join(outDir, "server"),
361
+ emptyOutDir: true,
362
+ rollupOptions: {
363
+ input: "virtual:noofpi/entry",
364
+ output: { entryFileNames: "index.mjs", inlineDynamicImports: true }
365
+ }
366
+ }
367
+ };
368
+ case "cloudflare-pages":
369
+ return {
370
+ ssr: { target: "webworker", noExternal: true },
371
+ build: {
372
+ ssr: true,
373
+ // The Worker is added to the static files (the client build is already there)
374
+ outDir: path7.join(outDir, "public"),
375
+ emptyOutDir: false,
376
+ rollupOptions: {
377
+ input: "virtual:noofpi/entry",
378
+ output: {
379
+ entryFileNames: "_worker.js",
380
+ inlineDynamicImports: true
381
+ }
382
+ }
383
+ }
384
+ };
385
+ default:
386
+ return {
387
+ build: {
388
+ ssr: true,
389
+ outDir: path7.join(outDir, "server"),
390
+ emptyOutDir: true,
391
+ rollupOptions: {
392
+ // `index` is what `noofpi start` loads, `start` runs without the CLI
393
+ input: {
394
+ index: "virtual:noofpi/server",
395
+ start: "virtual:noofpi/entry"
396
+ },
397
+ output: {
398
+ entryFileNames: "[name].mjs",
399
+ chunkFileNames: "assets/[name]-[hash].mjs"
400
+ }
401
+ }
402
+ }
403
+ };
404
+ }
405
+ }
406
+ function readPackageName(root) {
407
+ try {
408
+ const pkg = JSON.parse(
409
+ readFileSync(path7.join(root, "package.json"), "utf-8")
410
+ );
411
+ return pkg.name;
412
+ } catch {
413
+ return void 0;
414
+ }
415
+ }
416
+ function workerName(root) {
417
+ const name = (readPackageName(root) ?? path7.basename(root)).replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
418
+ return name || "noofpi-app";
419
+ }
420
+ function dockerfile(root, port) {
421
+ const bun = existsSync3(path7.join(root, "bun.lock")) || existsSync3(path7.join(root, "bun.lockb"));
422
+ if (bun) {
423
+ return `FROM oven/bun:1
424
+ WORKDIR /app
425
+ COPY package.json bun.lock* ./
426
+ RUN bun install${existsSync3(path7.join(root, "bun.lock")) ? " --frozen-lockfile" : ""}
427
+ COPY .output .output
428
+ USER bun
429
+ ENV NODE_ENV=production PORT=${port}
430
+ EXPOSE ${port}
431
+ CMD ["bun", ".output/server/start.mjs"]
432
+ `;
433
+ }
434
+ const lock = existsSync3(path7.join(root, "package-lock.json"));
435
+ return `FROM node:22-alpine
436
+ WORKDIR /app
437
+ COPY package.json package-lock.json* ./
438
+ RUN ${lock ? "npm ci" : "npm install"}
439
+ COPY .output .output
440
+ USER node
441
+ ENV NODE_ENV=production PORT=${port}
442
+ EXPOSE ${port}
443
+ CMD ["node", ".output/server/start.mjs"]
444
+ `;
445
+ }
446
+ async function finishPresetBuild(root, config, preset) {
447
+ const outDir = path7.join(root, OUTPUT_DIR);
448
+ const json = (value) => JSON.stringify(value, null, 2) + "\n";
449
+ switch (preset) {
450
+ case "cloudflare-worker":
451
+ await rm(path7.join(outDir, "public/index.html"), { force: true });
452
+ await writeFile3(
453
+ path7.join(outDir, "wrangler.json"),
454
+ json({
455
+ name: workerName(root),
456
+ main: "server/index.mjs",
457
+ compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
458
+ compatibility_flags: ["nodejs_compat"],
459
+ assets: { directory: "public" }
460
+ })
461
+ );
462
+ return "deploy with `wrangler deploy -c .output/wrangler.json`";
463
+ case "cloudflare-pages":
464
+ await rm(path7.join(outDir, "public/index.html"), { force: true });
465
+ await writeFile3(
466
+ path7.join(outDir, "public/_routes.json"),
467
+ json({ version: 1, include: ["/*"], exclude: ["/assets/*"] })
468
+ );
469
+ return "deploy with `wrangler pages deploy .output/public`";
470
+ case "github-pages": {
471
+ const index = path7.join(outDir, "public/index.html");
472
+ const html = applyHead(
473
+ readFileSync(index, "utf-8"),
474
+ resolveHead(config.head)
475
+ ).replace(SSR_OUTLET, () => "");
476
+ await writeFile3(index, html);
477
+ await writeFile3(path7.join(outDir, "public/404.html"), html);
478
+ await writeFile3(path7.join(outDir, "public/.nojekyll"), "");
479
+ return "publish `.output/public` to GitHub Pages (set `vite.base` to `/<repo>/` for project sites)";
480
+ }
481
+ case "docker":
482
+ await mkdir3(outDir, { recursive: true });
483
+ await writeFile3(
484
+ path7.join(outDir, "Dockerfile"),
485
+ dockerfile(root, config.devServer.port)
486
+ );
487
+ return "build with `docker build -f .output/Dockerfile -t my-app .`";
488
+ case "bun":
489
+ return "run with `bun .output/server/start.mjs`";
490
+ default:
491
+ return "run with `noofpi start` or `node .output/server/start.mjs`";
492
+ }
493
+ }
494
+
495
+ // src/vite/plugin.ts
496
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
497
+ import path10 from "path";
498
+ import { normalizePath as normalizePath2 } from "vite";
499
+
500
+ // src/vite/layouts.ts
501
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync2 } from "fs";
502
+ import path8 from "path";
503
+ var USE_LAYOUT = /\buseLayout\(\s*(?:(['"`])([^'"`$\n]+)\1|(false))\s*\)/;
504
+ function extractLayout(source) {
505
+ const match = USE_LAYOUT.exec(source);
506
+ if (!match) return void 0;
507
+ return match[3] ? false : match[2];
508
+ }
509
+ function scanPages(root, extract) {
510
+ const pagesDir = path8.join(root, "app/pages");
511
+ const result = {};
512
+ const walk = (dir) => {
513
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
514
+ const full = path8.join(dir, entry.name);
515
+ if (entry.isDirectory()) walk(full);
516
+ else if (entry.name.endsWith(".vue")) {
517
+ let value;
518
+ try {
519
+ value = extract(readFileSync2(full, "utf-8"));
520
+ } catch (error) {
521
+ throw new Error(
522
+ `[noofpi] ${path8.relative(root, full)}: ${error.message}`
523
+ );
524
+ }
525
+ if (value !== void 0)
526
+ result["/" + path8.relative(root, full).split(path8.sep).join("/")] = value;
527
+ }
528
+ }
529
+ };
530
+ if (existsSync4(pagesDir)) walk(pagesDir);
531
+ return result;
532
+ }
533
+ function scanPageLayouts(root) {
534
+ return scanPages(root, extractLayout);
535
+ }
536
+
537
+ // src/vite/middleware.ts
538
+ var USE_MIDDLEWARE = /^\s*\(\s*(?:(['"`])([^'"`$\n]+)\1|\[([^\]]*)\])\s*\)/;
539
+ var CALL = /\buseMiddleware\b(?=\s*\()/g;
540
+ var LITERAL = /^(['"`])([^'"`$\n]+)\1$/;
541
+ var stripComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:\\])\/\/.*$/gm, "$1");
542
+ function extractMiddleware(source) {
543
+ const code = stripComments(source);
544
+ const calls = [...code.matchAll(CALL)];
545
+ if (!calls.length) return void 0;
546
+ if (calls.length > 1)
547
+ throw new Error("useMiddleware() must be called only once per page");
548
+ const rest = code.slice(calls[0].index + calls[0][0].length);
549
+ const match = USE_MIDDLEWARE.exec(rest);
550
+ const unreadable = new Error(
551
+ "useMiddleware() must be called with string literals, e.g. useMiddleware('auth')"
552
+ );
553
+ if (!match) throw unreadable;
554
+ if (match[2] !== void 0) return [match[2]];
555
+ const names = [];
556
+ for (const item of (match[3] ?? "").split(",")) {
557
+ if (!item.trim()) continue;
558
+ const literal = LITERAL.exec(item.trim());
559
+ if (!literal) throw unreadable;
560
+ names.push(literal[2]);
561
+ }
562
+ return names;
563
+ }
564
+ function scanPageMiddleware(root) {
565
+ return scanPages(root, extractMiddleware);
566
+ }
567
+
568
+ // src/vite/types.ts
569
+ import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
570
+ import path9 from "path";
571
+ function doofpiTypes() {
572
+ return [
573
+ "// Generated by noofpi, do not edit",
574
+ 'import type * as server from "../server/doofpi";',
575
+ "",
576
+ 'declare module "noofpi/runtime" {',
577
+ " interface Register {",
578
+ " routes: typeof server extends { routes: infer R } ? R : any;",
579
+ " }",
580
+ "}",
581
+ ""
582
+ ].join("\n");
583
+ }
584
+ var PARAM = /:(\w+)(\(\.\*\)\*)?/g;
585
+ function paramsType(route) {
586
+ const fields = [...route.matchAll(PARAM)].map(
587
+ ([, name, catchAll]) => `${name}: ${catchAll ? "string[]" : "string | number"}`
588
+ );
589
+ return fields.length ? `{ ${fields.join("; ")} }` : "{}";
590
+ }
591
+ function routeTypes(routes) {
592
+ return [
593
+ "// Generated by noofpi, do not edit",
594
+ 'declare module "noofpi/runtime" {',
595
+ " interface Register {",
596
+ " pages: {",
597
+ ...[...routes].sort().map((route) => ` ${JSON.stringify(route)}: ${paramsType(route)};`),
598
+ " };",
599
+ " }",
600
+ "}",
601
+ "export {};",
602
+ ""
603
+ ].join("\n");
604
+ }
605
+ function writeRouteTypes(root) {
606
+ const routes = Object.keys(scanPages(root, () => true)).map(filePathToRoute);
607
+ const file = path9.join(root, ".noofpi/routes.d.ts");
608
+ const content = routeTypes(routes);
609
+ if (existsSync5(file) && readFileSync3(file, "utf8") === content) return;
610
+ mkdirSync(path9.dirname(file), { recursive: true });
611
+ writeFileSync(file, content);
612
+ }
613
+ function findLocaleFile(root, locale) {
614
+ return ["ts", "js", "json"].map((extension) => `app/locales/${locale}.${extension}`).find((file) => existsSync5(path9.join(root, file)));
615
+ }
616
+ function i18nTypes(i18n, defaultLocaleFile) {
617
+ const specifier = defaultLocaleFile?.replace(/\.(ts|js)$/, "");
618
+ return [
619
+ "// Generated by noofpi, do not edit",
620
+ ...specifier ? [`import type messages from ${JSON.stringify("../" + specifier)};`] : [],
621
+ "",
622
+ 'declare module "noofpi/runtime" {',
623
+ " interface Register {",
624
+ ...specifier ? [" messages: typeof messages;"] : [],
625
+ ` locales: ${i18n.locales.map((locale) => JSON.stringify(locale)).join(" | ")};`,
626
+ " }",
627
+ "}",
628
+ "export {};",
629
+ ""
630
+ ].join("\n");
631
+ }
632
+ function writeI18nTypes(root, i18n) {
633
+ if (!i18n) return;
634
+ const file = path9.join(root, ".noofpi/i18n.d.ts");
635
+ const content = i18nTypes(i18n, findLocaleFile(root, i18n.defaultLocale));
636
+ if (existsSync5(file) && readFileSync3(file, "utf8") === content) return;
637
+ mkdirSync(path9.dirname(file), { recursive: true });
638
+ writeFileSync(file, content);
639
+ }
640
+ function writeDoofpiTypes(root) {
641
+ if (!existsSync5(path9.join(root, "server/doofpi.ts"))) return;
642
+ const file = path9.join(root, ".noofpi/doofpi.d.ts");
643
+ const content = doofpiTypes();
644
+ if (existsSync5(file) && readFileSync3(file, "utf8") === content) return;
645
+ mkdirSync(path9.dirname(file), { recursive: true });
646
+ writeFileSync(file, content);
647
+ }
648
+
649
+ // src/vite/plugin.ts
650
+ var PREFIX = "virtual:noofpi/";
651
+ var VIRTUAL_IDS = [
652
+ "config",
653
+ "i18n",
654
+ "routes",
655
+ "layouts",
656
+ "middleware",
657
+ "plugins",
658
+ "app-root",
659
+ "error",
660
+ "entry-client",
661
+ "server",
662
+ "entry",
663
+ "template"
664
+ ].map((name) => PREFIX + name);
665
+ var DEV_ENTRY = "/@id/__x00__virtual:noofpi/entry-client";
666
+ function resolveCss(root, config, fonts) {
667
+ const generated = fonts.cssFile ? [fonts.cssFile] : [];
668
+ if (config.css) {
669
+ return [
670
+ ...generated,
671
+ ...config.css.map((file) => path10.resolve(root, file))
672
+ ];
673
+ }
674
+ const main = path10.join(root, "app/assets/main.css");
675
+ if (existsSync6(main)) return [...generated, main];
676
+ if (!config.tailwind) return generated;
677
+ const tailwindEntry = path10.join(root, ".noofpi/tailwind.css");
678
+ mkdirSync2(path10.dirname(tailwindEntry), { recursive: true });
679
+ writeFileSync2(tailwindEntry, '@import "tailwindcss";\n');
680
+ return [...generated, tailwindEntry];
681
+ }
682
+ function indexHtmlPath(root) {
683
+ return normalizePath2(path10.join(root, "index.html"));
684
+ }
685
+ function noofpiPlugin(options) {
686
+ const { root, config, css } = options;
687
+ const htmlId = indexHtmlPath(root);
688
+ const file = (relative) => {
689
+ const full = path10.join(root, relative);
690
+ return existsSync6(full) ? normalizePath2(full) : void 0;
691
+ };
692
+ const imp = (target) => JSON.stringify(normalizePath2(target));
693
+ let scannedPages = "";
694
+ const scanPages2 = () => JSON.stringify([scanPageLayouts(root), scanPageMiddleware(root)]);
695
+ return {
696
+ name: "noofpi",
697
+ enforce: "pre",
698
+ buildStart() {
699
+ if (config.i18n) {
700
+ if (!findLocaleFile(root, config.i18n.defaultLocale))
701
+ this.error(
702
+ `[noofpi] i18n.defaultLocale "${config.i18n.defaultLocale}" has no messages: create app/locales/${config.i18n.defaultLocale}.ts`
703
+ );
704
+ for (const locale of config.i18n.locales)
705
+ if (!findLocaleFile(root, locale))
706
+ this.warn(
707
+ `[noofpi] i18n locale "${locale}" has no file app/locales/${locale}.ts, it falls back to "${config.i18n.defaultLocale}"`
708
+ );
709
+ }
710
+ writeDoofpiTypes(root);
711
+ writeRouteTypes(root);
712
+ writeI18nTypes(root, config.i18n);
713
+ },
714
+ // Page files added or removed change the typed `navigateTo()` paths, locale files the typed `t()` keys
715
+ configureServer(server) {
716
+ const onFile = (changed) => {
717
+ const normalized = normalizePath2(changed);
718
+ if (normalized.endsWith(".vue") && normalized.includes("/app/pages/"))
719
+ writeRouteTypes(root);
720
+ else if (normalized.includes("/app/locales/"))
721
+ writeI18nTypes(root, config.i18n);
722
+ };
723
+ server.watcher.on("add", onFile);
724
+ server.watcher.on("unlink", onFile);
725
+ },
726
+ // `useLayout()` / `useMiddleware()` literals are baked into the routes module, so it must be rebuilt when one changes
727
+ handleHotUpdate({ file: file2, server }) {
728
+ const changed = normalizePath2(file2);
729
+ if (!changed.endsWith(".vue") || !changed.includes("/app/pages/")) return;
730
+ if (scanPages2() === scannedPages) return;
731
+ for (const environment of Object.values(server.environments)) {
732
+ const mod = environment.moduleGraph.getModuleById(
733
+ "\0" + PREFIX + "routes"
734
+ );
735
+ if (mod) environment.moduleGraph.invalidateModule(mod);
736
+ }
737
+ server.ws.send({ type: "full-reload" });
738
+ return [];
739
+ },
740
+ resolveId(source) {
741
+ if (VIRTUAL_IDS.includes(source)) return "\0" + source;
742
+ if (source === htmlId) return htmlId;
743
+ },
744
+ load(id) {
745
+ if (id === htmlId) return htmlTemplate("virtual:noofpi/entry-client");
746
+ if (!id.startsWith("\0" + PREFIX)) return;
747
+ const isServerConfig = this.environment?.config.consumer === "server";
748
+ switch (id.slice(("\0" + PREFIX).length)) {
749
+ case "config":
750
+ return [
751
+ `export const publicConfig = ${JSON.stringify(toPublicConfig(config))};`,
752
+ `export const serverConfig = ${isServerConfig ? JSON.stringify(toServerConfig(config)) : "undefined"};`
753
+ ].join("\n");
754
+ case "i18n":
755
+ const glob = (eager) => `import.meta.glob('/app/locales/*.{ts,js,json}', { ${eager ? "eager: true, " : ""}import: 'default' })`;
756
+ return [
757
+ `export const i18nConfig = ${JSON.stringify(config.i18n)};`,
758
+ `export const messageFiles = ${config.i18n && isServerConfig ? glob(true) : "{}"};`,
759
+ `export const messageLoaders = ${config.i18n && !isServerConfig ? glob(false) : "{}"};`
760
+ ].join("\n");
761
+ case "routes": {
762
+ const layouts = scanPageLayouts(root);
763
+ const middleware = scanPageMiddleware(root);
764
+ scannedPages = JSON.stringify([layouts, middleware]);
765
+ return [
766
+ `import { createRoutes } from 'noofpi/runtime/routes';`,
767
+ `export default createRoutes(import.meta.glob('/app/pages/**/*.vue'), ${JSON.stringify(layouts)}, ${JSON.stringify(middleware)});`
768
+ ].join("\n");
769
+ }
770
+ case "layouts":
771
+ return [
772
+ `import { createLayouts } from 'noofpi/runtime/routes';`,
773
+ `export default createLayouts(import.meta.glob('/app/layouts/*.vue', { eager: true, import: 'default' }));`
774
+ ].join("\n");
775
+ case "middleware":
776
+ return `export default import.meta.glob('/app/middleware/*.{ts,js}', { eager: true, import: 'default' });`;
777
+ case "plugins":
778
+ return `export default import.meta.glob('/app/plugins/*.{ts,js}', { eager: true, import: 'default' });`;
779
+ case "app-root": {
780
+ const appVue = file("app/app.vue");
781
+ return appVue ? `export { default } from ${imp(appVue)};` : `export { default } from 'noofpi/runtime/default-app';`;
782
+ }
783
+ case "error": {
784
+ const errorVue = file("app/error.vue");
785
+ return errorVue ? `export { default } from ${imp(errorVue)};` : "export default undefined;";
786
+ }
787
+ case "entry-client":
788
+ return [
789
+ ...css.map((file2) => `import ${imp(file2)};`),
790
+ `import { mount } from 'noofpi/runtime/entry-client';`,
791
+ `mount();`
792
+ ].join("\n");
793
+ case "entry":
794
+ return presetEntryCode(config.build.preset, config);
795
+ case "template":
796
+ return `export default ${JSON.stringify(readBuiltTemplate(root))};`;
797
+ case "server": {
798
+ const userDoofpi = file("server/doofpi.ts");
799
+ const userProxy = file("server/proxy.ts");
800
+ const { ssr } = config;
801
+ return [
802
+ userDoofpi ? `import userDoofpi from ${imp(userDoofpi)};` : "",
803
+ userProxy ? `import userProxyHook from ${imp(userProxy)};` : "",
804
+ ssr ? `export { render } from 'noofpi/runtime/entry-server';` : "",
805
+ `export const config = ${JSON.stringify(toServerConfig(config))};`,
806
+ `export const doofpi = ${userDoofpi ? "userDoofpi" : "undefined"};`,
807
+ `export const proxyHook = ${userProxy ? "userProxyHook" : "undefined"};`,
808
+ `const serverMiddleware = import.meta.glob('/server/middleware/*.{ts,js}', { eager: true, import: 'default' });`,
809
+ `export const middleware = Object.keys(serverMiddleware).sort().map((file) => serverMiddleware[file]);`
810
+ ].filter(Boolean).join("\n");
811
+ }
812
+ }
813
+ }
814
+ };
815
+ }
816
+
817
+ // src/vite/config.ts
818
+ import path12 from "path";
819
+ import vue from "@vitejs/plugin-vue";
820
+ import tailwindcss from "@tailwindcss/vite";
821
+ import { mergeConfig } from "vite";
822
+
823
+ // src/vite/auto-imports.ts
824
+ import AutoImport from "unplugin-auto-import/vite";
825
+ import Components from "unplugin-vue-components/vite";
826
+ var RUNTIME_IMPORTS = [
827
+ "useAsyncData",
828
+ "useState",
829
+ "clearError",
830
+ "createError",
831
+ "showError",
832
+ "useError",
833
+ "useCookie",
834
+ "useCookies",
835
+ "useDoofpi",
836
+ "useDoofpiFetch",
837
+ "useDoofpiForm",
838
+ "useHead",
839
+ "useLayout",
840
+ "definePage",
841
+ "useLoaderData",
842
+ "useMiddleware",
843
+ "defineRouteMiddleware",
844
+ "defineNoofpiPlugin",
845
+ "navigateTo",
846
+ "useI18n",
847
+ "defineMessages"
848
+ ];
849
+ var RUNTIME_COMPONENTS = [
850
+ "ClientOnly",
851
+ "NoofpiImage",
852
+ "NoofpiLayout",
853
+ "NoofpiLink",
854
+ "NoofpiPage"
855
+ ];
856
+ function autoImportPlugins() {
857
+ return [
858
+ AutoImport({
859
+ imports: ["vue", "vue-router", { "noofpi/runtime": RUNTIME_IMPORTS }],
860
+ dirs: [
861
+ "app/composables",
862
+ "app/composables/*/index.{ts,js}",
863
+ "app/utils",
864
+ "app/utils/*/index.{ts,js}"
865
+ ],
866
+ include: [/\.[jt]sx?$/, /\.vue$/, /\.vue\?vue/],
867
+ dts: ".noofpi/auto-imports.d.ts"
868
+ }),
869
+ Components({
870
+ dirs: ["app/components"],
871
+ directoryAsNamespace: true,
872
+ resolvers: [
873
+ (name) => RUNTIME_COMPONENTS.includes(name) ? { name, from: "noofpi/runtime" } : void 0
874
+ ],
875
+ dts: ".noofpi/components.d.ts"
876
+ })
877
+ ];
878
+ }
879
+
880
+ // src/vite/images.ts
881
+ import { createHash as createHash2 } from "crypto";
882
+ import { readFile as readFile2 } from "fs/promises";
883
+ import path11 from "path";
884
+ var IMAGE_QUERY = /^(.+\.(?:jpe?g|png|webp|avif))\?image$/i;
885
+ async function processImage(file, images, options) {
886
+ const { default: sharp } = await import("sharp");
887
+ const input = await readFile2(file);
888
+ const metadata = await sharp(input).metadata();
889
+ const turned = (metadata.orientation ?? 1) >= 5;
890
+ const width = turned ? metadata.height : metadata.width;
891
+ const height = turned ? metadata.width : metadata.height;
892
+ if (!width || !height)
893
+ throw new Error(`[noofpi] could not read the size of ${file}`);
894
+ const image = { width, height, sources: [] };
895
+ const files = [];
896
+ if (!options.variants) return { image, files };
897
+ const hash = createHash2("sha256").update(input).update(JSON.stringify(images)).digest("hex").slice(0, 8);
898
+ const name = path11.basename(file, path11.extname(file)).replace(/[^\w.-]+/g, "-");
899
+ const widths = variantWidths(width, images.widths);
900
+ for (const format of images.formats) {
901
+ const srcset = [];
902
+ for (const target of widths) {
903
+ const fileName = `assets/${name}-${hash}-${target}w.${format}`;
904
+ srcset.push(`${options.base}${fileName} ${target}w`);
905
+ if (!options.emit) continue;
906
+ const resized = sharp(input).rotate().resize({ width: target, withoutEnlargement: true });
907
+ const data = await (format === "avif" ? resized.avif({ quality: images.quality }) : resized.webp({ quality: images.quality })).toBuffer();
908
+ files.push({ fileName, data });
909
+ }
910
+ image.sources.push({ type: `image/${format}`, srcset: srcset.join(", ") });
911
+ }
912
+ return { image, files };
913
+ }
914
+ function imagesPlugin(images) {
915
+ let base = "/";
916
+ let build = false;
917
+ return {
918
+ name: "noofpi:images",
919
+ enforce: "pre",
920
+ configResolved(config) {
921
+ build = config.command === "build";
922
+ base = config.base.startsWith("/") ? config.base.replace(/\/?$/, "/") : "/";
923
+ },
924
+ async load(id) {
925
+ const match = IMAGE_QUERY.exec(id);
926
+ if (!match) return;
927
+ const file = match[1];
928
+ this.addWatchFile(file);
929
+ const { image, files } = await processImage(file, images, {
930
+ base,
931
+ variants: build,
932
+ emit: build && this.environment?.config.consumer === "client"
933
+ });
934
+ for (const { fileName, data } of files)
935
+ this.emitFile({ type: "asset", fileName, source: data });
936
+ return [
937
+ `import src from ${JSON.stringify(file + "?url")};`,
938
+ `export default { ...${JSON.stringify(image)}, src };`
939
+ ].join("\n");
940
+ }
941
+ };
942
+ }
943
+
944
+ // src/vite/config.ts
945
+ function createViteConfig(root, config, kind, fonts = NO_FONTS) {
946
+ const base = {
947
+ root,
948
+ configFile: false,
949
+ appType: "custom",
950
+ logLevel: "info",
951
+ plugins: [
952
+ vue(),
953
+ // Must come before Tailwind so the theme is in the stylesheet by the time Tailwind compiles it
954
+ config.tailwind && fonts.theme ? fontThemePlugin(fonts.theme) : null,
955
+ config.tailwind ? tailwindcss() : null,
956
+ config.autoImports ? autoImportPlugins() : null,
957
+ imagesPlugin(config.images),
958
+ noofpiPlugin({ root, config, css: resolveCss(root, config, fonts) })
959
+ ],
960
+ resolve: { dedupe: ["vue", "vue-router"] },
961
+ // noofpi's runtime imports virtual modules, so it must go through vite instead of being externalized
962
+ ssr: { noExternal: ["noofpi"] },
963
+ // Subpaths must be listed too: a prebundled `noofpi/runtime` would be a second copy of the runtime modules
964
+ // (different injection keys than the ones `createNoofpiApp` provides)
965
+ optimizeDeps: {
966
+ exclude: ["noofpi", "noofpi/runtime", "noofpi/runtime/routes"],
967
+ // The generated index.html has no imports vite can scan, so these would otherwise be found one by one
968
+ // on the first page load, each triggering a re-bundle and a full reload
969
+ include: ["vue", "vue-router", "doofpi"]
970
+ }
971
+ };
972
+ if (kind === "client") {
973
+ base.build = {
974
+ outDir: path12.join(root, OUTPUT_DIR, "public"),
975
+ emptyOutDir: true,
976
+ rollupOptions: { input: indexHtmlPath(root) }
977
+ };
978
+ } else if (kind === "server") {
979
+ base.publicDir = false;
980
+ return mergeConfig(
981
+ mergeConfig(base, serverBuildConfig(root, config.build.preset)),
982
+ config.vite
983
+ );
984
+ }
985
+ return mergeConfig(base, config.vite);
986
+ }
987
+
988
+ export {
989
+ resolveFonts,
990
+ htmlTemplate,
991
+ OUTPUT_DIR,
992
+ finishPresetBuild,
993
+ DEV_ENTRY,
994
+ resolveCss,
995
+ createViteConfig
996
+ };