exta2 0.0.1-beta.29

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.mjs ADDED
@@ -0,0 +1,885 @@
1
+ // packages/exta/src/vite/index.ts
2
+ import { existsSync as existsSync2, mkdirSync as mkdirSync4, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "node:fs";
3
+ import { pathToFileURL as pathToFileURL3 } from "node:url";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { join as join12, relative as relative6 } from "node:path";
6
+
7
+ // packages/exta/src/core/index.ts
8
+ import { mkdirSync, writeFileSync } from "node:fs";
9
+ import { join as join2, relative } from "node:path";
10
+
11
+ // packages/exta/src/core/index.html.ts
12
+ import { existsSync, readFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ var cache;
15
+ function getIndexHtml() {
16
+ if (cache)
17
+ return cache;
18
+ let path2 = join(process.cwd(), "index.html");
19
+ return existsSync(path2) ? (cache = readFileSync(path2, "utf-8"), cache) : `<!doctype html>
20
+ <html lang="en">
21
+ <head>
22
+ <meta charset="UTF-8" />
23
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
24
+ %head%
25
+ </head>
26
+ <body>
27
+ %body%
28
+ </body>
29
+ </html>`;
30
+ }
31
+
32
+ // packages/exta/src/core/index.ts
33
+ function initialize(dist = join2(process.cwd(), ".exta"), pages) {
34
+ mkdirSync(dist, { recursive: !0 }), writeFileSync(
35
+ join2(dist, "index.html"),
36
+ getIndexHtml().replace("%body%", '<div id="_app"></div>').replace("%head%", '<script src="/.exta/client.js" type="module"></script>')
37
+ ), writeFileSync(join2(dist, "client.js"), 'import "$exta-client";'), writeFileSync(
38
+ join2(dist, "manifest.js"),
39
+ `export default {${Object.keys(pages).map(
40
+ (page) => ` "${page}": () => import("./${relative(dist, pages[page].client).replace(/\\/g, "/")}"),
41
+ `
42
+ ).join(`
43
+ `)}}`
44
+ );
45
+ }
46
+
47
+ // packages/exta/src/core/routing.ts
48
+ import { join as join8, parse as parse2, relative as relative4 } from "node:path";
49
+
50
+ // packages/exta/src/compiler/index.ts
51
+ import { readFile } from "node:fs/promises";
52
+ import { join as join6, relative as relative3 } from "node:path";
53
+ import { build } from "esbuild";
54
+
55
+ // packages/exta/src/compiler/constants.ts
56
+ var PAGE_STATIC_DATA_FUNCTION = "getStaticProps", PAGE_STATIC_PARAMS_FUNCTION = "getStaticParams";
57
+
58
+ // packages/exta/src/compiler/utils.ts
59
+ import { mkdir, writeFile } from "node:fs/promises";
60
+ import { dirname, isAbsolute, join as join4, relative as relative2 } from "node:path";
61
+ import oxc from "oxc-parser";
62
+
63
+ // packages/exta/src/logger.ts
64
+ import "colors";
65
+ process.env.EXTA_DEBUG && (global.COMPILER_LOG_LEVEL = "debug");
66
+ function getLogLevel(logLevel) {
67
+ if (!logLevel)
68
+ return 2 /* INFO */;
69
+ switch (logLevel.toUpperCase()) {
70
+ case "ERROR":
71
+ return 0 /* ERROR */;
72
+ case "WARN":
73
+ return 1 /* WARN */;
74
+ case "INFO":
75
+ return 2 /* INFO */;
76
+ case "DEBUG":
77
+ return 3 /* DEBUG */;
78
+ default:
79
+ return 2 /* INFO */;
80
+ }
81
+ }
82
+ var currentLogLevel = getLogLevel(
83
+ global.COMPILER_LOG_LEVEL
84
+ );
85
+ function error(message) {
86
+ currentLogLevel >= 0 /* ERROR */ && console.error(`[ERROR]: ${message}`.red);
87
+ }
88
+ function warn(message) {
89
+ currentLogLevel >= 1 /* WARN */ && console.warn(`[WARN]: ${message}`.yellow);
90
+ }
91
+ function debug(message) {
92
+ currentLogLevel >= 3 /* DEBUG */ && console.debug(`[DEBUG]: ${message}`.cyan);
93
+ }
94
+
95
+ // packages/exta/src/utils/path.ts
96
+ import { join as join3, normalize, parse, resolve } from "node:path";
97
+ function changeExtension(filename, to) {
98
+ let { dir, name } = parse(filename);
99
+ return join3(dir, name + to).replace(/\\/g, "/");
100
+ }
101
+
102
+ // packages/exta/src/compiler/utils.ts
103
+ async function getExports(code, filename = "@virtual.ts") {
104
+ let result = await oxc.parseAsync(filename, code, {
105
+ lang: "tsx",
106
+ sourceType: "module"
107
+ });
108
+ if (result.errors && process.argv.includes("--show-parser-error"))
109
+ for (let parserError of result.errors)
110
+ error(
111
+ `[exta/compiler:oxc-parser] ${parserError.message}
112
+ - ${JSON.stringify(parserError).red}`
113
+ );
114
+ let exports = [];
115
+ for (let _export_entries of result.module.staticExports)
116
+ for (let [, _export] of Object.entries(_export_entries.entries))
117
+ _export.exportName.name ? exports.push(_export.exportName.name) : _export.exportName ? exports.push("__default") : warn(`Cannot resolve export name - ${code.slice(_export.start, _export.end)}`);
118
+ return exports;
119
+ }
120
+ async function generateOriginalServerFile(filename, hasFunction, cwd = process.cwd()) {
121
+ isAbsolute(filename) || (filename = join4(cwd, filename));
122
+ let basePageDirectory = join4(cwd, "pages"), relativeFilename = relative2(basePageDirectory, filename), outdirectory = join4(cwd, ".exta"), funcList = [];
123
+ hasFunction.params && funcList.push(PAGE_STATIC_PARAMS_FUNCTION), hasFunction.data && funcList.push(PAGE_STATIC_DATA_FUNCTION);
124
+ let outServerFile = join4(
125
+ outdirectory,
126
+ "intermediate",
127
+ "server",
128
+ changeExtension(relativeFilename, ".ts")
129
+ ), outClientFile = join4(
130
+ outdirectory,
131
+ "intermediate",
132
+ "client",
133
+ changeExtension(relativeFilename, ".tsx")
134
+ );
135
+ return await mkdir(dirname(outServerFile), { recursive: !0 }), await mkdir(dirname(outClientFile), { recursive: !0 }), await writeFile(
136
+ outServerFile,
137
+ `export { ${funcList.join(", ")} } from "${relative2(dirname(outServerFile), filename).replace(/\\/g, "/")}";`
138
+ ), await writeFile(
139
+ outClientFile,
140
+ hasFunction.default ? `export { default as _page } from "${relative2(dirname(outClientFile), filename).replace(/\\/g, "/")}";export const __exta_page=true;` : "export const _page = () => null;export const __exta_page=true;"
141
+ ), {
142
+ outServerFile,
143
+ outClientFile
144
+ };
145
+ }
146
+
147
+ // packages/exta/src/compiler/plugin.ts
148
+ import { builtinModules } from "node:module";
149
+ import { join as join5 } from "node:path";
150
+ var BUILTIN_MODULES = builtinModules.concat(builtinModules.map((m) => `node:${m}`));
151
+ function sideEffectPlugin(options) {
152
+ return {
153
+ name: "exta/esbuild-sideeffect-plugin",
154
+ setup(build2) {
155
+ build2.onResolve({ filter: /.*/ }, async (args) => {
156
+ if (BUILTIN_MODULES.includes(args.path) || options?.ignoreSideEffects && (options?.preserveSideEffects || []).includes(args.path))
157
+ return {
158
+ sideEffects: !1,
159
+ path: args.path,
160
+ external: !0
161
+ };
162
+ });
163
+ }
164
+ };
165
+ }
166
+ function vmPlugin() {
167
+ return {
168
+ name: "my-virtual-module-plugin",
169
+ setup(build2) {
170
+ build2.onResolve({ filter: /^\$exta-router$/ }, (args) => ({ path: args.path, namespace: "virtual" })), build2.onLoad({ filter: /^\$exta-router$/, namespace: "virtual" }, () => ({
171
+ contents: "module.exports = {};",
172
+ loader: "js"
173
+ }));
174
+ }
175
+ };
176
+ }
177
+ function onlyReact(extensions = [".css", ".scss", ".sass", ".less"], isServerSide = !1, options) {
178
+ return options.assetsExtensions && extensions.push(...options.assetsExtensions), {
179
+ name: "exta/esbuild-react-plugin",
180
+ setup(build2) {
181
+ build2.onResolve(
182
+ {
183
+ filter: new RegExp(
184
+ `\\.(${extensions.map((ext) => ext.replace(".", "")).join("|")})$`
185
+ )
186
+ },
187
+ (args) => isServerSide ? {
188
+ path: args.path,
189
+ namespace: "exta:ignore"
190
+ } : args.path.startsWith(".") ? {
191
+ path: join5(args.resolveDir, args.path),
192
+ external: !0
193
+ } : {
194
+ path: args.path,
195
+ external: !0
196
+ }
197
+ ), build2.onLoad({ filter: /.*/, namespace: "exta:ignore" }, () => ({
198
+ contents: "",
199
+ loader: "js"
200
+ }));
201
+ }
202
+ };
203
+ }
204
+
205
+ // packages/exta/src/compiler/index.ts
206
+ async function compilePage(filename, options = {}, ignoreAssets) {
207
+ let cwd = process.cwd(), source = await readFile(filename, "utf-8"), exports = await getExports(source, filename), hasStaticPropsFunction = exports.includes(PAGE_STATIC_DATA_FUNCTION), hasStaticParamsFunction = exports.includes(PAGE_STATIC_PARAMS_FUNCTION), intermeddiateFiles = await generateOriginalServerFile(filename, {
208
+ data: hasStaticPropsFunction,
209
+ params: hasStaticParamsFunction,
210
+ default: exports.includes("__default")
211
+ }), basePageDirectory = join6(cwd, "pages"), relativeFilename = relative3(basePageDirectory, filename), outdirectory = options.outdir ?? join6(cwd, ".exta"), outfiles = {
212
+ client: join6(outdirectory, "client", changeExtension(relativeFilename, ".js")),
213
+ server: join6(outdirectory, "server", changeExtension(relativeFilename, ".mjs"))
214
+ };
215
+ return await build({
216
+ entryPoints: [intermeddiateFiles.outClientFile],
217
+ outfile: outfiles.client,
218
+ packages: "external",
219
+ sourcemap: "inline",
220
+ format: "esm",
221
+ platform: "browser",
222
+ treeShaking: !0,
223
+ bundle: !0,
224
+ jsx: "automatic",
225
+ ignoreAnnotations: !0,
226
+ plugins: [sideEffectPlugin(options), onlyReact(void 0, ignoreAssets, options)]
227
+ }), await build({
228
+ entryPoints: [intermeddiateFiles.outServerFile],
229
+ outfile: outfiles.server,
230
+ packages: "external",
231
+ format: "esm",
232
+ platform: "node",
233
+ treeShaking: !0,
234
+ bundle: !0,
235
+ ignoreAnnotations: !0,
236
+ plugins: [sideEffectPlugin(options), onlyReact(void 0, !0, options), vmPlugin()]
237
+ }), { outfiles };
238
+ }
239
+
240
+ // packages/exta/src/utils/fs.ts
241
+ import * as fs from "node:fs";
242
+ import * as path from "node:path";
243
+ function scanDirectory(directoryPath, fileList = []) {
244
+ return fs.readdirSync(directoryPath).forEach((item) => {
245
+ let fullPath = path.join(directoryPath, item);
246
+ fs.statSync(fullPath).isDirectory() ? scanDirectory(fullPath, fileList) : fileList.push(fullPath);
247
+ }), fileList;
248
+ }
249
+
250
+ // packages/exta/src/core/routing.ts
251
+ function prettyURL(path2) {
252
+ return path2 === "." && (path2 = ""), path2.startsWith("/") || (path2 = `/${path2}`), path2.endsWith("/") && (path2 = path2.slice(0, -1)), path2;
253
+ }
254
+ async function compilePages(compileOptions, ignoreAssets = !1) {
255
+ let baseDir = join8(process.cwd(), "pages"), pages = scanDirectory(baseDir), output = {};
256
+ for await (let page of pages) {
257
+ let pageName = parse2(page).name, name = prettyURL(relative4(baseDir, page).replace(/\\/g, "/"));
258
+ pageName === "_layout" ? name = "[layout]" : pageName === "_error" && (name = "[error]"), output[name] = (await compilePage(page, compileOptions, ignoreAssets)).outfiles;
259
+ }
260
+ return output;
261
+ }
262
+
263
+ // packages/exta/src/utils/params.ts
264
+ function matchUrlToRoute(url, routeResult) {
265
+ let { regex, params } = routeResult, match = regex.exec(url);
266
+ if (!match)
267
+ return null;
268
+ let result = {};
269
+ for (let i = 0; i < params.length; i++) {
270
+ let paramName = params[i], capturedValue = match[i + 1];
271
+ if (paramName.startsWith("..."))
272
+ throw new Error(
273
+ "[... file names are not supported due to static data generation issues."
274
+ );
275
+ result[paramName] = capturedValue;
276
+ }
277
+ return result;
278
+ }
279
+
280
+ // packages/exta/src/utils/url.ts
281
+ function encodeJSON(input) {
282
+ if (typeof input == "string")
283
+ try {
284
+ return encodeURIComponent(input);
285
+ } catch {
286
+ return input;
287
+ }
288
+ else {
289
+ if (Array.isArray(input))
290
+ return input.map((item) => encodeJSON(item));
291
+ if (input && typeof input == "object") {
292
+ let result = {};
293
+ for (let [key, value] of Object.entries(input))
294
+ result[key] = encodeJSON(value);
295
+ return result;
296
+ }
297
+ }
298
+ return input;
299
+ }
300
+
301
+ // packages/exta/src/utils/urlPath.ts
302
+ function convertToRegex(path2) {
303
+ let params = [], processedPath = path2.replace(/\.[^/.]+$/, "");
304
+ processedPath.endsWith("/index") && (processedPath = processedPath.slice(0, -6));
305
+ let regexString = `^/${processedPath.split("/").filter((part) => part !== "").map((part) => {
306
+ if (part.startsWith("[...") && part.endsWith("]")) {
307
+ let paramName = part.slice(4, -1);
308
+ return params.push(paramName), "(.*)";
309
+ }
310
+ if (part.startsWith("[") && part.endsWith("]")) {
311
+ let paramName = part.slice(1, -1);
312
+ return params.push(paramName), "([^/]+)";
313
+ }
314
+ return part;
315
+ }).join("/")}/?$`;
316
+ return { regex: new RegExp(regexString), params };
317
+ }
318
+
319
+ // packages/exta/src/utils/find.ts
320
+ var findPage = (url, _manifest_object) => {
321
+ let sortedManifest = [..._manifest_object].sort(
322
+ (a, b) => a.params.length - b.params.length
323
+ );
324
+ for (let route of sortedManifest)
325
+ if (route.regexp.test(decodeURIComponent(url)) && !route.path.startsWith("[") && !route.path.endsWith("]"))
326
+ return route;
327
+ return null;
328
+ };
329
+
330
+ // packages/exta/src/vite/build.ts
331
+ import { readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync4 } from "node:fs";
332
+ import { join as join11, parse as parse3, relative as relative5 } from "node:path";
333
+ import { createServer } from "vite";
334
+
335
+ // packages/exta/src/vite/builder/ssr.ts
336
+ import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2 } from "node:fs";
337
+ import { join as join9, dirname as dirname2 } from "node:path";
338
+ import { performance } from "node:perf_hooks";
339
+ import { pathToFileURL } from "node:url";
340
+ import { renderToString } from "react-dom/server";
341
+ import React3 from "react";
342
+
343
+ // packages/exta/src/client/components/_error.ts
344
+ import React from "react";
345
+ var containerStyle = {
346
+ display: "flex",
347
+ justifyContent: "center",
348
+ alignItems: "center",
349
+ width: "100%",
350
+ height: "100vh",
351
+ textAlign: "center",
352
+ flexDirection: "column"
353
+ }, defaultProps = {
354
+ status: 404,
355
+ message: "Page not found"
356
+ }, DefaultError = ({ status, message } = defaultProps) => (status = status ?? defaultProps.status, message = message ?? defaultProps.message, React.createElement("div", { style: containerStyle }, [
357
+ React.createElement("h1", { key: "status" }, String(status)),
358
+ React.createElement("p", { key: "message" }, message)
359
+ ]));
360
+
361
+ // packages/exta/src/client/components/_layout..ts
362
+ import React2 from "react";
363
+ var DefaultLayout = ({ children }) => React2.createElement(React2.Fragment, null, children);
364
+
365
+ // packages/exta/src/vite/builder/shared.ts
366
+ function replaceParamsInRoute(route, params) {
367
+ let result = route, paramRegex = /\[([^\]]+)\]/g;
368
+ return result = result.replace(paramRegex, (match, paramName) => params[paramName] || match), result = result.replace(/\.[^/.]+$/, ""), result = result.replace(/\/index$/, "") || "/", result;
369
+ }
370
+
371
+ // packages/exta/src/utils/spinner.ts
372
+ import readline from "node:readline";
373
+ import "colors";
374
+ var stream = process.stdout, defaultSpinner = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"].map(
375
+ (item) => item.cyan
376
+ ), Spinner = class {
377
+ tick;
378
+ spinner;
379
+ message;
380
+ processor;
381
+ constructor(opts = {}) {
382
+ this.tick = opts.tick || 50, this.spinner = opts.spinner || defaultSpinner, this.message = opts.message || "";
383
+ }
384
+ clearLine() {
385
+ return readline.clearLine(stream, 0), readline.cursorTo(stream, 0), this;
386
+ }
387
+ start() {
388
+ let index = 0;
389
+ return this.processor = setInterval(() => {
390
+ this.clearLine(), stream.write(`${this.spinner[index % this.spinner.length]} ${this.message}`), index += 1;
391
+ }, this.tick), this;
392
+ }
393
+ stop(message = "") {
394
+ return this.processor && (clearInterval(this.processor), this.clearLine(), stream.write(message)), this;
395
+ }
396
+ edit(message) {
397
+ return this.message = message, this;
398
+ }
399
+ };
400
+
401
+ // packages/exta/src/utils/array.ts
402
+ function getUniqueArray(arr) {
403
+ return [...new Set(arr)];
404
+ }
405
+
406
+ // packages/exta/src/vite/builder/ssr.ts
407
+ var fileRegexp = /^[^/\\]+[\\/]/;
408
+ function parsePathname(url) {
409
+ let { pathname } = new URL(url, "http://localhost/");
410
+ return pathname.endsWith("/") && (pathname = pathname.slice(0, -1)), pathname;
411
+ }
412
+ function collectCssFiles(manifest, entry) {
413
+ let result = [], visited = /* @__PURE__ */ new Set();
414
+ function recurse(key) {
415
+ if (visited.has(key))
416
+ return;
417
+ visited.add(key);
418
+ let chunk = manifest[key];
419
+ if (chunk && (chunk.css && result.push(...chunk.css), chunk.imports))
420
+ for (let imported of chunk.imports)
421
+ recurse(imported);
422
+ }
423
+ return recurse(entry), result;
424
+ }
425
+ function collectJavaScriptFiles(manifest, entry) {
426
+ let result = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
427
+ function recurse(key) {
428
+ if (visited.has(key))
429
+ return;
430
+ visited.add(key);
431
+ let chunk = manifest[key];
432
+ if (chunk) {
433
+ if (chunk.imports)
434
+ for (let importedKey of chunk.imports)
435
+ recurse(importedKey);
436
+ result.add(chunk.file);
437
+ }
438
+ }
439
+ return recurse(entry), [...result];
440
+ }
441
+ var serverRendering = (children, { Layout, props, template, cssFiles, staticManifest, path: path2, scripts }) => {
442
+ global.__EXTA_SSR_DATA__ = {
443
+ pathname: path2,
444
+ params: props.params || {},
445
+ preload: [],
446
+ head: []
447
+ };
448
+ let component = React3.createElement(children, {
449
+ ...props,
450
+ key: path2
451
+ }), string = renderToString(React3.createElement(Layout, null, component)), insert = [];
452
+ for (let cssChunk of cssFiles)
453
+ insert.push(`<link rel="stylesheet" href="/${cssChunk}" />`);
454
+ for (let preloadFile of global.__EXTA_SSR_DATA__.preload)
455
+ insert.push(`<link rel="prefetch" href="${preloadFile}" />`);
456
+ for (let script of scripts)
457
+ insert.push(`<link rel="modulepreload" href="/${script}"></link>`);
458
+ insert.push(
459
+ `<script id="__STATIC_MANIFEST__" type="application/json">${JSON.stringify(staticManifest)}</script>`
460
+ );
461
+ for (let head of global.__EXTA_SSR_DATA__.head)
462
+ switch (head.type) {
463
+ case "html":
464
+ insert.push(head.data);
465
+ break;
466
+ case "preload-data-link": {
467
+ let page = parsePathname(head.data).replace(/\//g, "_") + ".json";
468
+ staticManifest[page] ? insert.push(
469
+ `<link rel="preload" href="/data/${staticManifest[page]}.json" as="fetch"></link>`
470
+ ) : insert.push(`<!--${head.data}-->`);
471
+ break;
472
+ }
473
+ default:
474
+ break;
475
+ }
476
+ return template = template.replace(/<head[^>]*>([\s\S]*?)<\/head>/, (match, inner) => `<head${match.match(/<head([^>]*)>/)?.[1] || ""}>${insert.join("")}
477
+ ${inner}</head>`), template.replace('<div id="_app"></div>', `<div id="_app">${string}</div>`);
478
+ };
479
+ async function createStaticHTML(pages, outdir, vite, template, manifest, staticManifest) {
480
+ let startTime = performance.now(), spinner = new Spinner();
481
+ spinner.message = "Generating html files...", spinner.start();
482
+ let getLayout = async () => pages["[layout]"] ? (await vite.ssrLoadModule(pages["[layout]"].client))._page : DefaultLayout, getError = async () => pages["[error]"] ? (await vite.ssrLoadModule(pages["[error]"].client))._page : DefaultError, getClientComponent = async (path2) => (await vite.ssrLoadModule(path2))._page, ErrorComponent = await getError(), Layout = await getLayout(), layoutCompiledFile = `.exta/${pages["[layout]"].client.replace(fileRegexp, "")}`.replace(/\\/g, "/"), layoutCss = pages["[layout]"] ? collectCssFiles(manifest, layoutCompiledFile) : [], layoutScript = manifest[layoutCompiledFile]?.file;
483
+ writeFileSync2(join9(outdir, "data", "_empty.json"), "{}");
484
+ for (let pageName in pages) {
485
+ let page = pages[pageName], data = await import(pathToFileURL(page.server).href), compiledFile = `.exta/${page.client.replace(fileRegexp, "")}`.replace(
486
+ /\\/g,
487
+ "/"
488
+ ), cssFiles = collectCssFiles(manifest, compiledFile), script = collectJavaScriptFiles(manifest, compiledFile);
489
+ if (data[PAGE_STATIC_PARAMS_FUNCTION]) {
490
+ let paramsModule = await data[PAGE_STATIC_PARAMS_FUNCTION]();
491
+ if (!Array.isArray(paramsModule))
492
+ throw new Error(
493
+ `An error occurred while generating HTML file. - Static params function must return array. (in ${pageName})`
494
+ );
495
+ for (let params of paramsModule) {
496
+ let route = replaceParamsInRoute(pageName, params), outStaticPage = changeExtension(join9(outdir, route), ".html"), staticDataPath = changeExtension(
497
+ join9(
498
+ outdir,
499
+ "data",
500
+ staticManifest[route.replace(/\//g, "_") + ".json"] || "_empty"
501
+ ),
502
+ ".json"
503
+ );
504
+ spinner.message = `Generating html files... - ${route}`;
505
+ let Client = await getClientComponent(page.client), ssrProps2 = {
506
+ Layout,
507
+ props: {
508
+ props: JSON.parse(readFileSync2(staticDataPath).toString()),
509
+ params: matchUrlToRoute(route, convertToRegex(pageName))
510
+ },
511
+ template,
512
+ cssFiles: getUniqueArray([...cssFiles, ...layoutCss]),
513
+ staticManifest,
514
+ path: route,
515
+ scripts: getUniqueArray([layoutScript, ...script])
516
+ };
517
+ mkdirSync2(dirname2(outStaticPage), { recursive: !0 }), writeFileSync2(outStaticPage, serverRendering(Client, ssrProps2));
518
+ }
519
+ } else {
520
+ if (pageName.startsWith("[") && pageName.endsWith("]"))
521
+ continue;
522
+ let route = replaceParamsInRoute(pageName, {}), outStaticPage = join9(outdir, route) + "/index.html", staticDataPath = changeExtension(
523
+ join9(
524
+ outdir,
525
+ "data",
526
+ staticManifest[route.replace(/\//g, "_") + ".json"] || "_empty"
527
+ ),
528
+ ".json"
529
+ );
530
+ spinner.message = `Generating html files... - ${route}`;
531
+ let Client = await getClientComponent(page.client), ssrProps2 = {
532
+ Layout,
533
+ props: {
534
+ props: JSON.parse(readFileSync2(staticDataPath).toString()),
535
+ params: {}
536
+ },
537
+ template,
538
+ cssFiles: getUniqueArray([...cssFiles, ...layoutCss]),
539
+ staticManifest,
540
+ path: route,
541
+ scripts: getUniqueArray([layoutScript, ...script])
542
+ };
543
+ mkdirSync2(dirname2(outStaticPage), { recursive: !0 }), writeFileSync2(outStaticPage, serverRendering(Client, ssrProps2));
544
+ }
545
+ }
546
+ let ssrProps = {
547
+ Layout,
548
+ props: {},
549
+ template,
550
+ cssFiles: [...layoutCss],
551
+ staticManifest,
552
+ path: ".exta/ssr:unknown",
553
+ scripts: []
554
+ };
555
+ writeFileSync2(join9(outdir, "404.html"), serverRendering(ErrorComponent, ssrProps)), spinner.stop(
556
+ `html files generated. (${((performance.now() - startTime) / 1e3).toFixed(2)}s)`
557
+ );
558
+ }
559
+
560
+ // packages/exta/src/vite/builder/props.ts
561
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
562
+ import { join as join10, dirname as dirname3 } from "node:path";
563
+ import { performance as performance2 } from "node:perf_hooks";
564
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
565
+
566
+ // packages/exta/src/utils/random.ts
567
+ function randomString16() {
568
+ let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
569
+ return Array.from(
570
+ { length: 16 },
571
+ () => chars[Math.floor(Math.random() * chars.length)]
572
+ ).join("");
573
+ }
574
+
575
+ // packages/exta/src/vite/builder/props.ts
576
+ async function createStaticProps(pages, outdir) {
577
+ let startTime = performance2.now(), staticManifest = {}, spinner = new Spinner();
578
+ spinner.message = "Generating static data", spinner.start();
579
+ for (let pageName in pages) {
580
+ spinner.message = `Generating static data - collecting pages (${pageName})`;
581
+ let page = pages[pageName], data = await import(pathToFileURL2(page.server).href);
582
+ if (data[PAGE_STATIC_PARAMS_FUNCTION]) {
583
+ let paramsModule = await data[PAGE_STATIC_PARAMS_FUNCTION]();
584
+ if (!Array.isArray(paramsModule))
585
+ throw new Error(
586
+ `An error occurred while building the page. - Static params function must return array. (in ${pageName})`
587
+ );
588
+ for (let params of paramsModule) {
589
+ let originalURL = replaceParamsInRoute(pageName, params), outfile = changeExtension(originalURL, ".json").replace(/\//g, "_"), random = randomString16(), outStaticPage = join10(outdir, "data", `${random}.json`);
590
+ if (spinner.message = `Generating static data - ${originalURL}`, mkdirSync3(dirname3(outStaticPage), { recursive: !0 }), staticManifest[outfile] = random, data[PAGE_STATIC_DATA_FUNCTION]) {
591
+ let staticProps = await data[PAGE_STATIC_DATA_FUNCTION]({ params });
592
+ writeFileSync3(outStaticPage, JSON.stringify(staticProps));
593
+ } else
594
+ staticManifest[outfile] = null;
595
+ }
596
+ } else {
597
+ let originalURL = replaceParamsInRoute(pageName, {}), outfile = changeExtension(originalURL, ".json").replace(/\//g, "_"), random = randomString16(), outStaticPage = join10(outdir, "data", `${random}.json`);
598
+ if (spinner.message = `Generating static data - ${originalURL}`, staticManifest[outfile] = random, mkdirSync3(dirname3(outStaticPage), { recursive: !0 }), data[PAGE_STATIC_DATA_FUNCTION]) {
599
+ let staticProps = await data[PAGE_STATIC_DATA_FUNCTION]();
600
+ writeFileSync3(outStaticPage, JSON.stringify(staticProps));
601
+ } else
602
+ staticManifest[outfile] = null;
603
+ }
604
+ }
605
+ return spinner.stop(
606
+ `Static props generated. (${((performance2.now() - startTime) / 1e3).toFixed(2)}s)`
607
+ ), staticManifest;
608
+ }
609
+
610
+ // packages/exta/src/vite/build.ts
611
+ function extaBuild(compilerOptions = {}) {
612
+ let viteConfig, pageMap = {}, pages, vite, staticManifest;
613
+ function generatePageMap(bundle) {
614
+ if (Object.keys(pageMap).length !== 0)
615
+ return pageMap;
616
+ for (let key in bundle) {
617
+ if (bundle[key].type === "asset" || !bundle[key].isDynamicEntry && !bundle[key].exports.includes("__exta_page"))
618
+ continue;
619
+ let setKey = relative5(
620
+ join11(".exta", "client").replace(/\\/g, "/"),
621
+ bundle[key].facadeModuleId
622
+ ), pageName = parse3(setKey).name;
623
+ pageName === "_layout" && (setKey = "[layout]"), pageName === "_error" && (setKey = "[error]"), pageMap[setKey] = key;
624
+ }
625
+ return pageMap;
626
+ }
627
+ return {
628
+ name: "exta:build",
629
+ apply: "build",
630
+ async config(config) {
631
+ initialize(config.build.outDir || "dist", {}), pages = await compilePages({
632
+ ...compilerOptions,
633
+ outdir: config.build.outDir || "dist"
634
+ }), config.build ??= {}, config.build.rollupOptions ??= {}, config.build.rollupOptions.input ??= {}, config.build.manifest = !0, config.build.rollupOptions.input["index.html"] = "index.html", vite = await createServer({
635
+ server: { middlewareMode: !0, hmr: !1 },
636
+ ...config
637
+ });
638
+ },
639
+ async configResolved(config) {
640
+ viteConfig = config;
641
+ },
642
+ async buildStart() {
643
+ },
644
+ async generateBundle(options, bundle) {
645
+ pages = await compilePages({ ...compilerOptions, outdir: viteConfig.build.outDir }), initialize(viteConfig.build.outDir, pages), console.log(), console.log(), staticManifest = await createStaticProps(pages, viteConfig.build.outDir), console.log(), writeFileSync4(
646
+ join11(viteConfig.build.outDir, "map.json"),
647
+ JSON.stringify(generatePageMap(bundle))
648
+ );
649
+ },
650
+ async writeBundle() {
651
+ let { outDir } = viteConfig.build, indexHTML = readFileSync3(join11(outDir, "index.html")).toString();
652
+ pages = await compilePages(
653
+ { ...compilerOptions, outdir: viteConfig.build.outDir },
654
+ !0
655
+ );
656
+ let manifestPath = join11(outDir, ".vite/manifest.json"), manifest = JSON.parse(readFileSync3(manifestPath).toString());
657
+ if (console.log(), await createStaticHTML(
658
+ pages,
659
+ viteConfig.build.outDir,
660
+ vite,
661
+ indexHTML,
662
+ manifest,
663
+ staticManifest
664
+ ), await vite.close(), rmSync(join11(outDir, "map.json"), { recursive: !0, force: !0 }), rmSync(join11(outDir, "manifest.js"), { recursive: !0, force: !0 }), rmSync(join11(outDir, "client.js"), { recursive: !0, force: !0 }), rmSync(join11(outDir, "server"), { recursive: !0, force: !0 }), rmSync(join11(outDir, "client"), { recursive: !0, force: !0 }), process.env.BUILD_SUMMARY) {
665
+ let buildSummary = [];
666
+ buildSummary.push("Build Summary");
667
+ for (let staticFile in staticManifest) {
668
+ let filename = changeExtension(staticFile.replace(/_/g, "/"), "");
669
+ if (!staticManifest[staticFile]) {
670
+ buildSummary.push(`${filename}`);
671
+ continue;
672
+ }
673
+ buildSummary.push(
674
+ `${filename.padEnd(60)}${`${staticManifest[staticFile] || "null"}.json`}`
675
+ );
676
+ }
677
+ writeFileSync4(join11(__dirname, "../summary.txt"), buildSummary.join(`
678
+ `)), console.log(
679
+ `
680
+ Check the ${join11(__dirname, "../summary.txt")} file to view the build summary.`
681
+ );
682
+ }
683
+ console.log();
684
+ },
685
+ transformIndexHtml(html) {
686
+ return {
687
+ html,
688
+ tags: [
689
+ {
690
+ tag: "script",
691
+ injectTo: "head",
692
+ attrs: { id: "__PAGE_MAP__", type: "text/javascript" },
693
+ children: `window.__EXTA_PAGEMAP__ = ${JSON.stringify(pageMap)}`
694
+ }
695
+ ]
696
+ };
697
+ }
698
+ };
699
+ }
700
+
701
+ // packages/exta/src/vite/index.ts
702
+ var manifestModuleId = "$exta-manifest", resolvedManifestModuleId = "\0" + manifestModuleId, clientModuleId = "$exta-client", resolvedClientModuleId = "\0" + clientModuleId, routerModuleId = "$exta-router", resolvedRouterModuleId = "\0" + routerModuleId;
703
+ function exta(options) {
704
+ let isDev = process.env.NODE_ENV === "development", dist = options?.compileOptions.outdir ?? join12(process.cwd(), ".exta"), _manifest_object = [], _server_props = /* @__PURE__ */ new Map(), _pages, _manifest = null, logger, env;
705
+ existsSync2(dist) && rmSync2(dist, { recursive: !0, force: !0 }), mkdirSync4(dist);
706
+ function generateManifest(rawManif, force = !1) {
707
+ if (_manifest && !force)
708
+ return _manifest;
709
+ let manifest = [];
710
+ for (let path2 in rawManif) {
711
+ let converted = convertToRegex(path2), relativePath = relative6(
712
+ join12(process.cwd(), ".exta"),
713
+ rawManif[path2].client
714
+ ).replace(/\\/g, "/"), code = `{path: ${JSON.stringify(path2)}, regexp: ${converted.regex.toString()}, params: ${JSON.stringify(converted.params)}, buildPath: ${JSON.stringify(relativePath)}, originalPath: ${JSON.stringify(path2)}}`;
715
+ manifest.push(code), _manifest_object.push({
716
+ path: path2,
717
+ originalPath: path2,
718
+ regexp: converted.regex,
719
+ params: converted.params,
720
+ buildPath: relativePath,
721
+ buildServerPath: rawManif[path2].server
722
+ });
723
+ }
724
+ return _manifest = `export const PAGES_MANIFEST = [
725
+ ${manifest.join(`,
726
+ `)}
727
+ ]`, _manifest;
728
+ }
729
+ let findPage2 = (url) => findPage(url, _manifest_object);
730
+ return [
731
+ {
732
+ name: "exta",
733
+ config(config, _env) {
734
+ env = _env, config.server ??= {}, config.server.watch ??= {}, config.server.watch.ignored = [
735
+ "/.exta/**",
736
+ ...Array.isArray(config.server.watch.ignored) ? config.server.watch.ignored : config.server.watch.ignored ? [config.server.watch.ignored] : []
737
+ ], config.resolve ??= {}, config.resolve.alias ??= {}, config.resolve.alias["$exta-pages"] = join12(
738
+ env.command === "serve" ? dist : config.build.outDir || "dist",
739
+ "manifest.js"
740
+ );
741
+ },
742
+ configResolved(config) {
743
+ logger = config.logger;
744
+ },
745
+ async handleHotUpdate({ server, file }) {
746
+ if (file.includes(".exta"))
747
+ return [];
748
+ let dist2 = options?.compileOptions?.outdir || join12(process.cwd(), ".exta");
749
+ _pages = await compilePages(options?.compileOptions), _server_props.clear();
750
+ let beforeManifest = `${_manifest}`, afterManifest = generateManifest(_pages, !0);
751
+ if (beforeManifest !== afterManifest)
752
+ return server.ws.send({ type: "full-reload" }), [];
753
+ writeFileSync5(
754
+ join12(dist2, "manifest.js"),
755
+ `export default {${Object.keys(_pages).map(
756
+ (page) => ` "${page}": () => import("./${relative6(dist2, _pages[page].client).replace(/\\/g, "/")}"),
757
+ `
758
+ ).join(`
759
+ `)}}`
760
+ );
761
+ let invalidateAndUpdate = (modid, isVirtual = !0) => {
762
+ if (!modid)
763
+ return;
764
+ let mod = server.moduleGraph.getModuleById(modid);
765
+ mod && (server.moduleGraph.invalidateModule(mod), server.ws.send({
766
+ type: "update",
767
+ updates: [
768
+ {
769
+ type: "js-update",
770
+ path: isVirtual ? "/@id/" + mod.id : mod.url,
771
+ acceptedPath: isVirtual ? "/@id/" + mod.id : mod.url,
772
+ timestamp: Date.now()
773
+ }
774
+ ]
775
+ }));
776
+ };
777
+ invalidateAndUpdate(resolvedManifestModuleId), invalidateAndUpdate(
778
+ (await server.moduleGraph.getModuleByUrl("$exta-pages"))?.id ?? null
779
+ );
780
+ let normalizedFile = file.replace(/\\/g, "/"), pagesDirectory = join12(process.cwd(), "pages"), pagesFiles = scanDirectory(pagesDirectory).map(
781
+ (p) => p.replace(/\\/g, "/")
782
+ ), compiledFile = changeExtension(
783
+ join12(
784
+ process.cwd(),
785
+ ".exta",
786
+ "client",
787
+ relative6(pagesDirectory, normalizedFile)
788
+ ),
789
+ ".js"
790
+ ).replace(/\\/g, "/");
791
+ if (pagesFiles.includes(normalizedFile)) {
792
+ let modules = Array.from(server.moduleGraph.urlToModuleMap.values()).filter(
793
+ (mod) => mod.file && mod.file.replace(/\\/g, "/") === compiledFile
794
+ );
795
+ for (let mod of modules)
796
+ invalidateAndUpdate(mod.id, !1);
797
+ }
798
+ logger.info(
799
+ `${"[exta]".gray} ${relative6(process.cwd(), file).cyan.bold} updated`,
800
+ {}
801
+ );
802
+ },
803
+ async buildStart() {
804
+ _pages = await compilePages(options?.compileOptions);
805
+ },
806
+ async configureServer(server) {
807
+ _pages = await compilePages(options?.compileOptions), initialize(options?.compileOptions?.outdir, _pages), isDev && server.middlewares.use("/.exta/__page_data", async (req, res) => {
808
+ let page = new URL(req.url, "http://localhost").searchParams.get("page") || "/";
809
+ if (debug(`Requested "${page}"`), page === "$IS_CONNECTED$")
810
+ return res.end(JSON.stringify({ connected: !0 }));
811
+ let clientURL = new URL(page, "http://localhost"), pageManifest = findPage2(page), prettyPathname = prettyURL(decodeURIComponent(clientURL.pathname));
812
+ if (res.setHeader("Content-Type", "application/json"), !pageManifest?.buildServerPath)
813
+ return res.end(JSON.stringify({ props: {}, status: 404 }));
814
+ if (_server_props.has(prettyPathname))
815
+ return res.end(
816
+ JSON.stringify({
817
+ props: _server_props.get(prettyPathname),
818
+ status: 200,
819
+ cached: !0
820
+ })
821
+ );
822
+ try {
823
+ let serverModule = await import(`${pathToFileURL3(pageManifest.buildServerPath).href}?v=${Date.now()}`), params = matchUrlToRoute(clientURL.pathname, {
824
+ regex: pageManifest.regexp,
825
+ params: pageManifest.params
826
+ }), data = {};
827
+ if (serverModule[PAGE_STATIC_PARAMS_FUNCTION]) {
828
+ let availableParams = await serverModule[PAGE_STATIC_PARAMS_FUNCTION](), success = !1;
829
+ for (let allowedParams of availableParams)
830
+ isDeepStrictEqual(encodeJSON(allowedParams), params) && (success = !0);
831
+ if (!success)
832
+ return res.end(
833
+ JSON.stringify({
834
+ props: {},
835
+ status: 404
836
+ })
837
+ );
838
+ }
839
+ serverModule[PAGE_STATIC_DATA_FUNCTION] && (data = await serverModule[PAGE_STATIC_DATA_FUNCTION]({
840
+ params
841
+ })), _server_props.set(prettyPathname, data), res.end(JSON.stringify({ props: data, status: 200 })), debug(`Request ended "${page}"`);
842
+ } catch (e) {
843
+ console.error(e), res.end(
844
+ JSON.stringify({
845
+ message: "Internal Server Error",
846
+ detail: e.message,
847
+ status: 500
848
+ })
849
+ );
850
+ }
851
+ });
852
+ },
853
+ transformIndexHtml(html) {
854
+ return html.replace("%body%", '<div id="_app"></div>');
855
+ },
856
+ resolveId(id) {
857
+ if (id === manifestModuleId)
858
+ return resolvedManifestModuleId;
859
+ if (id === clientModuleId)
860
+ return resolvedClientModuleId;
861
+ if (id === routerModuleId)
862
+ return resolvedRouterModuleId;
863
+ },
864
+ load(id) {
865
+ if (id === resolvedClientModuleId)
866
+ return {
867
+ code: readFileSync4(join12(__dirname, "client.mjs"), "utf-8")
868
+ };
869
+ if (id === resolvedManifestModuleId)
870
+ return {
871
+ code: generateManifest(_pages)
872
+ };
873
+ if (id === resolvedRouterModuleId)
874
+ return {
875
+ code: readFileSync4(join12(__dirname, "router.mjs"), "utf-8")
876
+ };
877
+ }
878
+ },
879
+ extaBuild(options?.compileOptions || {})
880
+ ];
881
+ }
882
+ export {
883
+ compilePage,
884
+ exta
885
+ };