@torpor/build 0.3.0 → 0.3.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @torpor/build
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 34d17f7: Feat: UI Form component and client-side submit
8
+ - Updated dependencies [f4716c5]
9
+ - Updated dependencies [1253f7a]
10
+ - Updated dependencies [6268e00]
11
+ - Updated dependencies [f2fb547]
12
+ - @torpor/view@0.3.2
13
+
3
14
  ## 0.3.0
4
15
 
5
16
  ### Minor Changes
@@ -7,7 +7,7 @@ function internal() {
7
7
  const $page$1 = $watch({
8
8
  status: 404,
9
9
  url: new URL("http://localhost"),
10
- form: {},
10
+ form: void 0,
11
11
  error: { message: "" }
12
12
  }, { shallow: true });
13
13
  const client = {
@@ -30,4 +30,4 @@ var $page_default = $page;
30
30
 
31
31
  //#endregion
32
32
  export { $page_default, internal };
33
- //# sourceMappingURL=_page-CsdPubw4.js.map
33
+ //# sourceMappingURL=_page-Cv6YWocY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_page-Cv6YWocY.js","names":["INTERNAL_GLOBAL: unique symbol","$page: PageState","client: ClientState","$page: PageState"],"sources":["../src/state/internal.ts","../src/state/$page.ts"],"sourcesContent":["import { $watch } from \"@torpor/view\";\nimport type ClientState from \"../types/ClientState\";\nimport type InternalState from \"../types/InternalState\";\nimport type PageState from \"../types/PageState\";\n\n// Do a weird little dance to ensure that everyone has the same $page and\n// client, regardless of if they are entering via serverEntry/clientEntry or the\n// built library. There may be an easier way to do this!\n\nconst INTERNAL_GLOBAL: unique symbol = Symbol.for(\"torpor-internal\");\n\nexport default function internal(): InternalState {\n\t// @ts-ignore\n\tif (globalThis[INTERNAL_GLOBAL] === undefined) {\n\t\t// TODO: Should use the SSR $watch if entering via serverEntry\n\t\tconst $page: PageState = $watch(\n\t\t\t{\n\t\t\t\tstatus: 404,\n\t\t\t\turl: new URL(\"http://localhost\"),\n\t\t\t\tform: undefined,\n\t\t\t\terror: {\n\t\t\t\t\tmessage: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tshallow: true,\n\t\t\t},\n\t\t);\n\t\tconst client: ClientState = {\n\t\t\t// @ts-ignore This will definitely, 100% get set\n\t\t\trouter: null,\n\t\t\tlayoutStack: [],\n\t\t\t// TODO: Probably expire after 30 seconds or something?\n\t\t\tprefetchedData: {},\n\t\t};\n\n\t\t// @ts-ignore\n\t\tglobalThis[INTERNAL_GLOBAL] = {\n\t\t\t$page,\n\t\t\tclient,\n\t\t} satisfies InternalState;\n\t}\n\t// @ts-ignore\n\treturn globalThis[INTERNAL_GLOBAL] as InternalState;\n}\n","import type PageState from \"../types/PageState\";\nimport internal from \"./internal\";\n\nconst $page: PageState = internal().$page;\n\nexport default $page;\n"],"mappings":";;;AASA,MAAMA,kBAAiC,OAAO,IAAI,kBAAkB;AAEpE,SAAwB,WAA0B;AAEjD,KAAI,WAAW,qBAAqB,QAAW;EAE9C,MAAMC,UAAmB,OACxB;GACC,QAAQ;GACR,KAAK,IAAI,IAAI,mBAAmB;GAChC,MAAM;GACN,OAAO,EACN,SAAS,IACT;GACD,EACD,EACC,SAAS,MACT,CACD;EACD,MAAMC,SAAsB;GAE3B,QAAQ;GACR,aAAa,EAAE;GAEf,gBAAgB,EAAE;GAClB;AAGD,aAAW,mBAAmB;GAC7B;GACA;GACA;;AAGF,QAAO,WAAW;;;;;ACxCnB,MAAMC,QAAmB,UAAU,CAAC;AAEpC,oBAAe"}
package/dist/bin/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import "../pathToRegex-CTgx7hQP.js";
3
3
  import "../seeOther-BmehiI4C.js";
4
4
  import "../response-D-XpIuMH.js";
5
- import { run } from "../run-CNdaKSPR.js";
5
+ import { run } from "../run-CVKpO0HO.js";
6
6
  import "../ServerEvent-2-CnAy1W.js";
7
7
  import "../connectMiddleware-DbLj0St1.js";
8
8
 
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "./pathToRegex-CTgx7hQP.js";
2
2
  import { ERROR_ROUTE, HOOK_ROUTE, HOOK_SERVER_ROUTE, LAYOUT_ROUTE, LAYOUT_SERVER_ROUTE, PAGE_ROUTE, PAGE_SERVER_ROUTE, Router, SERVER_ROUTE } from "./RouteType-g8Ce5gOd.js";
3
3
  import { promises } from "node:fs";
4
- import fpath from "node:path";
4
+ import path from "node:path";
5
5
  import tsconfigPaths from "vite-tsconfig-paths";
6
6
 
7
7
  //#region src/site/defaultAdapter.ts
@@ -42,12 +42,12 @@ var Site = class {
42
42
  * @param folder The folder containing the routes
43
43
  */
44
44
  async addRouteFolder(folder) {
45
- const routeFolder = fpath.join(this.root, folder);
45
+ const routeFolder = path.join(this.root, folder);
46
46
  const routeFiles = await promises.readdir(routeFolder, { recursive: true });
47
- for (let file of routeFiles) if (/^(\+|_).+(\.js|\.ts)$/.test(fpath.basename(file))) {
47
+ for (let file of routeFiles) if (/^(\+|_).+(\.js|\.ts)$/.test(path.basename(file))) {
48
48
  let routePath = this.#routePath(file);
49
49
  let type = this.#routeType(file);
50
- file = fpath.relative(this.root, fpath.resolve(routeFolder, file));
50
+ file = path.relative(this.root, path.resolve(routeFolder, file));
51
51
  this.routes.push({
52
52
  path: routePath,
53
53
  file,
@@ -63,8 +63,8 @@ var Site = class {
63
63
  * @param file The file
64
64
  * @param type The file type (if the file name is non-standard)
65
65
  */
66
- addRouteFile(path, file, type) {
67
- let routePath = this.#routePath(fpath.join(path, type ?? fpath.basename(file)));
66
+ addRouteFile(path$1, file, type) {
67
+ let routePath = this.#routePath(path.join(path$1, type ?? path.basename(file)));
68
68
  let routeType = type ? this.#routeTypeFromString(type) : this.#routeType(file);
69
69
  this.routes.push({
70
70
  path: routePath,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["defaultAdapter: Adapter","defaultAdapter","fs","#routePath","#routeType","#sortRoutes","#routeTypeFromString"],"sources":["../src/site/defaultAdapter.ts","../src/site/Site.ts"],"sourcesContent":["import type Adapter from \"../types/Adapter\";\n\n// TODO: This should be an adapter-auto package that conditionally loads other packages...\n\nconst defaultAdapter: Adapter = {\n\tserve: () => {\n\t\tconsole.log(\"An adapter needs to be set in site.config\");\n\t},\n};\n\nexport default defaultAdapter;\n","import { promises as fs } from \"node:fs\";\nimport fpath from \"node:path\";\nimport { type Plugin, type UserConfig } from \"vite\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\nimport type Adapter from \"../types/Adapter\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tRouteType,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport defaultAdapter from \"./defaultAdapter\";\n\n// 1. The user sets this up\n// 2. It is passed into serverEntry and clientEntry through a Vite plugin\n// (defined in manifest.ts)\n// 3. In those files, it is used to build a Router\n\n/**\n * The Site class contains the information necessary to setup a @torpor/build\n * site, including routes, plugins, and options.\n */\nexport default class Site {\n\troot: string;\n\troutes: { path: string; file: string; type: RouteType }[] = [];\n\t// Is default plugins a bad idea?\n\t// HACK: Set loose because otherwise it uses a list of allowed extensions\n\t// TODO: Should probably just do this ourselves and let the user pass in\n\t// tsconfigPaths themselves if they want to do something funky\n\tplugins: Plugin[] = [tsconfigPaths({ loose: true })];\n\t// Is default adapter a bad idea?\n\tadapter: Adapter = defaultAdapter;\n\t/**\n\t * Extra inputs, as absolute file paths, that will be compiled with the\n\t * output. What you do with them after that is up to you. File paths ending\n\t * with server.ts/js will only be compiled with the server output\n\t */\n\tinputs: string[] = [];\n\t/**\n\t * Vite config options to merge with the standard Torpor build options.\n\t * `plugins` and `build.rollupOptions.input` will be overridden, so you\n\t * should set `Site.plugins` and `Site.inputs` instead. Other options may be\n\t * overridden or incompatible, so experimentation may be required\n\t */\n\tviteConfig?: UserConfig;\n\n\tconstructor() {\n\t\tthis.root = process.cwd();\n\t}\n\n\t/**\n\t * Adds a folder of routes, based on the names of the files in the folder\n\t * @param folder The folder containing the routes\n\t */\n\tasync addRouteFolder(folder: string): Promise<void> {\n\t\tconst routeFolder = fpath.join(this.root, folder);\n\t\tconst routeFiles = await fs.readdir(routeFolder, { recursive: true });\n\t\tfor (let file of routeFiles) {\n\t\t\t// The file must start with `+` or `_` and end with `.js` or `.ts`\n\t\t\tif (/^(\\+|_).+(\\.js|\\.ts)$/.test(fpath.basename(file))) {\n\t\t\t\tlet routePath = this.#routePath(file);\n\t\t\t\tlet type = this.#routeType(file);\n\t\t\t\tfile = fpath.relative(this.root, fpath.resolve(routeFolder, file));\n\t\t\t\tthis.routes.push({ path: routePath, file, type });\n\t\t\t}\n\t\t}\n\t\tthis.#sortRoutes();\n\t}\n\n\t/**\n\t * Adds a file route, which can have a standard name (e.g. +page.ts) or any\n\t * name if you pass the type\n\t * @param path The route path\n\t * @param file The file\n\t * @param type The file type (if the file name is non-standard)\n\t */\n\taddRouteFile(\n\t\tpath: string,\n\t\tfile: string,\n\t\ttype?:\n\t\t\t| \"+page\"\n\t\t\t| \"+page.server\"\n\t\t\t| \"+server\"\n\t\t\t| \"_layout\"\n\t\t\t| \"_layout.server\"\n\t\t\t| \"_hook\"\n\t\t\t| \"_hook.server\"\n\t\t\t| \"_error\",\n\t): void {\n\t\tlet routePath = this.#routePath(fpath.join(path, type ?? fpath.basename(file)));\n\t\tlet routeType = type ? this.#routeTypeFromString(type) : this.#routeType(file);\n\t\tthis.routes.push({ path: routePath, file, type: routeType });\n\t\tthis.#sortRoutes();\n\t}\n\n\t#routePath(file: string): string {\n\t\tlet routePath = file\n\t\t\t.replace(/^\\//, \"\")\n\t\t\t.replace(/(\\.ts|\\.js)$/, \"\")\n\t\t\t.replace(/_hook.server$/, \"_hook/~server\")\n\t\t\t.replace(/_layout.server$/, \"_layout/~server\")\n\t\t\t.replace(/\\+page.server$/, \"~server\")\n\t\t\t.replace(/\\+server$/, \"\")\n\t\t\t.replace(/\\+page$/, \"\")\n\t\t\t.replace(/\\/$/, \"\");\n\t\treturn routePath.length > 0 ? `/${routePath}` : \"/\";\n\t}\n\n\t#routeType(file: string): RouteType {\n\t\tlet routePath = file.replace(/^\\//, \"\").replace(/(\\.ts|\\.js)$/, \"\");\n\t\tif (routePath.endsWith(\"+page\")) {\n\t\t\treturn PAGE_ROUTE;\n\t\t} else if (routePath.endsWith(\"+page.server\")) {\n\t\t\treturn PAGE_SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"+server\")) {\n\t\t\treturn SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"_layout\")) {\n\t\t\treturn LAYOUT_ROUTE;\n\t\t} else if (routePath.endsWith(\"_layout.server\")) {\n\t\t\treturn LAYOUT_SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"_hook\")) {\n\t\t\treturn HOOK_ROUTE;\n\t\t} else if (routePath.endsWith(\"_hook.server\")) {\n\t\t\treturn HOOK_SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"_error\")) {\n\t\t\treturn ERROR_ROUTE;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t#routeTypeFromString(\n\t\ttype:\n\t\t\t| \"+page\"\n\t\t\t| \"+page.server\"\n\t\t\t| \"+server\"\n\t\t\t| \"_layout\"\n\t\t\t| \"_layout.server\"\n\t\t\t| \"_hook\"\n\t\t\t| \"_hook.server\"\n\t\t\t| \"_error\",\n\t) {\n\t\tswitch (type) {\n\t\t\tcase \"+page\":\n\t\t\t\treturn PAGE_ROUTE;\n\t\t\tcase \"+page.server\":\n\t\t\t\treturn PAGE_SERVER_ROUTE;\n\t\t\tcase \"+server\":\n\t\t\t\treturn SERVER_ROUTE;\n\t\t\tcase \"_layout\":\n\t\t\t\treturn LAYOUT_ROUTE;\n\t\t\tcase \"_layout.server\":\n\t\t\t\treturn LAYOUT_SERVER_ROUTE;\n\t\t\tcase \"_hook\":\n\t\t\t\treturn HOOK_ROUTE;\n\t\t\tcase \"_hook.server\":\n\t\t\t\treturn HOOK_SERVER_ROUTE;\n\t\t\tcase \"_error\":\n\t\t\t\treturn ERROR_ROUTE;\n\t\t}\n\t}\n\n\t// TODO: You could make your site in a single file, like e.g. Hono...\n\t//addPage(path: string, endPoint: PageEndPoint, serverEndPoint?: PageServerEndPoint) {}\n\t//addEndPoint(path: string, endPoint: ServerEndPoint) {}\n\n\t#sortRoutes() {\n\t\tthis.routes = this.routes.sort((a, b) => {\n\t\t\t// Sort [param]s after paths\n\t\t\t// There might be a quicker/easier way to do this\n\t\t\tfor (let i = 0; i < Math.min(a.path.length, b.path.length); i++) {\n\t\t\t\tif (a.path[i] === \"[\" && b.path[i] !== \"[\") {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (b.path[i] === \"[\" && a.path[i] !== \"[\") {\n\t\t\t\t\treturn -1;\n\t\t\t\t} else if (a.path[i] === b.path[i]) {\n\t\t\t\t\t// Keep going...\n\t\t\t\t} else {\n\t\t\t\t\treturn a.path[i].localeCompare(b.path[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn a.path.length - b.path.length;\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;AAIA,MAAMA,iBAA0B,EAC/B,aAAa;AACZ,SAAQ,IAAI,4CAA4C;GAEzD;AAED,6BAAe;;;;;;;;ACiBf,IAAqB,OAArB,MAA0B;CACzB;CACA,SAA4D,EAAE;CAK9D,UAAoB,CAAC,cAAc,EAAE,OAAO,MAAM,CAAC,CAAC;CAEpD,UAAmBC;;;;;;CAMnB,SAAmB,EAAE;;;;;;;CAOrB;CAEA,cAAc;AACb,OAAK,OAAO,QAAQ,KAAK;;;;;;CAO1B,MAAM,eAAe,QAA+B;EACnD,MAAM,cAAc,MAAM,KAAK,KAAK,MAAM,OAAO;EACjD,MAAM,aAAa,MAAMC,SAAG,QAAQ,aA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;WACG,UAAU,SAAS,eAAe,CAC5C,QAAO;WACG,UAAU,SAAS,SAAS,CACtC,QAAO;AAER,SAAO;;CAGR,qBACC,MASC;AACD,UAAQ,MAAR;GACC,KAAK,QACJ,QAAO;GACR,KAAK,eACJ,QAAO;GACR,KAAK,UACJ,QAAO;GACR,KAAK,UACJ,QAAO;GACR,KAAK,iBACJ,QAAO;GACR,KAAK,QACJ,QAAO;GACR,KAAK,eACJ,QAAO;GACR,KAAK,SACJ,QAAO;;;CAQV,cAAc;AACb,OAAK,SAAS,KAAK,OAAO,MAAM,GAAG,MAAM;AAGxC,QAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IAAI,EAAE,KAAK,QAAQ,EAAE,KAAK,OAAO,EAAE,IAC3D,KAAI,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,IACtC,QAAO;YACG,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,IAC7C,QAAO;YACG,EAAE,KAAK,OAAO,EAAE,KAAK,IAAI,OAGnC,QAAO,EAAE,KAAK,GAAG,cAAc,EAAE,KAAK,GAAG;AAG3C,UAAO,EAAE,KAAK,SAAS,EAAE,KAAK;IAC7B"}
1
+ {"version":3,"file":"index.js","names":["defaultAdapter: Adapter","defaultAdapter","fpath","fs","#routePath","#routeType","#sortRoutes","path","#routeTypeFromString"],"sources":["../src/site/defaultAdapter.ts","../src/site/Site.ts"],"sourcesContent":["import type Adapter from \"../types/Adapter\";\n\n// TODO: This should be an adapter-auto package that conditionally loads other packages...\n\nconst defaultAdapter: Adapter = {\n\tserve: () => {\n\t\tconsole.log(\"An adapter needs to be set in site.config\");\n\t},\n};\n\nexport default defaultAdapter;\n","import { promises as fs } from \"node:fs\";\nimport fpath from \"node:path\";\nimport { type Plugin, type UserConfig } from \"vite\";\nimport tsconfigPaths from \"vite-tsconfig-paths\";\nimport type Adapter from \"../types/Adapter\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tRouteType,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport defaultAdapter from \"./defaultAdapter\";\n\n// 1. The user sets this up\n// 2. It is passed into serverEntry and clientEntry through a Vite plugin\n// (defined in manifest.ts)\n// 3. In those files, it is used to build a Router\n\n/**\n * The Site class contains the information necessary to setup a @torpor/build\n * site, including routes, plugins, and options.\n */\nexport default class Site {\n\troot: string;\n\troutes: { path: string; file: string; type: RouteType }[] = [];\n\t// Is default plugins a bad idea?\n\t// HACK: Set loose because otherwise it uses a list of allowed extensions\n\t// TODO: Should probably just do this ourselves and let the user pass in\n\t// tsconfigPaths themselves if they want to do something funky\n\tplugins: Plugin[] = [tsconfigPaths({ loose: true })];\n\t// Is default adapter a bad idea?\n\tadapter: Adapter = defaultAdapter;\n\t/**\n\t * Extra inputs, as absolute file paths, that will be compiled with the\n\t * output. What you do with them after that is up to you. File paths ending\n\t * with server.ts/js will only be compiled with the server output\n\t */\n\tinputs: string[] = [];\n\t/**\n\t * Vite config options to merge with the standard Torpor build options.\n\t * `plugins` and `build.rollupOptions.input` will be overridden, so you\n\t * should set `Site.plugins` and `Site.inputs` instead. Other options may be\n\t * overridden or incompatible, so experimentation may be required\n\t */\n\tviteConfig?: UserConfig;\n\n\tconstructor() {\n\t\tthis.root = process.cwd();\n\t}\n\n\t/**\n\t * Adds a folder of routes, based on the names of the files in the folder\n\t * @param folder The folder containing the routes\n\t */\n\tasync addRouteFolder(folder: string): Promise<void> {\n\t\tconst routeFolder = fpath.join(this.root, folder);\n\t\tconst routeFiles = await fs.readdir(routeFolder, { recursive: true });\n\t\tfor (let file of routeFiles) {\n\t\t\t// The file must start with `+` or `_` and end with `.js` or `.ts`\n\t\t\tif (/^(\\+|_).+(\\.js|\\.ts)$/.test(fpath.basename(file))) {\n\t\t\t\tlet routePath = this.#routePath(file);\n\t\t\t\tlet type = this.#routeType(file);\n\t\t\t\tfile = fpath.relative(this.root, fpath.resolve(routeFolder, file));\n\t\t\t\tthis.routes.push({ path: routePath, file, type });\n\t\t\t}\n\t\t}\n\t\tthis.#sortRoutes();\n\t}\n\n\t/**\n\t * Adds a file route, which can have a standard name (e.g. +page.ts) or any\n\t * name if you pass the type\n\t * @param path The route path\n\t * @param file The file\n\t * @param type The file type (if the file name is non-standard)\n\t */\n\taddRouteFile(\n\t\tpath: string,\n\t\tfile: string,\n\t\ttype?:\n\t\t\t| \"+page\"\n\t\t\t| \"+page.server\"\n\t\t\t| \"+server\"\n\t\t\t| \"_layout\"\n\t\t\t| \"_layout.server\"\n\t\t\t| \"_hook\"\n\t\t\t| \"_hook.server\"\n\t\t\t| \"_error\",\n\t): void {\n\t\tlet routePath = this.#routePath(fpath.join(path, type ?? fpath.basename(file)));\n\t\tlet routeType = type ? this.#routeTypeFromString(type) : this.#routeType(file);\n\t\tthis.routes.push({ path: routePath, file, type: routeType });\n\t\tthis.#sortRoutes();\n\t}\n\n\t#routePath(file: string): string {\n\t\tlet routePath = file\n\t\t\t.replace(/^\\//, \"\")\n\t\t\t.replace(/(\\.ts|\\.js)$/, \"\")\n\t\t\t.replace(/_hook.server$/, \"_hook/~server\")\n\t\t\t.replace(/_layout.server$/, \"_layout/~server\")\n\t\t\t.replace(/\\+page.server$/, \"~server\")\n\t\t\t.replace(/\\+server$/, \"\")\n\t\t\t.replace(/\\+page$/, \"\")\n\t\t\t.replace(/\\/$/, \"\");\n\t\treturn routePath.length > 0 ? `/${routePath}` : \"/\";\n\t}\n\n\t#routeType(file: string): RouteType {\n\t\tlet routePath = file.replace(/^\\//, \"\").replace(/(\\.ts|\\.js)$/, \"\");\n\t\tif (routePath.endsWith(\"+page\")) {\n\t\t\treturn PAGE_ROUTE;\n\t\t} else if (routePath.endsWith(\"+page.server\")) {\n\t\t\treturn PAGE_SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"+server\")) {\n\t\t\treturn SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"_layout\")) {\n\t\t\treturn LAYOUT_ROUTE;\n\t\t} else if (routePath.endsWith(\"_layout.server\")) {\n\t\t\treturn LAYOUT_SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"_hook\")) {\n\t\t\treturn HOOK_ROUTE;\n\t\t} else if (routePath.endsWith(\"_hook.server\")) {\n\t\t\treturn HOOK_SERVER_ROUTE;\n\t\t} else if (routePath.endsWith(\"_error\")) {\n\t\t\treturn ERROR_ROUTE;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t#routeTypeFromString(\n\t\ttype:\n\t\t\t| \"+page\"\n\t\t\t| \"+page.server\"\n\t\t\t| \"+server\"\n\t\t\t| \"_layout\"\n\t\t\t| \"_layout.server\"\n\t\t\t| \"_hook\"\n\t\t\t| \"_hook.server\"\n\t\t\t| \"_error\",\n\t) {\n\t\tswitch (type) {\n\t\t\tcase \"+page\":\n\t\t\t\treturn PAGE_ROUTE;\n\t\t\tcase \"+page.server\":\n\t\t\t\treturn PAGE_SERVER_ROUTE;\n\t\t\tcase \"+server\":\n\t\t\t\treturn SERVER_ROUTE;\n\t\t\tcase \"_layout\":\n\t\t\t\treturn LAYOUT_ROUTE;\n\t\t\tcase \"_layout.server\":\n\t\t\t\treturn LAYOUT_SERVER_ROUTE;\n\t\t\tcase \"_hook\":\n\t\t\t\treturn HOOK_ROUTE;\n\t\t\tcase \"_hook.server\":\n\t\t\t\treturn HOOK_SERVER_ROUTE;\n\t\t\tcase \"_error\":\n\t\t\t\treturn ERROR_ROUTE;\n\t\t}\n\t}\n\n\t// TODO: You could make your site in a single file, like e.g. Hono...\n\t//addPage(path: string, endPoint: PageEndPoint, serverEndPoint?: PageServerEndPoint) {}\n\t//addEndPoint(path: string, endPoint: ServerEndPoint) {}\n\n\t#sortRoutes() {\n\t\tthis.routes = this.routes.sort((a, b) => {\n\t\t\t// Sort [param]s after paths\n\t\t\t// There might be a quicker/easier way to do this\n\t\t\tfor (let i = 0; i < Math.min(a.path.length, b.path.length); i++) {\n\t\t\t\tif (a.path[i] === \"[\" && b.path[i] !== \"[\") {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (b.path[i] === \"[\" && a.path[i] !== \"[\") {\n\t\t\t\t\treturn -1;\n\t\t\t\t} else if (a.path[i] === b.path[i]) {\n\t\t\t\t\t// Keep going...\n\t\t\t\t} else {\n\t\t\t\t\treturn a.path[i].localeCompare(b.path[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn a.path.length - b.path.length;\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;AAIA,MAAMA,iBAA0B,EAC/B,aAAa;AACZ,SAAQ,IAAI,4CAA4C;GAEzD;AAED,6BAAe;;;;;;;;ACiBf,IAAqB,OAArB,MAA0B;CACzB;CACA,SAA4D,EAAE;CAK9D,UAAoB,CAAC,cAAc,EAAE,OAAO,MAAM,CAAC,CAAC;CAEpD,UAAmBC;;;;;;CAMnB,SAAmB,EAAE;;;;;;;CAOrB;CAEA,cAAc;AACb,OAAK,OAAO,QAAQ,KAAK;;;;;;CAO1B,MAAM,eAAe,QAA+B;EACnD,MAAM,cAAcC,KAAM,KAAK,KAAK,MAAM,OAAO;EACjD,MAAM,aAAa,MAAMC,SAAG,QAAQ,aAAa,EAAE,WAAW,MAAM,CAAC;AACrE,OAAK,IAAI,QAAQ,WAEhB,KAAI,wBAAwB,KAAKD,KAAM,SAAS,KAAK,CAAC,EAAE;GACvD,IAAI,YAAY,MAAKE,UAAW,KAAK;GACrC,IAAI,OAAO,MAAKC,UAAW,KAAK;AAChC,UAAOH,KAAM,SAAS,KAAK,MAAMA,KAAM,QAAQ,aAAa,KAAK,CAAC;AAClE,QAAK,OAAO,KAAK;IAAE,MAAM;IAAW;IAAM;IAAM,CAAC;;AAGnD,QAAKI,YAAa;;;;;;;;;CAUnB,aACC,QACA,MACA,MASO;EACP,IAAI,YAAY,MAAKF,UAAWF,KAAM,KAAKK,QAAM,QAAQL,KAAM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,EAAE,KAAK,OAAO,EAAE,IAC3D,KAAI,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,IACtC,QAAO;YACG,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,IAC7C,QAAO;YACG,EAAE,KAAK,OAAO,EAAE,KAAK,IAAI,OAGnC,QAAO,EAAE,KAAK,GAAG,cAAc,EAAE,KAAK,GAAG;AAG3C,UAAO,EAAE,KAAK,SAAS,EAAE,KAAK;IAC7B"}
package/dist/nav.js CHANGED
@@ -1,10 +1,44 @@
1
- import { $page_default, internal } from "./_page-CsdPubw4.js";
1
+ import { $page_default, internal } from "./_page-Cv6YWocY.js";
2
2
  import { clearLayoutSlot, fillLayoutSlot, hydrate, mount } from "@torpor/view";
3
3
 
4
4
  //#region src/state/client.ts
5
5
  const client = internal().client;
6
6
  var client_default = client;
7
7
 
8
+ //#endregion
9
+ //#region src/nav/reload.ts
10
+ /**
11
+ * Reloads data for the currently loaded page and rerenders it.
12
+ */
13
+ async function reload() {
14
+ const url = new URL(document.location.href);
15
+ return await navigate(url);
16
+ }
17
+
18
+ //#endregion
19
+ //#region src/nav/formSubmit.ts
20
+ async function formSubmit(e) {
21
+ e.preventDefault();
22
+ $page_default.form = void 0;
23
+ const form = e.target;
24
+ const options = {
25
+ body: new FormData(form),
26
+ method: "POST",
27
+ mode: "cors",
28
+ credentials: "same-origin",
29
+ headers: { "x-torpor-form-submit": "" }
30
+ };
31
+ const response = await fetch(form.action, options);
32
+ if (response.status === 200 && response.headers.has("x-torpor-form-redirect")) {
33
+ const redirect = response.headers.get("location");
34
+ await load(redirect);
35
+ window.location.href = redirect;
36
+ } else if (response.status >= 200 && response.status <= 299 || response.status >= 400 && response.status <= 499) {
37
+ if (response.headers.get("content-type") === "application/json") $page_default.form = await response.json();
38
+ await reload();
39
+ }
40
+ }
41
+
8
42
  //#endregion
9
43
  //#region src/nav/loadData.ts
10
44
  async function loadData(handler, params, path, newLayoutStack, clientEndPoint, serverEndPoint, prefetch = false) {
@@ -84,7 +118,6 @@ async function navigate(url, withHydration = false) {
84
118
  }
85
119
  const path = url.pathname;
86
120
  const query = url.searchParams;
87
- console.log(`navigating to '${path}'${query.size ? ` with ${query}` : ""}`);
88
121
  const route = client_default.router.match(path, query);
89
122
  if (!route) {
90
123
  console.log("404");
@@ -113,10 +146,9 @@ async function navigate(url, withHydration = false) {
113
146
  $page_default.form = form;
114
147
  formInput.remove();
115
148
  }
116
- const $props = {
117
- data,
118
- form
119
- };
149
+ let $props = { data };
150
+ $props.form = $page_default.form;
151
+ const $context = { TorporBuildContext: { onformsubmit: formSubmit } };
120
152
  client_default.layoutStack.push({
121
153
  path: route.handler.path,
122
154
  data: {},
@@ -129,7 +161,7 @@ async function navigate(url, withHydration = false) {
129
161
  let slots = void 0;
130
162
  if (handler.layouts) {
131
163
  let slotFunctions = [];
132
- slotFunctions[handler.layouts.length] = function clientComponent(parent$1, anchor, _, $context) {
164
+ slotFunctions[handler.layouts.length] = function clientComponent(parent$1, anchor) {
133
165
  let i = layoutStack.length - 1;
134
166
  layoutStack[i].slotRange = fillLayoutSlot(clientEndPoint.component, slotFunctions[i + 1], parent$1, anchor, $props, $context);
135
167
  };
@@ -143,8 +175,8 @@ async function navigate(url, withHydration = false) {
143
175
  } else if (i === 0) {
144
176
  component = layoutEndPoint.component;
145
177
  slots = { _: slotFunctions[i + 1] };
146
- } else slotFunctions[i] = function layoutComponent(parent$1, anchor, _, $context) {
147
- layoutStack[i - 1].slotRange = fillLayoutSlot(layoutEndPoint.component, slotFunctions[i + 1], parent$1, anchor, $props, $context);
178
+ } else slotFunctions[i] = function layoutComponent(parent$1, anchor, _, $context$1) {
179
+ layoutStack[i - 1].slotRange = fillLayoutSlot(layoutEndPoint.component, slotFunctions[i + 1], parent$1, anchor, $props, $context$1);
148
180
  };
149
181
  }
150
182
  }
@@ -169,16 +201,6 @@ async function load(path) {
169
201
  return await navigate(url);
170
202
  }
171
203
 
172
- //#endregion
173
- //#region src/nav/reload.ts
174
- /**
175
- * Reloads data for the currently loaded page and rerenders it.
176
- */
177
- async function reload() {
178
- const url = new URL(document.location.href);
179
- return await navigate(url);
180
- }
181
-
182
204
  //#endregion
183
205
  export { load, reload };
184
206
  //# sourceMappingURL=nav.js.map
package/dist/nav.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"nav.js","names":["client: ClientState","client","layoutEndPoint: PageEndPoint | undefined","layoutServerEndPoint: PageServerEndPoint | undefined","client","clientEndPoint: PageEndPoint | undefined","serverEndPoint: PageServerEndPoint | undefined","newLayoutStack: LayoutPath[]","form: Record<string, string> | undefined","$props: Record<string, any>","slots: Record<string, SlotRender> | undefined","slotFunctions: SlotRender[]","parent","layoutEndPoint: PageEndPoint | undefined"],"sources":["../src/state/client.ts","../src/nav/loadData.ts","../src/nav/navigate.ts","../src/nav/load.ts","../src/nav/reload.ts"],"sourcesContent":["import type ClientState from \"../types/ClientState\";\nimport internal from \"./internal\";\n\nconst client: ClientState = internal().client;\n\nexport default client;\n","import client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint\";\nimport type RouteHandler from \"../types/RouteHandler\";\n\nexport default async function loadData(\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\tpath: string,\n\tnewLayoutStack: LayoutPath[],\n\tclientEndPoint: PageEndPoint | undefined,\n\tserverEndPoint: PageServerEndPoint | undefined,\n\tprefetch = false,\n): Promise<Record<string, string> | void> {\n\tlet data = {};\n\tif (handler.layouts) {\n\t\tlet layoutStack = client.layoutStack;\n\t\tfor (let [i, layout] of handler.layouts.entries()) {\n\t\t\tlet layoutPath = layout.path;\n\t\t\tfor (let key in params) {\n\t\t\t\tlayoutPath = layoutPath.replace(`[${key}]`, params[key]);\n\t\t\t}\n\t\t\tif (layoutStack.at(i)?.path === layoutPath) {\n\t\t\t\t// We've already loaded this layout, we can just re-use its data and UI\n\t\t\t\tif (!prefetch) {\n\t\t\t\t\tlayoutStack[i].reuse = true;\n\t\t\t\t}\n\t\t\t\tnewLayoutStack[i] = layoutStack[i];\n\t\t\t\tObject.assign(data, layoutStack[i].data);\n\t\t\t} else {\n\t\t\t\tconst stackLayout = { path: layoutPath, data: {}, reuse: false, slotRange: null };\n\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\t\tconst layoutResponse = await loadClientAndServerData(\n\t\t\t\t\tstackLayout.data,\n\t\t\t\t\tdocument.location.origin + layoutPath,\n\t\t\t\t\tparams,\n\t\t\t\t\tlayoutEndPoint,\n\t\t\t\t\tlayoutServerEndPoint,\n\t\t\t\t);\n\t\t\t\tif (layoutResponse?.ok === false) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tObject.assign(data, stackLayout.data);\n\t\t\t\tnewLayoutStack.push(stackLayout);\n\t\t\t}\n\t\t}\n\t}\n\tlet endPointResponse = await loadClientAndServerData(\n\t\tdata,\n\t\tdocument.location.origin + path,\n\t\tparams,\n\t\tclientEndPoint,\n\t\tserverEndPoint,\n\t);\n\tif (endPointResponse?.ok === false) {\n\t\treturn;\n\t}\n\treturn data;\n}\n\nasync function loadClientAndServerData(\n\tdata: Record<string, any>,\n\tlocation: string,\n\tparams: Record<string, string>,\n\tclientEndPoint?: PageEndPoint,\n\tserverEndPoint?: PageServerEndPoint,\n): Promise<Response | undefined | void> {\n\tlet prefetchedData = client.prefetchedData;\n\n\tif (clientEndPoint?.load) {\n\t\tif (prefetchedData[location]) {\n\t\t\tObject.assign(data, prefetchedData[location]);\n\t\t} else {\n\t\t\tconst clientUrl = new URL(document.location.href);\n\t\t\tconst clientParams = buildClientParams(clientUrl, params, data);\n\t\t\tconst clientResponse = await clientEndPoint.load(clientParams);\n\t\t\tif (clientResponse) {\n\t\t\t\tif (clientResponse.ok) {\n\t\t\t\t\tif (clientResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\t\tconst clientData = await clientResponse.json();\n\t\t\t\t\t\tObject.assign(data, clientData);\n\t\t\t\t\t\tprefetchedData[location] = clientData;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn clientResponse;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (serverEndPoint?.load) {\n\t\tconst serverUrl = location.replace(/\\/$/, \"\") + \"/~server\";\n\n\t\tif (prefetchedData[serverUrl]) {\n\t\t\tObject.assign(data, prefetchedData[serverUrl]);\n\t\t} else {\n\t\t\tconst serverResponse = await fetch(serverUrl);\n\t\t\tif (serverResponse) {\n\t\t\t\tif (serverResponse.ok) {\n\t\t\t\t\tif (serverResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\t\tconst serverData = await serverResponse.json();\n\t\t\t\t\t\tObject.assign(data, serverData);\n\t\t\t\t\t\tprefetchedData[serverUrl] = serverData;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn serverResponse;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction buildClientParams(url: URL, params: Record<string, string>, data: Record<string, any>) {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tdata,\n\t};\n}\n","import { clearLayoutSlot, fillLayoutSlot, hydrate } from \"@torpor/view\";\nimport { type Component, type SlotRender } from \"@torpor/view\";\nimport { mount } from \"@torpor/view\";\nimport $page from \"../state/$page\";\nimport client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint\";\nimport loadData from \"./loadData\";\n\n// @ts-ignore\nexport default async function navigate(url: URL, withHydration = false): Promise<boolean> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn false;\n\t}\n\n\tconst path = url.pathname;\n\tconst query = url.searchParams;\n\n\tconsole.log(`navigating to '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\tconst route = client.router.match(path, query);\n\tif (!route) {\n\t\t// TODO: 404\n\t\tconsole.log(\"404\");\n\t\treturn false;\n\t}\n\n\t// Update $page before building the components\n\t$page.url = url;\n\tif (path.endsWith(\"/_error\")) {\n\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t// Make it look a bit classier by removing the query\n\t\twindow.history.replaceState({}, \"\", url.toString().split(\"?\")[0]);\n\t} else {\n\t\t$page.status = 200;\n\t}\n\n\tconst handler = route.handler;\n\tconst params = route.params || {};\n\n\t// There must be a client endpoint with a component\n\tconst clientEndPoint: PageEndPoint | undefined = (await handler.endPoint()).default;\n\tif (!clientEndPoint?.component) {\n\t\t// TODO: 404\n\t\tconsole.log(\"404\");\n\t\treturn false;\n\t}\n\n\t// There may be a server endpoint\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint())?.default;\n\n\tlet newLayoutStack: LayoutPath[] = [];\n\n\t// Pass the data into $props\n\t// TODO: Don't load if this is the first time -- it should have been passed\n\t// to us, somehow...\n\tconst data = await loadData(\n\t\thandler,\n\t\tparams,\n\t\tpath,\n\t\tnewLayoutStack,\n\t\tclientEndPoint,\n\t\tserverEndPoint,\n\t);\n\t// We may have form data in a hidden input -- not sure if this is the best\n\t// way to do it\n\tlet formInput = document.getElementById(\"t-form-data\") as HTMLInputElement;\n\tlet form: Record<string, string> | undefined;\n\tif (formInput) {\n\t\tform = JSON.parse(formInput.value);\n\t\t$page.form = form;\n\t\tformInput.remove();\n\t}\n\tconst $props: Record<string, any> = { data, form };\n\n\tclient.layoutStack.push({ path: route.handler.path, data: {}, reuse: false, slotRange: null });\n\tclient.layoutStack = newLayoutStack;\n\tlet layoutStack = client.layoutStack;\n\n\t// If there are layouts, work our way upwards, pushing each component into\n\t// the default slot of its parent\n\t// TODO: There's probably a nicer way to do this with reducers or something\n\tlet component = clientEndPoint.component as Component;\n\tlet slots: Record<string, SlotRender> | undefined = undefined;\n\tif (handler.layouts) {\n\t\tlet slotFunctions: SlotRender[] = [];\n\t\t// The last slot function will render the client component\n\t\tslotFunctions[handler.layouts.length] = function clientComponent(parent, anchor, _, $context) {\n\t\t\tlet i = layoutStack.length - 1;\n\t\t\tlayoutStack[i].slotRange = fillLayoutSlot(\n\t\t\t\tclientEndPoint.component!,\n\t\t\t\tslotFunctions[i + 1],\n\t\t\t\tparent,\n\t\t\t\tanchor,\n\t\t\t\t$props,\n\t\t\t\t$context,\n\t\t\t);\n\t\t};\n\n\t\t// Each earlier slot function will render a layout\n\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t?.default;\n\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\tif (layoutStack[i].reuse) {\n\t\t\t\t\t// Set the parent to add the new content to (from the old\n\t\t\t\t\t// content), clear the range under this point, and set the\n\t\t\t\t\t// component to the slot function within this layout\n\t\t\t\t\tparent = layoutStack[i].slotRange.startNode.parentNode as HTMLElement;\n\t\t\t\t\tclearLayoutSlot(layoutStack[i].slotRange);\n\t\t\t\t\tcomponent = slotFunctions[i + 1];\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (i === 0) {\n\t\t\t\t\tcomponent = layoutEndPoint.component as Component;\n\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t} else {\n\t\t\t\t\tslotFunctions[i] = function layoutComponent(parent, anchor, _, $context) {\n\t\t\t\t\t\tlayoutStack[i - 1].slotRange = fillLayoutSlot(\n\t\t\t\t\t\t\tlayoutEndPoint.component!,\n\t\t\t\t\t\t\tslotFunctions[i + 1],\n\t\t\t\t\t\t\tparent,\n\t\t\t\t\t\t\tanchor,\n\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (withHydration) {\n\t\thydrate(parent, component, $props, slots);\n\t} else {\n\t\ttry {\n\t\t\tmount(parent, component, $props, slots);\n\t\t} catch (error) {\n\t\t\t// TODO: Show a proper Error component\n\t\t\tparent.innerHTML = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\tconsole.log(error);\n\t\t}\n\t}\n\n\t// Reset prefetched data on each navigation\n\tclient.prefetchedData = {};\n\n\treturn true;\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path.\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn await navigate(url);\n}\n","import navigate from \"./navigate\";\n\n/**\n * Reloads data for the currently loaded page and rerenders it.\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn await navigate(url);\n}\n"],"mappings":";;;;AAGA,MAAMA,SAAsB,UAAU,CAAC;AAEvC,qBAAe;;;;ACCf,eAA8B,SAC7B,SACA,QACA,MACA,gBACA,gBACA,gBACA,WAAW,OAC8B;CACzC,IAAI,OAAO,EAAE;AACb,KAAI,QAAQ,SAAS;EACpB,IAAI,cAAcC,eAAO;AACzB,OAAK,IAAI,CAAC,GAAG,WAAW,QAAQ,QAAQ,SAAS,EAAE;GAClD,IAAI,aAAa,OAAO;AACxB,QAAK,IAAI,OAAO,OACf,cAAa,WAAW,QAAQ,IAAI,IAAI,IAAI,OAAO,KAAK;AAEzD,OAAI,YAAY,GAAG,EAAE,EAAE,SAAS,YAAY;AAE3C,QAAI,CAAC,SACJ,aAAY,GAAG,QAAQ;AAExB,mBAAe,KAAK,YAAY;AAChC,WAAO,OAAO,MAAM,YAAY,GAAG,KAAK;UAClC;IACN,MAAM,cAAc;KAAE,MAAM;KAAY,MAAM,E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B,QAAO;;;;;;;;ACnJR,eAA8B,KAAK,MAAgC;CAClE,MAAM,MAAM,IAAI,IAAI,MAAM,SAAS,SAAS,KAAK;AACjD,QAAO,MAAM,SAAS,IAAI;;;;;;;;ACF3B,eAA8B,SAA2B;CACxD,MAAM,MAAM,IAAI,IAAI,SAAS,SAAS,KAAK;AAC3C,QAAO,MAAM,SAAS,IAAI"}
1
+ {"version":3,"file":"nav.js","names":["client: ClientState","client","layoutEndPoint: PageEndPoint | undefined","layoutServerEndPoint: PageServerEndPoint | undefined","client","clientEndPoint: PageEndPoint | undefined","serverEndPoint: PageServerEndPoint | undefined","newLayoutStack: LayoutPath[]","form: Record<string, string> | undefined","$props: Record<string, any>","$page","slots: Record<string, SlotRender> | undefined","slotFunctions: SlotRender[]","parent","layoutEndPoint: PageEndPoint | undefined","$context"],"sources":["../src/state/client.ts","../src/nav/reload.ts","../src/nav/formSubmit.ts","../src/nav/loadData.ts","../src/nav/navigate.ts","../src/nav/load.ts"],"sourcesContent":["import type ClientState from \"../types/ClientState\";\nimport internal from \"./internal\";\n\nconst client: ClientState = internal().client;\n\nexport default client;\n","import navigate from \"./navigate\";\n\n/**\n * Reloads data for the currently loaded page and rerenders it.\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn await navigate(url);\n}\n","import $page from \"../state/$page\";\nimport load from \"./load\";\nimport reload from \"./reload\";\n\nexport default async function formSubmit(e: SubmitEvent): Promise<void> {\n\t// We'll take it from here\n\te.preventDefault();\n\n\t// Reset $page on submit and link navigation\n\t// TODO: Should we put data in $page.data??\n\t$page.form = undefined;\n\n\t// Perform a POST fetch to the form's action location\n\tconst form = e.target as HTMLFormElement;\n\tconst options = {\n\t\tbody: new FormData(form),\n\t\tmethod: \"POST\",\n\t\tmode: \"cors\",\n\t\tcredentials: \"same-origin\",\n\t\t// Add a special header which tells the server that we want the raw\n\t\t// error response (if applicable) rather than the reloaded page that you\n\t\t// would get if submitting a page without javascript\n\t\theaders: {\n\t\t\t\"x-torpor-form-submit\": \"\",\n\t\t},\n\t};\n\tconst response = await fetch(\n\t\tform.action,\n\t\t// @ts-ignore -- don't know what it's complaining about here\n\t\toptions,\n\t);\n\n\tif (response.status === 200 && response.headers.has(\"x-torpor-form-redirect\")) {\n\t\t// TODO: Should do the correct type of redirect e.g. seeOther etc\n\t\tconst redirect = response.headers.get(\"location\")!;\n\t\tawait load(redirect);\n\t\twindow.location.href = redirect;\n\t} else if (\n\t\t(response.status >= 200 && response.status <= 299) ||\n\t\t(response.status >= 400 && response.status <= 499)\n\t) {\n\t\t// Put the response into `$page.form`, and it will be put into `$props` in reload\n\t\tif (response.headers.get(\"content-type\") === \"application/json\") {\n\t\t\t$page.form = await response.json();\n\t\t}\n\t\tawait reload();\n\t}\n}\n","import client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint\";\nimport type RouteHandler from \"../types/RouteHandler\";\n\nexport default async function loadData(\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\tpath: string,\n\tnewLayoutStack: LayoutPath[],\n\tclientEndPoint: PageEndPoint | undefined,\n\tserverEndPoint: PageServerEndPoint | undefined,\n\tprefetch = false,\n): Promise<Record<string, string> | void> {\n\tlet data = {};\n\tif (handler.layouts) {\n\t\tlet layoutStack = client.layoutStack;\n\t\tfor (let [i, layout] of handler.layouts.entries()) {\n\t\t\tlet layoutPath = layout.path;\n\t\t\tfor (let key in params) {\n\t\t\t\tlayoutPath = layoutPath.replace(`[${key}]`, params[key]);\n\t\t\t}\n\t\t\tif (layoutStack.at(i)?.path === layoutPath) {\n\t\t\t\t// We've already loaded this layout, we can just re-use its data and UI\n\t\t\t\tif (!prefetch) {\n\t\t\t\t\tlayoutStack[i].reuse = true;\n\t\t\t\t}\n\t\t\t\tnewLayoutStack[i] = layoutStack[i];\n\t\t\t\tObject.assign(data, layoutStack[i].data);\n\t\t\t} else {\n\t\t\t\tconst stackLayout = { path: layoutPath, data: {}, reuse: false, slotRange: null };\n\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\t\tconst layoutResponse = await loadClientAndServerData(\n\t\t\t\t\tstackLayout.data,\n\t\t\t\t\tdocument.location.origin + layoutPath,\n\t\t\t\t\tparams,\n\t\t\t\t\tlayoutEndPoint,\n\t\t\t\t\tlayoutServerEndPoint,\n\t\t\t\t);\n\t\t\t\tif (layoutResponse?.ok === false) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tObject.assign(data, stackLayout.data);\n\t\t\t\tnewLayoutStack.push(stackLayout);\n\t\t\t}\n\t\t}\n\t}\n\tlet endPointResponse = await loadClientAndServerData(\n\t\tdata,\n\t\tdocument.location.origin + path,\n\t\tparams,\n\t\tclientEndPoint,\n\t\tserverEndPoint,\n\t);\n\tif (endPointResponse?.ok === false) {\n\t\treturn;\n\t}\n\treturn data;\n}\n\nasync function loadClientAndServerData(\n\tdata: Record<string, any>,\n\tlocation: string,\n\tparams: Record<string, string>,\n\tclientEndPoint?: PageEndPoint,\n\tserverEndPoint?: PageServerEndPoint,\n): Promise<Response | undefined | void> {\n\tlet prefetchedData = client.prefetchedData;\n\n\tif (clientEndPoint?.load) {\n\t\tif (prefetchedData[location]) {\n\t\t\tObject.assign(data, prefetchedData[location]);\n\t\t} else {\n\t\t\tconst clientUrl = new URL(document.location.href);\n\t\t\tconst clientParams = buildClientParams(clientUrl, params, data);\n\t\t\tconst clientResponse = await clientEndPoint.load(clientParams);\n\t\t\tif (clientResponse) {\n\t\t\t\tif (clientResponse.ok) {\n\t\t\t\t\tif (clientResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\t\tconst clientData = await clientResponse.json();\n\t\t\t\t\t\tObject.assign(data, clientData);\n\t\t\t\t\t\tprefetchedData[location] = clientData;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn clientResponse;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (serverEndPoint?.load) {\n\t\tconst serverUrl = location.replace(/\\/$/, \"\") + \"/~server\";\n\n\t\tif (prefetchedData[serverUrl]) {\n\t\t\tObject.assign(data, prefetchedData[serverUrl]);\n\t\t} else {\n\t\t\tconst serverResponse = await fetch(serverUrl);\n\t\t\tif (serverResponse) {\n\t\t\t\tif (serverResponse.ok) {\n\t\t\t\t\tif (serverResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\t\tconst serverData = await serverResponse.json();\n\t\t\t\t\t\tObject.assign(data, serverData);\n\t\t\t\t\t\tprefetchedData[serverUrl] = serverData;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn serverResponse;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction buildClientParams(url: URL, params: Record<string, string>, data: Record<string, any>) {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tdata,\n\t};\n}\n","import { clearLayoutSlot, fillLayoutSlot, hydrate } from \"@torpor/view\";\nimport { type Component, type SlotRender } from \"@torpor/view\";\nimport { mount } from \"@torpor/view\";\nimport $page from \"../state/$page\";\nimport client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint\";\nimport formSubmit from \"./formSubmit\";\nimport loadData from \"./loadData\";\n\n// @ts-ignore\nexport default async function navigate(url: URL, withHydration = false): Promise<boolean> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn false;\n\t}\n\n\tconst path = url.pathname;\n\tconst query = url.searchParams;\n\n\t//console.log(`navigating to '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\tconst route = client.router.match(path, query);\n\tif (!route) {\n\t\t// TODO: 404\n\t\tconsole.log(\"404\");\n\t\treturn false;\n\t}\n\n\t// Update $page before building the components\n\t$page.url = url;\n\tif (path.endsWith(\"/_error\")) {\n\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t// Make it look a bit classier by removing the query\n\t\twindow.history.replaceState({}, \"\", url.toString().split(\"?\")[0]);\n\t} else {\n\t\t$page.status = 200;\n\t}\n\tconst handler = route.handler;\n\tconst params = route.params || {};\n\n\t// There must be a client endpoint with a component\n\tconst clientEndPoint: PageEndPoint | undefined = (await handler.endPoint()).default;\n\tif (!clientEndPoint?.component) {\n\t\t// TODO: 404\n\t\tconsole.log(\"404\");\n\t\treturn false;\n\t}\n\n\t// There may be a server endpoint\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint())?.default;\n\n\tlet newLayoutStack: LayoutPath[] = [];\n\n\t// Pass the data into $props\n\t// TODO: Don't load if this is the first time -- it should have been passed\n\t// to us, somehow...\n\tconst data = await loadData(\n\t\thandler,\n\t\tparams,\n\t\tpath,\n\t\tnewLayoutStack,\n\t\tclientEndPoint,\n\t\tserverEndPoint,\n\t);\n\t// We may have form data in a hidden input -- not sure if this is the best\n\t// way to do it\n\tlet formInput = document.getElementById(\"t-form-data\") as HTMLInputElement;\n\tlet form: Record<string, string> | undefined;\n\tif (formInput) {\n\t\tform = JSON.parse(formInput.value);\n\t\t$page.form = form;\n\t\tformInput.remove();\n\t}\n\tlet $props: Record<string, any> = { data };\n\n\t// We may have form data in $page.form, either from the hidden input\n\t// (above), or added via onformsubmit (below)\n\t$props.form = $page.form;\n\n\t// Add some special context for submitting Forms client-side\n\tconst $context = {\n\t\tTorporBuildContext: { onformsubmit: formSubmit },\n\t};\n\n\tclient.layoutStack.push({ path: route.handler.path, data: {}, reuse: false, slotRange: null });\n\tclient.layoutStack = newLayoutStack;\n\tlet layoutStack = client.layoutStack;\n\n\t// If there are layouts, work our way upwards, pushing each component into\n\t// the default slot of its parent\n\t// TODO: There's probably a nicer way to do this with reducers or something\n\tlet component = clientEndPoint.component as Component;\n\tlet slots: Record<string, SlotRender> | undefined = undefined;\n\tif (handler.layouts) {\n\t\tlet slotFunctions: SlotRender[] = [];\n\t\t// The last slot function will render the client component\n\t\tslotFunctions[handler.layouts.length] = function clientComponent(parent, anchor) {\n\t\t\tlet i = layoutStack.length - 1;\n\t\t\tlayoutStack[i].slotRange = fillLayoutSlot(\n\t\t\t\tclientEndPoint.component!,\n\t\t\t\tslotFunctions[i + 1],\n\t\t\t\tparent,\n\t\t\t\tanchor,\n\t\t\t\t$props,\n\t\t\t\t$context,\n\t\t\t);\n\t\t};\n\n\t\t// Each earlier slot function will render a layout\n\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t?.default;\n\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\tif (layoutStack[i].reuse) {\n\t\t\t\t\t// Set the parent to add the new content to (from the old\n\t\t\t\t\t// content), clear the range under this point, and set the\n\t\t\t\t\t// component to the slot function within this layout\n\t\t\t\t\tparent = layoutStack[i].slotRange.startNode.parentNode as HTMLElement;\n\t\t\t\t\tclearLayoutSlot(layoutStack[i].slotRange);\n\t\t\t\t\tcomponent = slotFunctions[i + 1];\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (i === 0) {\n\t\t\t\t\tcomponent = layoutEndPoint.component as Component;\n\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t} else {\n\t\t\t\t\tslotFunctions[i] = function layoutComponent(parent, anchor, _, $context) {\n\t\t\t\t\t\tlayoutStack[i - 1].slotRange = fillLayoutSlot(\n\t\t\t\t\t\t\tlayoutEndPoint.component!,\n\t\t\t\t\t\t\tslotFunctions[i + 1],\n\t\t\t\t\t\t\tparent,\n\t\t\t\t\t\t\tanchor,\n\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (withHydration) {\n\t\thydrate(parent, component, $props, slots);\n\t} else {\n\t\ttry {\n\t\t\tmount(parent, component, $props, slots);\n\t\t} catch (error) {\n\t\t\t// TODO: Show a proper Error component\n\t\t\tparent.innerHTML = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\tconsole.log(error);\n\t\t}\n\t}\n\n\t// Reset prefetched data on each navigation\n\tclient.prefetchedData = {};\n\n\treturn true;\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path.\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn await navigate(url);\n}\n"],"mappings":";;;;AAGA,MAAMA,SAAsB,UAAU,CAAC;AAEvC,qBAAe;;;;;;;ACAf,eAA8B,SAA2B;CACxD,MAAM,MAAM,IAAI,IAAI,SAAS,SAAS,KAAK;AAC3C,QAAO,MAAM,SAAS,IAAI;;;;;ACH3B,eAA8B,WAAW,GAA+B;AAEvE,GAAE,gBAAgB;AAIlB,eAAM,OAAO;CAGb,MAAM,OAAO,EAAE;CACf,MAAM,UAAU;EACf,MAAM,IAAI,SAAS,KAAK;EACxB,QAAQ;EACR,MAAM;EACN,aAAa;EAIb,SAAS,EACR,wBAAwB,IACxB;EACD;CACD,MAAM,WAAW,MAAM,MACtB,KAAK,QAEL,QACA;AAED,KAAI,SAAS,WAAW,OAAO,SAAS,QAAQ,IAAI,yBAAyB,EAAE;EAE9E,MAAM,WAAW,SAAS,QAAQ,IAAI,WAAW;AACjD,QAAM,KAAK,SAAS;AACpB,SAAO,SAAS,OAAO;YAEtB,SAAS,UAAU,OAAO,SAAS,UAAU,OAC7C,SAAS,UAAU,OAAO,SAAS,UAAU,KAC7C;AAED,MAAI,S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UAAU,GAClF;AACH,OAAI,gBAAgB,UACnB,KAAI,YAAY,GAAG,OAAO;AAIzB,aAAS,YAAY,GAAG,UAAU,UAAU;AAC5C,oBAAgB,YAAY,GAAG,UAAU;AACzC,gBAAY,cAAc,IAAI;AAC9B;cACU,MAAM,GAAG;AACnB,gBAAY,eAAe;AAC3B,YAAQ,EAAE,GAAG,cAAc,IAAI,IAAI;SAEnC,eAAc,KAAK,SAAS,gBAAgB,UAAQ,QAAQ,GAAG,YAAU;AACxE,gBAAY,IAAI,GAAG,YAAY,eAC9B,eAAe,WACf,cAAc,IAAI,IAClBD,UACA,QACA,QACAE,WACA;;;;AAON,KAAI,cACH,SAAQ,QAAQ,WAAW,QAAQ,MAAM;KAEzC,KAAI;AACH,QAAM,QAAQ,WAAW,QAAQ,MAAM;UAC/B,OAAO;AAEf,SAAO,YAAY,6DAA2D,QAAQ;AACtF,UAAQ,IAAI,MAAM;;AAKpB,gBAAO,iBAAiB,EAAE;AAE1B,QAAO;;;;;;;;AC5JR,eAA8B,KAAK,MAAgC;CAClE,MAAM,MAAM,IAAI,IAAI,MAAM,SAAS,SAAS,KAAK;AACjD,QAAO,MAAM,SAAS,IAAI"}
@@ -1,7 +1,7 @@
1
1
  import { serverError } from "./response-D-XpIuMH.js";
2
2
  import { Server, connectMiddleware } from "./connectMiddleware-DbLj0St1.js";
3
3
  import fs, { existsSync, promises, readFileSync } from "node:fs";
4
- import fpath from "node:path";
4
+ import path from "node:path";
5
5
  import { build, createServer, defineConfig, transformWithEsbuild } from "vite";
6
6
  import torpor from "@torpor/unplugin/vite";
7
7
  import estorpor from "@torpor/unplugin/esbuild";
@@ -30,9 +30,9 @@ ${!serverRequest ? "const load = { default: { load: true } };" : ""}
30
30
  export default {
31
31
  routes: [
32
32
  ${site.routes.map((r) => {
33
- if (serverRequest || !/server\.(ts|js)$/.test(r.file)) return `{ path: "${r.path}", type: ${r.type}, endPoint: ${serverRequest || !/server\.(ts|js)$/.test(r.file) ? `() => import(/* @vite-ignore */ "${fpath.join(site.root, r.file)}")` : "undefined"} }`;
33
+ if (serverRequest || !/server\.(ts|js)$/.test(r.file)) return `{ path: "${r.path}", type: ${r.type}, endPoint: ${serverRequest || !/server\.(ts|js)$/.test(r.file) ? `() => import(/* @vite-ignore */ "${path.join(site.root, r.file)}")` : "undefined"} }`;
34
34
  else {
35
- const haveLoad = readFileSync(fpath.join(site.root, r.file)).includes("load:");
35
+ const haveLoad = readFileSync(path.join(site.root, r.file)).includes("load:");
36
36
  return `{ path: "${r.path}", type: ${r.type}, endPoint: ${haveLoad ? "() => load" : "undefined"} }`;
37
37
  }
38
38
  }).join(",\n ")}
@@ -47,15 +47,15 @@ export default {
47
47
  //#endregion
48
48
  //#region src/run/runBuild.ts
49
49
  async function runBuild(site) {
50
- const distFolder = fpath.resolve(site.root, "dist");
50
+ const distFolder = path.resolve(site.root, "dist");
51
51
  if (existsSync(distFolder)) await promises.rm(distFolder, { recursive: true });
52
- const clientFolder = fpath.join(distFolder, "client");
53
- const serverFolder = fpath.join(distFolder, "server");
52
+ const clientFolder = path.join(distFolder, "client");
53
+ const serverFolder = path.join(distFolder, "server");
54
54
  if (site.adapter.prebuild) await site.adapter.prebuild(site);
55
- let siteHtml = fpath.resolve(site.root, "src/site.html");
56
- const siteFolder = fpath.resolve(site.root, "./node_modules/@torpor/build/src/site/");
57
- let clientScript = fpath.join(siteFolder, "clientEntry.ts");
58
- let serverScript = fpath.join(siteFolder, "serverEntry.ts");
55
+ let siteHtml = path.resolve(site.root, "src/site.html");
56
+ const siteFolder = path.resolve(site.root, "./node_modules/@torpor/build/src/site/");
57
+ let clientScript = path.join(siteFolder, "clientEntry.ts");
58
+ let serverScript = path.join(siteFolder, "serverEntry.ts");
59
59
  const clientConfig = structuredClone(site.viteConfig ?? {});
60
60
  clientConfig.plugins = [
61
61
  manifest(site),
@@ -68,7 +68,7 @@ async function runBuild(site) {
68
68
  clientConfig.build.rollupOptions.input = [
69
69
  siteHtml,
70
70
  clientScript,
71
- ...site.routes.filter((r) => !/server\.(ts|js)$/.test(r.file)).map((r) => fpath.resolve(site.root, r.file)),
71
+ ...site.routes.filter((r) => !/server\.(ts|js)$/.test(r.file)).map((r) => path.resolve(site.root, r.file)),
72
72
  ...site.inputs.filter((f) => !/server\.(ts|js)$/.test(f))
73
73
  ];
74
74
  clientConfig.build.ssrManifest = true;
@@ -84,14 +84,14 @@ async function runBuild(site) {
84
84
  serverConfig.build.rollupOptions ??= {};
85
85
  serverConfig.build.rollupOptions.input = [
86
86
  serverScript,
87
- ...site.routes.map((r) => fpath.resolve(site.root, r.file)),
87
+ ...site.routes.map((r) => path.resolve(site.root, r.file)),
88
88
  ...site.inputs
89
89
  ];
90
90
  serverConfig.build.ssr = serverScript;
91
91
  await build(defineConfig(serverConfig));
92
- siteHtml = fpath.join(clientFolder, "site.html");
93
- await promises.rename(fpath.join(clientFolder, "src", "site.html"), siteHtml);
94
- await promises.rm(fpath.join(clientFolder, "src"), { recursive: true });
92
+ siteHtml = path.join(clientFolder, "site.html");
93
+ await promises.rename(path.join(clientFolder, "src", "site.html"), siteHtml);
94
+ await promises.rm(path.join(clientFolder, "src"), { recursive: true });
95
95
  if (site.adapter.postbuild) await site.adapter.postbuild(site);
96
96
  }
97
97
 
@@ -134,12 +134,12 @@ async function runDev(site) {
134
134
  config.optimizeDeps.esbuildOptions.plugins ??= [];
135
135
  config.optimizeDeps.esbuildOptions.plugins.push(estorpor());
136
136
  const vite = await createServer(config);
137
- const templateFile = fpath.resolve(site.root, "src/site.html");
137
+ const templateFile = path.resolve(site.root, "src/site.html");
138
138
  let template = await promises.readFile(templateFile, "utf-8");
139
139
  template = await vite.transformIndexHtml("", template);
140
- const siteFolder = fpath.resolve(site.root, "./node_modules/@torpor/build/src/site/");
141
- let clientScript = fpath.join(siteFolder, "clientEntry.ts");
142
- let serverScript = fpath.join(siteFolder, "serverEntry.ts");
140
+ const siteFolder = path.resolve(site.root, "./node_modules/@torpor/build/src/site/");
141
+ let clientScript = path.join(siteFolder, "clientEntry.ts");
142
+ let serverScript = path.join(siteFolder, "serverEntry.ts");
143
143
  template = prepareTemplate(template, clientScript);
144
144
  server.use(connectMiddleware(vite.middlewares));
145
145
  server.add("*", async (ev) => {
@@ -247,32 +247,32 @@ const types = {
247
247
  //#region src/run/runPreview.ts
248
248
  async function runPreview(site) {
249
249
  await runBuild(site);
250
- const distFolder = fpath.resolve(site.root, "dist");
251
- const clientFolder = fpath.join(distFolder, "client");
252
- const serverFolder = fpath.join(distFolder, "server");
253
- let clientScript = (await promises.readdir(fpath.join(clientFolder, "assets"))).find((f) => f.startsWith("clientEntry-"));
250
+ const distFolder = path.resolve(site.root, "dist");
251
+ const clientFolder = path.join(distFolder, "client");
252
+ const serverFolder = path.join(distFolder, "server");
253
+ let clientScript = (await promises.readdir(path.join(clientFolder, "assets"))).find((f) => f.startsWith("clientEntry-"));
254
254
  if (!clientScript) throw new Error("clientEntry.js not found");
255
255
  clientScript = `/assets/${clientScript}`;
256
- let siteHtml = fpath.join(clientFolder, "site.html");
256
+ let siteHtml = path.join(clientFolder, "site.html");
257
257
  let template = await promises.readFile(siteHtml, "utf-8");
258
258
  template = prepareTemplate(template, clientScript);
259
259
  const server = new Server();
260
260
  server.add("/assets/*", async (ev) => {
261
261
  try {
262
262
  const url = new URL(ev.request.url);
263
- const file = fpath.join(site.root, "dist", "client", url.pathname);
263
+ const file = path.join(site.root, "dist", "client", url.pathname);
264
264
  if (existsSync(file)) {
265
265
  const body = bufferToArrayBuffer(await promises.readFile(file));
266
266
  return new Response(body, {
267
267
  status: 200,
268
- headers: { "Content-Type": contentType(fpath.extname(file)) }
268
+ headers: { "Content-Type": contentType(path.extname(file)) }
269
269
  });
270
270
  }
271
271
  } catch (e) {
272
272
  return serverError(e);
273
273
  }
274
274
  });
275
- const serverScript = fpath.resolve(serverFolder, "serverEntry.js");
275
+ const serverScript = path.resolve(serverFolder, "serverEntry.js");
276
276
  server.add("*", async (ev) => {
277
277
  try {
278
278
  const { load } = await import(serverScript);
@@ -296,11 +296,11 @@ function bufferToArrayBuffer(buffer) {
296
296
  async function run(folder, mode) {
297
297
  let configFile = "";
298
298
  let deleteConfigFile = false;
299
- const jsConfigFile = fpath.join(folder, "site.config.js");
300
- const tsConfigFile = fpath.join(folder, "site.config.ts");
299
+ const jsConfigFile = path.join(folder, "site.config.js");
300
+ const tsConfigFile = path.join(folder, "site.config.ts");
301
301
  if (fs.existsSync(jsConfigFile)) configFile = jsConfigFile;
302
302
  else if (fs.existsSync(tsConfigFile)) {
303
- configFile = fpath.join(folder, "site.config.temp.js");
303
+ configFile = path.join(folder, "site.config.temp.js");
304
304
  let source = fs.readFileSync(tsConfigFile, "utf-8");
305
305
  let transformed = await transformWithEsbuild(source, tsConfigFile, { loader: "ts" });
306
306
  fs.writeFileSync(configFile, transformed.code);
@@ -328,4 +328,4 @@ async function run(folder, mode) {
328
328
 
329
329
  //#endregion
330
330
  export { run, runBuild, runDev, runPreview };
331
- //# sourceMappingURL=run-CNdaKSPR.js.map
331
+ //# sourceMappingURL=run-CVKpO0HO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-CVKpO0HO.js","names":["fs","createViteServer","fs","e: any","types: Record<string, string>","fs","e: any"],"sources":["../src/site/manifest.ts","../src/run/runBuild.ts","../src/run/prepareTemplate.ts","../src/run/runDev.ts","../src/server/contentType.ts","../src/run/runPreview.ts","../src/run/run.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Plugin } from \"vite\";\nimport Site from \"./Site\";\n\nconst moduleId = \"@torpor/build/manifest\";\n\n/**\n * A Vite plugin that provides information about the app to both clientEntry and\n * serverEntry.\n */\nexport default function manifest(site: Site, server = false): Plugin {\n\treturn {\n\t\tname: \"torpor-manifest\",\n\t\tresolveId: {\n\t\t\torder: \"pre\",\n\t\t\thandler(id) {\n\t\t\t\tif (id === moduleId) {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// @ts-ignore\n\t\tload(id, viteOptions) {\n\t\t\tif (id === moduleId) {\n\t\t\t\tlet serverRequest = server && !!viteOptions?.ssr;\n\t\t\t\treturn `\n${!serverRequest ? \"const load = { default: { load: true } };\" : \"\"}\nexport default {\n routes: [\n ${site.routes\n\t\t\t.map((r) => {\n\t\t\t\tif (serverRequest || !/server\\.(ts|js)$/.test(r.file)) {\n\t\t\t\t\treturn `{ path: \"${r.path}\", type: ${r.type}, endPoint: ${serverRequest || !/server\\.(ts|js)$/.test(r.file) ? `() => import(/* @vite-ignore */ \"${path.join(site.root, r.file)}\")` : \"undefined\"} }`;\n\t\t\t\t} else {\n\t\t\t\t\t// On the client, for a server route, we need to check\n\t\t\t\t\t// whether there's a load function and set a dummy endPoint\n\t\t\t\t\t// if so. The correct endpoint will be hit in clientEntry\n\t\t\t\t\t// HACK: Should do this better than checking for `load:` in source...\n\t\t\t\t\tconst haveLoad = readFileSync(path.join(site.root, r.file)).includes(\"load:\");\n\t\t\t\t\treturn `{ path: \"${r.path}\", type: ${r.type}, endPoint: ${haveLoad ? \"() => load\" : \"undefined\"} }`;\n\t\t\t\t}\n\t\t\t})\n\t\t\t.join(\",\\n \")}\n ],\n};\n`;\n\t\t\t}\n\t\t},\n\t};\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { build, defineConfig } from \"vite\";\nimport Site from \"../site/Site\";\nimport manifest from \"../site/manifest.ts\";\n\n// TODO: Don't cache index.html in dev?\n// TODO: Multiple hook.server locations\n// TODO: Don't reload layouts during client routing\n// TODO: Call the correct +page and +server routes when in the same folder\n\nexport default async function runBuild(site: Site): Promise<void> {\n\t// Delete the dist folder if it exists\n\tconst distFolder = path.resolve(site.root, \"dist\");\n\tif (existsSync(distFolder)) {\n\t\tawait fs.rm(distFolder, { recursive: true });\n\t}\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// HOOK: Prebuild\n\tif (site.adapter.prebuild) {\n\t\tawait site.adapter.prebuild(site);\n\t}\n\n\t// TODO: From a setting\n\tlet siteHtml = path.resolve(site.root, \"src/site.html\");\n\n\t// TODO: Is this going to be the correct path after installing from npm?\n\tconst siteFolder = path.resolve(site.root, \"./node_modules/@torpor/build/src/site/\");\n\tlet clientScript = path.join(siteFolder, \"clientEntry.ts\");\n\tlet serverScript = path.join(siteFolder, \"serverEntry.ts\");\n\n\t// Build the client assets, including site.html and the route files\n\t// EXCLUDING anything with `server.js` in the name\n\tconst clientConfig = structuredClone(site.viteConfig ?? {});\n\tclientConfig.plugins = [manifest(site), torpor(), ...site.plugins];\n\tclientConfig.build ??= {};\n\tclientConfig.build.outDir = clientFolder;\n\tclientConfig.build.rollupOptions ??= {};\n\tclientConfig.build.rollupOptions.input = [\n\t\tsiteHtml,\n\t\tclientScript,\n\t\t...site.routes\n\t\t\t.filter((r) => !/server\\.(ts|js)$/.test(r.file))\n\t\t\t.map((r) => path.resolve(site.root, r.file)),\n\t\t...site.inputs.filter((f) => !/server\\.(ts|js)$/.test(f)),\n\t];\n\tclientConfig.build.ssrManifest = true;\n\tawait build(defineConfig(clientConfig));\n\n\t// Build the server assets, including the server entry script and the route\n\t// files\n\tconst serverConfig = structuredClone(site.viteConfig ?? {});\n\tserverConfig.plugins = [manifest(site, true), torpor(), ...site.plugins];\n\tserverConfig.build ??= {};\n\tserverConfig.build.outDir = serverFolder;\n\tserverConfig.build.rollupOptions ??= {};\n\tserverConfig.build.rollupOptions.input = [\n\t\tserverScript,\n\t\t...site.routes.map((r) => path.resolve(site.root, r.file)),\n\t\t...site.inputs,\n\t];\n\tserverConfig.build.ssr = serverScript;\n\tawait build(defineConfig(serverConfig));\n\n\t// Move the site.html file into /client\n\t// HACK: Should do this in Rollup if possible?\n\tsiteHtml = path.join(clientFolder, \"site.html\");\n\tawait fs.rename(path.join(clientFolder, \"src\", \"site.html\"), siteHtml);\n\tawait fs.rm(path.join(clientFolder, \"src\"), { recursive: true });\n\n\t// HOOK: Postbuild\n\tif (site.adapter.postbuild) {\n\t\tawait site.adapter.postbuild(site);\n\t}\n}\n","export default function prepareTemplate(template: string, clientScript: string): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet bodyStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)\\s+/);\n\tbodyStart = result.indexOf(\">\", bodyStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyStart === -1 || bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import estorpor from \"@torpor/unplugin/esbuild\";\nimport torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { createServer as createViteServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport connectMiddleware from \"../server/connect/connectMiddleware.ts\";\nimport Site from \"../site/Site.ts\";\nimport manifest from \"../site/manifest.ts\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\nexport default async function runDev(site: Site): Promise<void> {\n\tconst server = new Server();\n\n\t// Create the Vite server in middleware mode and configure the app type as\n\t// \"custom\", disabling Vite's own HTML serving logic so the parent server\n\t// can take control\n\tconst config = structuredClone(site.viteConfig ?? {});\n\tconfig.server = { middlewareMode: true };\n\tconfig.appType = \"custom\";\n\tconfig.plugins = [manifest(site, true), torpor(), ...site.plugins];\n\n\t// HACK: To be able to import `.torp` files from barrel files in\n\t// node_modules, we need to add their libraries to `ssr.noExternal` in\n\t// site.config.ts, and let esbuild know how to compile them here\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.extensions ??= [];\n\tconfig.optimizeDeps.extensions.push(\".torp\");\n\tconfig.optimizeDeps.esbuildOptions ??= {};\n\tconfig.optimizeDeps.esbuildOptions.plugins ??= [];\n\tconfig.optimizeDeps.esbuildOptions.plugins.push(estorpor());\n\n\tconst vite = await createViteServer(config);\n\n\t// Read site.html\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc)\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tlet template = await fs.readFile(templateFile, \"utf-8\");\n\n\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t// universal transform, not individual transforms for each route\n\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t// TODO: Is this going to be the correct path after installing from npm?\n\tconst siteFolder = path.resolve(site.root, \"./node_modules/@torpor/build/src/site/\");\n\tlet clientScript = path.join(siteFolder, \"clientEntry.ts\");\n\tlet serverScript = path.join(siteFolder, \"serverEntry.ts\");\n\n\t// Prepare site.html so that we can just splice components into it\n\ttemplate = prepareTemplate(template, clientScript);\n\n\t// Use Vite's Connect instance as middleware. We need to wrap it with\n\t// createMiddlewareHandler that converts Connect middleware to\n\t// Request/Response web handlers\n\tserver.use(connectMiddleware(vite.middlewares));\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Serve the site\n\tsite.adapter.serve(server, site);\n}\n","// From https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n\nexport default function contentType(extension: string): string {\n\treturn types[extension] || \"application/octet-stream\";\n}\n\nconst types: Record<string, string> = {\n\t\".aac\": \"audio/aac\",\n\t\".abw\": \"application/x-abiword\",\n\t\".apng\": \"image/apng\",\n\t\".arc\": \"application/x-freearc\",\n\t\".avif\": \"image/avif\",\n\t\".avi\": \"video/x-msvideo\",\n\t\".azw\": \"application/vnd.amazon.ebook\",\n\t\".bin\": \"application/octet-stream\",\n\t\".bmp\": \"image/bmp\",\n\t\".bz\": \"application/x-bzip\",\n\t\".bz2\": \"application/x-bzip2\",\n\t\".cda\": \"application/x-cdf\",\n\t\".csh\": \"application/x-csh\",\n\t\".css\": \"text/css\",\n\t\".csv\": \"text/csv\",\n\t\".doc\": \"application/msword\",\n\t\".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n\t\".eot\": \"application/vnd.ms-fontobject\",\n\t\".epub\": \"application/epub+zip\",\n\t\".gz\": \"application/gzip\",\n\t\".gif\": \"image/gif\",\n\t\".htm\": \"text/html\",\n\t\".html\": \"text/html\",\n\t\".ico\": \"image/vnd.microsoft.icon\",\n\t\".ics\": \"text/calendar\",\n\t\".jar\": \"application/java-archive\",\n\t\".jpeg\": \"image/jpeg\",\n\t\".jpg\": \"image/jpeg\",\n\t\".js\": \"text/javascript\",\n\t\".json\": \"application/json\",\n\t\".jsonld\": \"application/ld+json\",\n\t\".mid\": \"audio/midi\",\n\t\".midi\": \"audio/midi\",\n\t\".mjs\": \"text/javascript\",\n\t\".mp3\": \"audio/mpeg\",\n\t\".mp4\": \"video/mp4\",\n\t\".mpeg\": \"video/mpeg\",\n\t\".mpkg\": \"application/vnd.apple.installer+xml\",\n\t\".odp\": \"application/vnd.oasis.opendocument.presentation\",\n\t\".ods\": \"application/vnd.oasis.opendocument.spreadsheet\",\n\t\".odt\": \"application/vnd.oasis.opendocument.text\",\n\t\".oga\": \"audio/ogg\",\n\t\".ogv\": \"video/ogg\",\n\t\".ogx\": \"application/ogg\",\n\t\".opus\": \"audio/ogg\",\n\t\".otf\": \"font/otf\",\n\t\".png\": \"image/png\",\n\t\".pdf\": \"application/pdf\",\n\t\".php\": \"application/x-httpd-php\",\n\t\".ppt\": \"application/vnd.ms-powerpoint\",\n\t\".pptx\": \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n\t\".rar\": \"application/vnd.rar\",\n\t\".rtf\": \"application/rtf\",\n\t\".sh\": \"application/x-sh\",\n\t\".svg\": \"image/svg+xml\",\n\t\".tar\": \"application/x-tar\",\n\t\".tif\": \"image/tiff\",\n\t\".tiff\": \"image/tiff\",\n\t\".ts\": \"video/mp2t\",\n\t\".ttf\": \"font/ttf\",\n\t\".txt\": \"text/plain\",\n\t\".vsd\": \"application/vnd.visio\",\n\t\".wav\": \"audio/wav\",\n\t\".weba\": \"audio/webm\",\n\t\".webm\": \"video/webm\",\n\t\".webp\": \"image/webp\",\n\t\".woff\": \"font/woff\",\n\t\".woff2\": \"font/woff2\",\n\t\".xhtml\": \"application/xhtml+xml\",\n\t\".xls\": \"application/vnd.ms-excel\",\n\t\".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n\t\".xml\": \"application/xml\",\n\t\".xul\": \"application/vnd.mozilla.xul+xml\",\n\t\".zip\": \"application/zip\",\n\t\".3gp\": \"video/3gpp\",\n\t\".3g2\": \"video/3gpp2\",\n\t\".7z\": \"application/x-7z-compressed\",\n};\n","import { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport contentType from \"../server/contentType.ts\";\nimport Site from \"../site/Site\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\nimport runBuild from \"./runBuild\";\n\nexport default async function runPreview(site: Site): Promise<void> {\n\t// Build the site\n\tawait runBuild(site);\n\n\tconst distFolder = path.resolve(site.root, \"dist\");\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// Find the client script file in /assets\n\tlet clientScript = (await fs.readdir(path.join(clientFolder, \"assets\"))).find((f) =>\n\t\tf.startsWith(\"clientEntry-\"),\n\t);\n\tif (!clientScript) {\n\t\tthrow new Error(\"clientEntry.js not found\");\n\t}\n\tclientScript = `/assets/${clientScript}`;\n\n\t// Read site.html\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc)\n\tlet siteHtml = path.join(clientFolder, \"site.html\");\n\tlet template = await fs.readFile(siteHtml, \"utf-8\");\n\n\t// Prepare site.html so that we can just splice components into it\n\ttemplate = prepareTemplate(template, clientScript);\n\n\t// Configure the server\n\tconst server = new Server();\n\n\t// Serve dist/client/assets statically\n\tserver.add(\"/assets/*\", async (ev) => {\n\t\ttry {\n\t\t\tconst url = new URL(ev.request.url);\n\t\t\tconst file = path.join(site.root, \"dist\", \"client\", url.pathname);\n\t\t\tif (existsSync(file)) {\n\t\t\t\t// TODO: Stream the data?\n\t\t\t\tconst body = bufferToArrayBuffer(await fs.readFile(file));\n\t\t\t\treturn new Response(body, {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": contentType(path.extname(file)),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tconst serverScript = path.resolve(serverFolder, \"serverEntry.js\");\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry\n\t\t\tconst { load } = await import(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Serve the site\n\tsite.adapter.serve(server, site);\n}\n\n// From https://stackoverflow.com/a/79345620\n// No idea why it is needed\nfunction bufferToArrayBuffer(buffer: Buffer): ArrayBuffer {\n\treturn buffer.buffer.slice(\n\t\tbuffer.byteOffset,\n\t\tbuffer.byteOffset + buffer.byteLength,\n\t) as ArrayBuffer;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { transformWithEsbuild } from \"vite\";\nimport Site from \"../site/Site\";\nimport runBuild from \"./runBuild\";\nimport runDev from \"./runDev\";\nimport runPreview from \"./runPreview\";\n\nexport default async function run(\n\tfolder: string,\n\tmode: \"dev\" | \"build\" | \"preview\",\n): Promise<void> {\n\t// Look for and load a site.config.js/ts file in the working directory\n\tlet configFile = \"\";\n\tlet deleteConfigFile = false;\n\tconst jsConfigFile = path.join(folder, \"site.config.js\");\n\tconst tsConfigFile = path.join(folder, \"site.config.ts\");\n\tif (fs.existsSync(jsConfigFile)) {\n\t\t// If it's JS, we can just import it straight up\n\t\tconfigFile = jsConfigFile;\n\t} else if (fs.existsSync(tsConfigFile)) {\n\t\t// If it's TS, we need to convert it to JS\n\t\t// TODO: Put the generated file somewhere better (dist?)\n\t\tconfigFile = path.join(folder, \"site.config.temp.js\");\n\t\tlet source = fs.readFileSync(tsConfigFile, \"utf-8\");\n\t\tlet transformed = await transformWithEsbuild(source, tsConfigFile, {\n\t\t\tloader: \"ts\",\n\t\t});\n\t\tfs.writeFileSync(configFile, transformed.code);\n\t\tdeleteConfigFile = true;\n\t} else {\n\t\tthrow new Error(\"site.config file not found\");\n\t}\n\n\tconst site = (await import(configFile)).default as Site;\n\tif (!site || !site.root || !site.routes) {\n\t\tthrow new Error(\"Invalid site in config file\");\n\t}\n\tif (deleteConfigFile) {\n\t\tfs.rmSync(configFile);\n\t}\n\n\tswitch (mode) {\n\t\tcase \"dev\": {\n\t\t\tawait runDev(site);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"build\": {\n\t\t\tawait runBuild(site);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"preview\": {\n\t\t\tawait runPreview(site);\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\tconsole.log(\"No mode passed, running in dev\");\n\t\t\tawait runDev(site);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;AAKA,MAAM,WAAW;;;;;AAMjB,SAAwB,SAAS,MAAY,SAAS,OAAe;AACpE,QAAO;EACN,MAAM;EACN,WAAW;GACV,OAAO;GACP,QAAQ,IAAI;AACX,QAAI,OAAO,SACV,QAAO;;GAGT;EAED,KAAK,IAAI,aAAa;AACrB,OAAI,OAAO,UAAU;IACpB,IAAI,gBAAgB,UAAU,CAAC,CAAC,aAAa;AAC7C,WAAO;EACT,CAAC,gBAAgB,8CAA8C,GAAG;;;MAG9D,KAAK,OACP,KAAK,MAAM;AACX,SAAI,iBAAiB,CAAC,mBAAmB,KAAK,EAAE,KAAK,CACpD,QAAO,YA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Q,IAAI,SAAS;AAGrB,MAAK,QAAQ,MAAM,QAAQ,KAAK;;AAKjC,SAAS,oBAAoB,QAA6B;AACzD,QAAO,OAAO,OAAO,MACpB,OAAO,YACP,OAAO,aAAa,OAAO,WAC3B;;;;;ACnFF,eAA8B,IAC7B,QACA,MACgB;CAEhB,IAAI,aAAa;CACjB,IAAI,mBAAmB;CACvB,MAAM,eAAe,KAAK,KAAK,QAAQ,iBAAiB;CACxD,MAAM,eAAe,KAAK,KAAK,QAAQ,iBAAiB;AACxD,KAAI,GAAG,WAAW,aAAa,CAE9B,cAAa;UACH,GAAG,WAAW,aAAa,EAAE;AAGvC,eAAa,KAAK,KAAK,QAAQ,sBAAsB;EACrD,IAAI,SAAS,GAAG,aAAa,cAAc,QAAQ;EACnD,IAAI,cAAc,MAAM,qBAAqB,QAAQ,cAAc,EAClE,QAAQ,MACR,CAAC;AACF,KAAG,cAAc,YAAY,YAAY,KAAK;AAC9C,qBAAmB;OAEnB,OAAM,IAAI,MAAM,6BAA6B;CAG9C,MAAM,QAAQ,MAAM,OAAO,aAAa;AACxC,KAAI,CAAC,QAAQ,CAAC,KAAK,QAAQ,CAAC,KAAK,OAChC,OAAM,IAAI,MAAM,8BAA8B;AAE/C,KAAI,iBACH,IAAG,OAAO,WAAW;AAGtB,SAAQ,MAAR;EACC,KAAK;AACJ,SAAM,OAAO,KAAK;AAClB;EAED,KAAK;AACJ,SAAM,SAAS,KAAK;AACpB;EAED,KAAK;AACJ,SAAM,WAAW,KAAK;AACtB;EAED;AACC,WAAQ,IAAI,iCAAiC;AAC7C,SAAM,OAAO,KAAK;AAClB"}
package/dist/run.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "./pathToRegex-CTgx7hQP.js";
2
2
  import "./seeOther-BmehiI4C.js";
3
3
  import "./response-D-XpIuMH.js";
4
- import { run, runBuild, runDev, runPreview } from "./run-CNdaKSPR.js";
4
+ import { run, runBuild, runDev, runPreview } from "./run-CVKpO0HO.js";
5
5
  import "./ServerEvent-2-CnAy1W.js";
6
6
  import "./connectMiddleware-DbLj0St1.js";
7
7
 
package/dist/state.js CHANGED
@@ -1,3 +1,3 @@
1
- import { $page_default } from "./_page-CsdPubw4.js";
1
+ import { $page_default } from "./_page-Cv6YWocY.js";
2
2
 
3
3
  export { $page_default as $page };
package/dist/test.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import "./pathToRegex-CTgx7hQP.js";
2
2
  import { HOOK_ROUTE, HOOK_SERVER_ROUTE, LAYOUT_ROUTE, LAYOUT_SERVER_ROUTE, PAGE_ROUTE, PAGE_SERVER_ROUTE, Router, SERVER_ROUTE } from "./RouteType-g8Ce5gOd.js";
3
- import { $page_default } from "./_page-CsdPubw4.js";
3
+ import { $page_default } from "./_page-Cv6YWocY.js";
4
4
  import { notFound, ok, seeOther } from "./seeOther-BmehiI4C.js";
5
5
  import { ServerEvent } from "./ServerEvent-2-CnAy1W.js";
6
- import fpath from "node:path";
6
+ import path from "node:path";
7
7
 
8
8
  //#region src/test/runTest.ts
9
9
  /**
@@ -25,16 +25,16 @@ async function runTest(site, route, ev) {
25
25
  type: r.type,
26
26
  endPoint: () => import(
27
27
  /* @vite-ignore */
28
- fpath.join(site.root, r.file)
28
+ path.join(site.root, r.file)
29
29
  )
30
30
  })));
31
31
  return await load(router, ev, "%COMPONENT_BODY%");
32
32
  }
33
33
  async function load(router, ev, template) {
34
34
  const url = new URL(ev.request.url);
35
- const path = url.pathname;
35
+ const path$1 = url.pathname;
36
36
  const query = url.searchParams;
37
- const route = router.match(path, query);
37
+ const route = router.match(path$1, query);
38
38
  if (!route) return notFound();
39
39
  $page_default.url = url;
40
40
  const handler = route.handler;
package/dist/test.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"test.js","names":["path","serverEndPoint: ServerEndPoint | undefined","serverHook: ServerHook | undefined","clientEndPoint: PageEndPoint | undefined","serverEndPoint: PageServerEndPoint | undefined","layoutEndPoint: PageEndPoint | undefined","layoutServerEndPoint: PageServerEndPoint | undefined","$props: Record<string, any>","slots: Record<string, ServerSlotRender> | undefined","slotFunctions: ServerSlotRender[]"],"sources":["../src/test/runTest.ts"],"sourcesContent":["import { type ServerComponent, type ServerSlotRender } from \"@torpor/view\";\nimport path from \"node:path\";\nimport notFound from \"../response/notFound.ts\";\nimport ok from \"../response/ok.ts\";\nimport seeOther from \"../response/seeOther.ts\";\nimport ServerEvent from \"../server/ServerEvent.ts\";\nimport Router from \"../site/Router.ts\";\nimport Site from \"../site/Site\";\nimport $page from \"../state/$page.ts\";\nimport type PageEndPoint from \"../types/PageEndPoint.ts\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint.ts\";\nimport type RouteHandler from \"../types/RouteHandler.ts\";\nimport {\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport type ServerEndPoint from \"../types/ServerEndPoint.ts\";\nimport type ServerHook from \"../types/ServerHook.ts\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent.ts\";\n\n/**\n * Runs a site route in test mode\n * @param site The site configuration, with routing configured\n * @param route The route path e.g. `/home`\n * @param ev An optional ServerEvent, which you can use to set test cookies and headers\n * @returns An HTTP response containing the requested data, HTML, or error status\n */\nexport default async function runTest(\n\tsite: Site,\n\troute: string,\n\tev?: ServerEvent,\n): Promise<Response> {\n\tif (!route.startsWith(\"/\")) route += \"/\";\n\tif (!ev) {\n\t\tconst req = new Request(`http://localhost${route}`);\n\t\tev = new ServerEvent(req);\n\t}\n\n\t// Build the router from the Site object created by the user\n\tconst router = new Router();\n\trouter.addPages(\n\t\tsite.routes.map((r) => ({\n\t\t\tpath: r.path,\n\t\t\ttype: r.type,\n\t\t\tendPoint: () => import(/* @vite-ignore */ path.join(site.root, r.file)),\n\t\t})),\n\t);\n\n\treturn await load(router, ev, \"%COMPONENT_BODY%\");\n}\n\n// HACK: This is a copy of serverEntry\n// TODO: Make it shared instead!\nasync function load(router: Router, ev: ServerEvent, template: string): Promise<Response> {\n\t//const url = new URL(`http://${process.env.HOST ?? \"localhost\"}${ev.request.url}`);\n\tconst url = new URL(ev.request.url);\n\tconst path = url.pathname;\n\tconst query = url.searchParams;\n\n\t//console.log(`handling ${ev.request.method} for '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\tconst route = router.match(path, query);\n\tif (!route) {\n\t\treturn notFound();\n\t}\n\n\t// Update $page before building the components\n\t// TODO: Find somewhere better to put this\n\t$page.url = url;\n\n\tconst handler = route.handler;\n\tconst params = route.params || {};\n\n\t// TODO: Hit the server hook out here\n\t// We could maybe set data loading up as middleware on a route??????\n\n\tswitch (handler.type) {\n\t\tcase PAGE_ROUTE:\n\t\tcase LAYOUT_ROUTE: {\n\t\t\t// It's a /+page.ts or /_layout.ts endpoint\n\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\treturn await loadView(ev, url, handler, params, template);\n\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\treturn await runAction(ev, url, handler, params, query);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase PAGE_SERVER_ROUTE:\n\t\tcase LAYOUT_SERVER_ROUTE: {\n\t\t\t// It's a /+page.server.ts or /_layout.server.ts endpoint\n\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\treturn await loadData(ev, url, handler, \"load\", params);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase SERVER_ROUTE: {\n\t\t\t// It's a /+server.ts endpoint\n\t\t\tconst functionName = ev.request.method.toLowerCase().replace(\"delete\", \"del\");\n\t\t\treturn await loadData(ev, url, handler, functionName, params);\n\t\t}\n\t\tcase HOOK_ROUTE:\n\t\tcase HOOK_SERVER_ROUTE: {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn notFound();\n}\n\nasync function loadData(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tfunctionName: string,\n\tparams: Record<string, string>,\n) {\n\tconst serverEndPoint: ServerEndPoint | undefined = (await handler.endPoint()).default;\n\tif (serverEndPoint && serverEndPoint[functionName]) {\n\t\tconst serverParams = buildServerParams(ev, url, params);\n\n\t\tif (handler.serverHook) {\n\t\t\tconst serverHook: ServerHook | undefined = (await handler.serverHook()).default;\n\t\t\tif (serverHook?.handle) {\n\t\t\t\tawait serverHook.handle(serverParams);\n\t\t\t}\n\t\t}\n\n\t\tconst result = await serverEndPoint[functionName](serverParams);\n\n\t\t// If there was no response returned from load (such as errors or a\n\t\t// redirect), send an ok response\n\t\treturn result || ok();\n\t}\n\n\treturn notFound();\n}\n\nasync function loadView(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\ttemplate: string,\n) {\n\t// There must be a client endpoint with a component\n\tconst clientEndPoint: PageEndPoint | undefined = (await handler.endPoint()).default;\n\tif (!clientEndPoint?.component) {\n\t\treturn notFound();\n\t}\n\n\t// There may be a server endpoint\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint())?.default;\n\n\t// Maybe hit the server hook\n\tconst serverParams = buildServerParams(ev, url, params);\n\tif (handler.serverHook) {\n\t\tconst serverHook: ServerHook | undefined = (await handler.serverHook()).default;\n\t\tif (serverHook?.handle) {\n\t\t\tawait serverHook.handle(serverParams);\n\t\t}\n\t}\n\n\t// Pass the data into $props\n\t// TODO: Promise.all\n\t// NOTE: We're loading data from top to bottom, overriding as we go, and I'm not sure if this is the best way to go\n\tlet data = {};\n\tif (handler.layouts) {\n\t\tfor (let layout of handler.layouts) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\tconst layoutResponse = await loadClientAndServerData(\n\t\t\t\turl,\n\t\t\t\tparams,\n\t\t\t\tserverParams,\n\t\t\t\tdata,\n\t\t\t\tlayoutEndPoint,\n\t\t\t\tlayoutServerEndPoint,\n\t\t\t);\n\t\t\tif (layoutResponse?.ok === false) {\n\t\t\t\treturn layoutResponse;\n\t\t\t}\n\t\t}\n\t}\n\tlet endPointResponse = await loadClientAndServerData(\n\t\turl,\n\t\tparams,\n\t\tserverParams,\n\t\tdata,\n\t\tclientEndPoint,\n\t\tserverEndPoint,\n\t);\n\tif (endPointResponse?.ok === false) {\n\t\treturn endPointResponse;\n\t}\n\tlet $props: Record<string, any> = { data };\n\n\t// If there are layouts, work our way upwards, pushing each component into\n\t// the default slot of its parent\n\t// TODO: Also handle layout server data\n\t// TODO: There's probably a nicer way to do this with reducers or something\n\t// TODO: Re-use parent layouts\n\tlet component = clientEndPoint.component as ServerComponent;\n\tlet slots: Record<string, ServerSlotRender> | undefined = undefined;\n\tif (handler.layouts) {\n\t\tlet slotFunctions: ServerSlotRender[] = [];\n\t\tslotFunctions[handler.layouts.length] = (_, context) =>\n\t\t\t(clientEndPoint.component as ServerComponent)($props, context);\n\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t?.default;\n\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\tif (i === 0) {\n\t\t\t\t\tcomponent = layoutEndPoint.component as ServerComponent;\n\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t} else {\n\t\t\t\t\tslotFunctions[i] = (_, context) =>\n\t\t\t\t\t\t(layoutEndPoint.component as ServerComponent)($props, context, {\n\t\t\t\t\t\t\t_: slotFunctions[i + 1],\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlet html;\n\ttry {\n\t\tlet { body, head } = component($props, undefined, slots);\n\t\thtml = template.replace(\"%COMPONENT_BODY%\", body).replace(\"%COMPONENT_HEAD\", head);\n\t} catch (error) {\n\t\t// TODO: Show a proper Error component\n\t\thtml = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\tconsole.log(error);\n\t}\n\n\treturn new Response(html, {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"text/html\",\n\t\t},\n\t});\n}\n\nasync function runAction(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\tquery: URLSearchParams,\n) {\n\tconst actionName = (Array.from(query.keys())[0] || \"default\").replace(/^\\//, \"\");\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint()).default;\n\tif (serverEndPoint?.actions) {\n\t\tconst action = serverEndPoint.actions[actionName];\n\t\tif (action) {\n\t\t\t// TODO: form.errors etc\n\t\t\tconst serverParams = buildServerParams(ev, url, params);\n\n\t\t\tif (handler.serverHook) {\n\t\t\t\tconst serverHook: ServerHook | undefined = (await handler.serverHook()).default;\n\t\t\t\tif (serverHook?.handle) {\n\t\t\t\t\tawait serverHook.handle(serverParams);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst result = await action(serverParams); // <--\n\n\t\t\t// If there was no response returned from the action (such as errors\n\t\t\t// or a redirect), reload the page by redirecting\n\t\t\treturn result || seeOther(url.pathname);\n\t\t}\n\t}\n\n\treturn notFound();\n}\n\nasync function loadClientAndServerData(\n\turl: URL,\n\tparams: Record<string, string>,\n\tserverParams: ServerLoadEvent,\n\tdata: Record<string, any>,\n\tclientEndPoint?: PageEndPoint,\n\tserverEndPoint?: PageServerEndPoint,\n) {\n\tif (clientEndPoint?.load) {\n\t\tconst clientParams = buildClientParams(url, data, params);\n\t\tconst clientResponse = await clientEndPoint.load(clientParams);\n\t\tif (clientResponse) {\n\t\t\tif (clientResponse.ok) {\n\t\t\t\tif (clientResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\tObject.assign(data, await clientResponse.json());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn clientResponse;\n\t\t\t}\n\t\t}\n\t}\n\tif (serverEndPoint?.load) {\n\t\tconst serverResponse = await serverEndPoint.load(serverParams);\n\t\tif (serverResponse) {\n\t\t\tif (serverResponse.ok) {\n\t\t\t\tif (serverResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\tObject.assign(data, await serverResponse.json());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn serverResponse;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction buildClientParams(url: URL, params: Record<string, string>, data: Record<string, any>) {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tdata,\n\t};\n}\n\nfunction buildServerParams(\n\tev: ServerEvent,\n\turl: URL,\n\tparams: Record<string, string>,\n): ServerLoadEvent {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tappData: {},\n\t\trequest: ev.request,\n\t\tcookies: ev.cookies,\n\t\theaders: ev.headers,\n\t\tadapter: ev.adapter,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,eAA8B,QAC7B,MACA,OACA,IACoB;AACpB,KAAI,CAAC,MAAM,WAAW,IAAI,CAAE,UAAS;AACrC,KAAI,CAAC,IAAI;EACR,MAAM,MAAM,IAAI,QAAQ,mBAAmB,QAAQ;AACnD,OAAK,IAAI,YAAY,IAAI;;CAI1B,MAAM,SAAS,IAAI,QAAQ;AAC3B,QAAO,SACN,KAAK,OAAO,KAAK,OAAO;EACvB,MAAM,EAAE;EACR,MAAM,EAAE;EACR,gBAAgB;;GAA0BA,MAAK,KAAK,KAAK,MAAM,EAAE,KAAK;;EACtE,EAAE,CACH;AAED,QAAO,MAAM,KAAK,QAAQ,IAAI,mBAAmB;;AAKlD,eAAe,KAAK,QAAgB,IAAiB,UAAqC;CAEzF,MAAM,MAAM,IAAI,IAAI,GAAG,QAAQ,IAAI;CACnC,MAAM,OAAO,IAAI;CACjB,MAAM,QAAQ,IAAI;CAIlB,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AAO;;;AAMX,SAAS,kBAAkB,KAAU,QAAgC,MAA2B;AAC/F,QAAO;EACN;EACA;EACA;EACA;;AAGF,SAAS,kBACR,IACA,KACA,QACkB;AAClB,QAAO;EACN;EACA;EACA,SAAS,EAAE;EACX,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ"}
1
+ {"version":3,"file":"test.js","names":["path","serverEndPoint: ServerEndPoint | undefined","serverHook: ServerHook | undefined","clientEndPoint: PageEndPoint | undefined","serverEndPoint: PageServerEndPoint | undefined","layoutEndPoint: PageEndPoint | undefined","layoutServerEndPoint: PageServerEndPoint | undefined","$props: Record<string, any>","slots: Record<string, ServerSlotRender> | undefined","slotFunctions: ServerSlotRender[]"],"sources":["../src/test/runTest.ts"],"sourcesContent":["import { type ServerComponent, type ServerSlotRender } from \"@torpor/view\";\nimport path from \"node:path\";\nimport notFound from \"../response/notFound.ts\";\nimport ok from \"../response/ok.ts\";\nimport seeOther from \"../response/seeOther.ts\";\nimport ServerEvent from \"../server/ServerEvent.ts\";\nimport Router from \"../site/Router.ts\";\nimport Site from \"../site/Site\";\nimport $page from \"../state/$page.ts\";\nimport type PageEndPoint from \"../types/PageEndPoint.ts\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint.ts\";\nimport type RouteHandler from \"../types/RouteHandler.ts\";\nimport {\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport type ServerEndPoint from \"../types/ServerEndPoint.ts\";\nimport type ServerHook from \"../types/ServerHook.ts\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent.ts\";\n\n/**\n * Runs a site route in test mode\n * @param site The site configuration, with routing configured\n * @param route The route path e.g. `/home`\n * @param ev An optional ServerEvent, which you can use to set test cookies and headers\n * @returns An HTTP response containing the requested data, HTML, or error status\n */\nexport default async function runTest(\n\tsite: Site,\n\troute: string,\n\tev?: ServerEvent,\n): Promise<Response> {\n\tif (!route.startsWith(\"/\")) route += \"/\";\n\tif (!ev) {\n\t\tconst req = new Request(`http://localhost${route}`);\n\t\tev = new ServerEvent(req);\n\t}\n\n\t// Build the router from the Site object created by the user\n\tconst router = new Router();\n\trouter.addPages(\n\t\tsite.routes.map((r) => ({\n\t\t\tpath: r.path,\n\t\t\ttype: r.type,\n\t\t\tendPoint: () => import(/* @vite-ignore */ path.join(site.root, r.file)),\n\t\t})),\n\t);\n\n\treturn await load(router, ev, \"%COMPONENT_BODY%\");\n}\n\n// HACK: This is a copy of serverEntry\n// TODO: Make it shared instead!\nasync function load(router: Router, ev: ServerEvent, template: string): Promise<Response> {\n\t//const url = new URL(`http://${process.env.HOST ?? \"localhost\"}${ev.request.url}`);\n\tconst url = new URL(ev.request.url);\n\tconst path = url.pathname;\n\tconst query = url.searchParams;\n\n\t//console.log(`handling ${ev.request.method} for '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\tconst route = router.match(path, query);\n\tif (!route) {\n\t\treturn notFound();\n\t}\n\n\t// Update $page before building the components\n\t// TODO: Find somewhere better to put this\n\t$page.url = url;\n\n\tconst handler = route.handler;\n\tconst params = route.params || {};\n\n\t// TODO: Hit the server hook out here\n\t// We could maybe set data loading up as middleware on a route??????\n\n\tswitch (handler.type) {\n\t\tcase PAGE_ROUTE:\n\t\tcase LAYOUT_ROUTE: {\n\t\t\t// It's a /+page.ts or /_layout.ts endpoint\n\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\treturn await loadView(ev, url, handler, params, template);\n\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\treturn await runAction(ev, url, handler, params, query);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase PAGE_SERVER_ROUTE:\n\t\tcase LAYOUT_SERVER_ROUTE: {\n\t\t\t// It's a /+page.server.ts or /_layout.server.ts endpoint\n\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\treturn await loadData(ev, url, handler, \"load\", params);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase SERVER_ROUTE: {\n\t\t\t// It's a /+server.ts endpoint\n\t\t\tconst functionName = ev.request.method.toLowerCase().replace(\"delete\", \"del\");\n\t\t\treturn await loadData(ev, url, handler, functionName, params);\n\t\t}\n\t\tcase HOOK_ROUTE:\n\t\tcase HOOK_SERVER_ROUTE: {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn notFound();\n}\n\nasync function loadData(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tfunctionName: string,\n\tparams: Record<string, string>,\n) {\n\tconst serverEndPoint: ServerEndPoint | undefined = (await handler.endPoint()).default;\n\tif (serverEndPoint && serverEndPoint[functionName]) {\n\t\tconst serverParams = buildServerParams(ev, url, params);\n\n\t\tif (handler.serverHook) {\n\t\t\tconst serverHook: ServerHook | undefined = (await handler.serverHook()).default;\n\t\t\tif (serverHook?.handle) {\n\t\t\t\tawait serverHook.handle(serverParams);\n\t\t\t}\n\t\t}\n\n\t\tconst result = await serverEndPoint[functionName](serverParams);\n\n\t\t// If there was no response returned from load (such as errors or a\n\t\t// redirect), send an ok response\n\t\treturn result || ok();\n\t}\n\n\treturn notFound();\n}\n\nasync function loadView(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\ttemplate: string,\n) {\n\t// There must be a client endpoint with a component\n\tconst clientEndPoint: PageEndPoint | undefined = (await handler.endPoint()).default;\n\tif (!clientEndPoint?.component) {\n\t\treturn notFound();\n\t}\n\n\t// There may be a server endpoint\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint())?.default;\n\n\t// Maybe hit the server hook\n\tconst serverParams = buildServerParams(ev, url, params);\n\tif (handler.serverHook) {\n\t\tconst serverHook: ServerHook | undefined = (await handler.serverHook()).default;\n\t\tif (serverHook?.handle) {\n\t\t\tawait serverHook.handle(serverParams);\n\t\t}\n\t}\n\n\t// Pass the data into $props\n\t// TODO: Promise.all\n\t// NOTE: We're loading data from top to bottom, overriding as we go, and I'm not sure if this is the best way to go\n\tlet data = {};\n\tif (handler.layouts) {\n\t\tfor (let layout of handler.layouts) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\tconst layoutResponse = await loadClientAndServerData(\n\t\t\t\turl,\n\t\t\t\tparams,\n\t\t\t\tserverParams,\n\t\t\t\tdata,\n\t\t\t\tlayoutEndPoint,\n\t\t\t\tlayoutServerEndPoint,\n\t\t\t);\n\t\t\tif (layoutResponse?.ok === false) {\n\t\t\t\treturn layoutResponse;\n\t\t\t}\n\t\t}\n\t}\n\tlet endPointResponse = await loadClientAndServerData(\n\t\turl,\n\t\tparams,\n\t\tserverParams,\n\t\tdata,\n\t\tclientEndPoint,\n\t\tserverEndPoint,\n\t);\n\tif (endPointResponse?.ok === false) {\n\t\treturn endPointResponse;\n\t}\n\tlet $props: Record<string, any> = { data };\n\n\t// If there are layouts, work our way upwards, pushing each component into\n\t// the default slot of its parent\n\t// TODO: Also handle layout server data\n\t// TODO: There's probably a nicer way to do this with reducers or something\n\t// TODO: Re-use parent layouts\n\tlet component = clientEndPoint.component as ServerComponent;\n\tlet slots: Record<string, ServerSlotRender> | undefined = undefined;\n\tif (handler.layouts) {\n\t\tlet slotFunctions: ServerSlotRender[] = [];\n\t\tslotFunctions[handler.layouts.length] = (_, context) =>\n\t\t\t(clientEndPoint.component as ServerComponent)($props, context);\n\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t?.default;\n\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\tif (i === 0) {\n\t\t\t\t\tcomponent = layoutEndPoint.component as ServerComponent;\n\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t} else {\n\t\t\t\t\tslotFunctions[i] = (_, context) =>\n\t\t\t\t\t\t(layoutEndPoint.component as ServerComponent)($props, context, {\n\t\t\t\t\t\t\t_: slotFunctions[i + 1],\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlet html;\n\ttry {\n\t\tlet { body, head } = component($props, undefined, slots);\n\t\thtml = template.replace(\"%COMPONENT_BODY%\", body).replace(\"%COMPONENT_HEAD\", head);\n\t} catch (error) {\n\t\t// TODO: Show a proper Error component\n\t\thtml = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\tconsole.log(error);\n\t}\n\n\treturn new Response(html, {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"text/html\",\n\t\t},\n\t});\n}\n\nasync function runAction(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\tquery: URLSearchParams,\n) {\n\tconst actionName = (Array.from(query.keys())[0] || \"default\").replace(/^\\//, \"\");\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint()).default;\n\tif (serverEndPoint?.actions) {\n\t\tconst action = serverEndPoint.actions[actionName];\n\t\tif (action) {\n\t\t\t// TODO: form.errors etc\n\t\t\tconst serverParams = buildServerParams(ev, url, params);\n\n\t\t\tif (handler.serverHook) {\n\t\t\t\tconst serverHook: ServerHook | undefined = (await handler.serverHook()).default;\n\t\t\t\tif (serverHook?.handle) {\n\t\t\t\t\tawait serverHook.handle(serverParams);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst result = await action(serverParams); // <--\n\n\t\t\t// If there was no response returned from the action (such as errors\n\t\t\t// or a redirect), reload the page by redirecting\n\t\t\treturn result || seeOther(url.pathname);\n\t\t}\n\t}\n\n\treturn notFound();\n}\n\nasync function loadClientAndServerData(\n\turl: URL,\n\tparams: Record<string, string>,\n\tserverParams: ServerLoadEvent,\n\tdata: Record<string, any>,\n\tclientEndPoint?: PageEndPoint,\n\tserverEndPoint?: PageServerEndPoint,\n) {\n\tif (clientEndPoint?.load) {\n\t\tconst clientParams = buildClientParams(url, data, params);\n\t\tconst clientResponse = await clientEndPoint.load(clientParams);\n\t\tif (clientResponse) {\n\t\t\tif (clientResponse.ok) {\n\t\t\t\tif (clientResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\tObject.assign(data, await clientResponse.json());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn clientResponse;\n\t\t\t}\n\t\t}\n\t}\n\tif (serverEndPoint?.load) {\n\t\tconst serverResponse = await serverEndPoint.load(serverParams);\n\t\tif (serverResponse) {\n\t\t\tif (serverResponse.ok) {\n\t\t\t\tif (serverResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\tObject.assign(data, await serverResponse.json());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn serverResponse;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction buildClientParams(url: URL, params: Record<string, string>, data: Record<string, any>) {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tdata,\n\t};\n}\n\nfunction buildServerParams(\n\tev: ServerEvent,\n\turl: URL,\n\tparams: Record<string, string>,\n): ServerLoadEvent {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tappData: {},\n\t\trequest: ev.request,\n\t\tcookies: ev.cookies,\n\t\theaders: ev.headers,\n\t\tadapter: ev.adapter,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,eAA8B,QAC7B,MACA,OACA,IACoB;AACpB,KAAI,CAAC,MAAM,WAAW,IAAI,CAAE,UAAS;AACrC,KAAI,CAAC,IAAI;EACR,MAAM,MAAM,IAAI,QAAQ,mBAAmB,QAAQ;AACnD,O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AAM,iBAAiB,MAAM,eAAe,KAAK,aAAa;AAC9D,MAAI,eACH,KAAI,eAAe,IAClB;OAAI,eAAe,QAAQ,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAC3E,QAAO,OAAO,MAAM,MAAM,eAAe,MAAM,CAAC;QAGjD,QAAO;;AAIV,KAAI,gBAAgB,MAAM;EACzB,MAAM,iBAAiB,MAAM,eAAe,KAAK,aAAa;AAC9D,MAAI,eACH,KAAI,eAAe,IAClB;OAAI,eAAe,QAAQ,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAC3E,QAAO,OAAO,MAAM,MAAM,eAAe,MAAM,CAAC;QAGjD,QAAO;;;AAMX,SAAS,kBAAkB,KAAU,QAAgC,MAA2B;AAC/F,QAAO;EACN;EACA;EACA;EACA;;AAGF,SAAS,kBACR,IACA,KACA,QACkB;AAClB,QAAO;EACN;EACA;EACA,SAAS,EAAE;EACX,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torpor/build",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "A framework for building sites and apps with Torpor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -50,8 +50,8 @@
50
50
  "dotenv": "^17.2.3",
51
51
  "vite": "^7.1.9",
52
52
  "vite-tsconfig-paths": "^5.1.4",
53
- "@torpor/unplugin": "^0.2.0",
54
- "@torpor/view": "^0.3.0"
53
+ "@torpor/view": "^0.3.2",
54
+ "@torpor/unplugin": "^0.2.0"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@trivago/prettier-plugin-sort-imports": "^5.2.2",
@@ -0,0 +1,48 @@
1
+ import $page from "../state/$page";
2
+ import load from "./load";
3
+ import reload from "./reload";
4
+
5
+ export default async function formSubmit(e: SubmitEvent): Promise<void> {
6
+ // We'll take it from here
7
+ e.preventDefault();
8
+
9
+ // Reset $page on submit and link navigation
10
+ // TODO: Should we put data in $page.data??
11
+ $page.form = undefined;
12
+
13
+ // Perform a POST fetch to the form's action location
14
+ const form = e.target as HTMLFormElement;
15
+ const options = {
16
+ body: new FormData(form),
17
+ method: "POST",
18
+ mode: "cors",
19
+ credentials: "same-origin",
20
+ // Add a special header which tells the server that we want the raw
21
+ // error response (if applicable) rather than the reloaded page that you
22
+ // would get if submitting a page without javascript
23
+ headers: {
24
+ "x-torpor-form-submit": "",
25
+ },
26
+ };
27
+ const response = await fetch(
28
+ form.action,
29
+ // @ts-ignore -- don't know what it's complaining about here
30
+ options,
31
+ );
32
+
33
+ if (response.status === 200 && response.headers.has("x-torpor-form-redirect")) {
34
+ // TODO: Should do the correct type of redirect e.g. seeOther etc
35
+ const redirect = response.headers.get("location")!;
36
+ await load(redirect);
37
+ window.location.href = redirect;
38
+ } else if (
39
+ (response.status >= 200 && response.status <= 299) ||
40
+ (response.status >= 400 && response.status <= 499)
41
+ ) {
42
+ // Put the response into `$page.form`, and it will be put into `$props` in reload
43
+ if (response.headers.get("content-type") === "application/json") {
44
+ $page.form = await response.json();
45
+ }
46
+ await reload();
47
+ }
48
+ }
@@ -6,6 +6,7 @@ import client from "../state/client";
6
6
  import type LayoutPath from "../types/LayoutPath";
7
7
  import type PageEndPoint from "../types/PageEndPoint";
8
8
  import type PageServerEndPoint from "../types/PageServerEndPoint";
9
+ import formSubmit from "./formSubmit";
9
10
  import loadData from "./loadData";
10
11
 
11
12
  // @ts-ignore
@@ -20,7 +21,7 @@ export default async function navigate(url: URL, withHydration = false): Promise
20
21
  const path = url.pathname;
21
22
  const query = url.searchParams;
22
23
 
23
- console.log(`navigating to '${path}'${query.size ? ` with ${query}` : ""}`);
24
+ //console.log(`navigating to '${path}'${query.size ? ` with ${query}` : ""}`);
24
25
 
25
26
  const route = client.router.match(path, query);
26
27
  if (!route) {
@@ -39,7 +40,6 @@ export default async function navigate(url: URL, withHydration = false): Promise
39
40
  } else {
40
41
  $page.status = 200;
41
42
  }
42
-
43
43
  const handler = route.handler;
44
44
  const params = route.params || {};
45
45
 
@@ -77,7 +77,16 @@ export default async function navigate(url: URL, withHydration = false): Promise
77
77
  $page.form = form;
78
78
  formInput.remove();
79
79
  }
80
- const $props: Record<string, any> = { data, form };
80
+ let $props: Record<string, any> = { data };
81
+
82
+ // We may have form data in $page.form, either from the hidden input
83
+ // (above), or added via onformsubmit (below)
84
+ $props.form = $page.form;
85
+
86
+ // Add some special context for submitting Forms client-side
87
+ const $context = {
88
+ TorporBuildContext: { onformsubmit: formSubmit },
89
+ };
81
90
 
82
91
  client.layoutStack.push({ path: route.handler.path, data: {}, reuse: false, slotRange: null });
83
92
  client.layoutStack = newLayoutStack;
@@ -91,7 +100,7 @@ export default async function navigate(url: URL, withHydration = false): Promise
91
100
  if (handler.layouts) {
92
101
  let slotFunctions: SlotRender[] = [];
93
102
  // The last slot function will render the client component
94
- slotFunctions[handler.layouts.length] = function clientComponent(parent, anchor, _, $context) {
103
+ slotFunctions[handler.layouts.length] = function clientComponent(parent, anchor) {
95
104
  let i = layoutStack.length - 1;
96
105
  layoutStack[i].slotRange = fillLayoutSlot(
97
106
  clientEndPoint.component!,
@@ -1,6 +1,7 @@
1
1
  import manifest from "@torpor/build/manifest";
2
2
  import loadData from "../nav/loadData.ts";
3
3
  import navigate from "../nav/navigate.ts";
4
+ import $page from "../state/$page.ts";
4
5
  import client from "../state/client";
5
6
  import type LayoutPath from "../types/LayoutPath";
6
7
  import type PageEndPoint from "../types/PageEndPoint";
@@ -99,5 +100,9 @@ window.addEventListener("popstate", async () => {
99
100
  await navigateToLocation(document.location, true);
100
101
 
101
102
  async function navigateToLocation(location: Location, firstTime = false) {
103
+ // Reset $page on submit and link navigation
104
+ // TODO: Should we put data in $page.data??
105
+ $page.form = undefined;
106
+
102
107
  return await navigate(new URL(location.toString()), firstTime);
103
108
  }
@@ -30,7 +30,6 @@ router.addPages(manifest.routes);
30
30
  //console.log(`routes:\n ${router.routes.map((r) => r.path).join("\n ")}`);
31
31
 
32
32
  export async function load(ev: ServerEvent, template: string): Promise<Response> {
33
- //const url = new URL(`http://${process.env.HOST ?? "localhost"}${ev.request.url}`);
34
33
  const url = new URL(ev.request.url);
35
34
  const path = url.pathname;
36
35
  const query = url.searchParams;
@@ -303,22 +302,41 @@ async function runAction(
303
302
  }
304
303
  }
305
304
 
306
- const result = await action(serverParams);
305
+ let result = await action(serverParams);
307
306
 
308
- // If no result, ok or 4xx error, re-render the view with the form result
309
- // If redirect or server error, just return the result to handle it as normal
310
- // TODO: do not re-run hooks?
311
- if (
307
+ if (ev.request.headers.has("x-torpor-form-submit")) {
308
+ // If the form was submitted from javascript, just return the
309
+ // response and it will be handled on the client
310
+ // TODO: Should we make the user return a response??
311
+ result ??= ok();
312
+
313
+ // If it's a redirect, we need to stop the browser handling it
314
+ if (result.status >= 300 && result.status <= 399) {
315
+ const location = result.headers.get("location") ?? "";
316
+ result = ok();
317
+ result.headers.set("x-torpor-form-redirect", "");
318
+ result.headers.set("location", location);
319
+ }
320
+
321
+ return result;
322
+ } else if (
312
323
  !result ||
313
324
  (result.status >= 200 && result.status <= 299) ||
314
325
  (result.status >= 400 && result.status <= 499)
315
326
  ) {
327
+ // If the form was submitted without javascript, and there was
328
+ // no result, an ok result, or a 4xx error, re-render the view
329
+ // with the form result
330
+ // TODO: do not re-run hooks?
316
331
  const newUrl = new URL(url.pathname, url);
317
332
  const formStatus = result?.status;
318
333
  const form = await result?.json();
319
334
  $page.form = form;
320
335
  return await loadView(ev, newUrl, handler, params, template, formStatus, form);
321
336
  } else {
337
+ // If the form was submitted without javascript and there was a
338
+ // redirect or server error, just return the result to handle it
339
+ // as normal
322
340
  return result;
323
341
  }
324
342
  }
@@ -17,7 +17,7 @@ export default function internal(): InternalState {
17
17
  {
18
18
  status: 404,
19
19
  url: new URL("http://localhost"),
20
- form: {},
20
+ form: undefined,
21
21
  error: {
22
22
  message: "",
23
23
  },
@@ -1 +0,0 @@
1
- {"version":3,"file":"_page-CsdPubw4.js","names":["INTERNAL_GLOBAL: unique symbol","$page: PageState","client: ClientState","$page: PageState"],"sources":["../src/state/internal.ts","../src/state/$page.ts"],"sourcesContent":["import { $watch } from \"@torpor/view\";\nimport type ClientState from \"../types/ClientState\";\nimport type InternalState from \"../types/InternalState\";\nimport type PageState from \"../types/PageState\";\n\n// Do a weird little dance to ensure that everyone has the same $page and\n// client, regardless of if they are entering via serverEntry/clientEntry or the\n// built library. There may be an easier way to do this!\n\nconst INTERNAL_GLOBAL: unique symbol = Symbol.for(\"torpor-internal\");\n\nexport default function internal(): InternalState {\n\t// @ts-ignore\n\tif (globalThis[INTERNAL_GLOBAL] === undefined) {\n\t\t// TODO: Should use the SSR $watch if entering via serverEntry\n\t\tconst $page: PageState = $watch(\n\t\t\t{\n\t\t\t\tstatus: 404,\n\t\t\t\turl: new URL(\"http://localhost\"),\n\t\t\t\tform: {},\n\t\t\t\terror: {\n\t\t\t\t\tmessage: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tshallow: true,\n\t\t\t},\n\t\t);\n\t\tconst client: ClientState = {\n\t\t\t// @ts-ignore This will definitely, 100% get set\n\t\t\trouter: null,\n\t\t\tlayoutStack: [],\n\t\t\t// TODO: Probably expire after 30 seconds or something?\n\t\t\tprefetchedData: {},\n\t\t};\n\n\t\t// @ts-ignore\n\t\tglobalThis[INTERNAL_GLOBAL] = {\n\t\t\t$page,\n\t\t\tclient,\n\t\t} satisfies InternalState;\n\t}\n\t// @ts-ignore\n\treturn globalThis[INTERNAL_GLOBAL] as InternalState;\n}\n","import type PageState from \"../types/PageState\";\nimport internal from \"./internal\";\n\nconst $page: PageState = internal().$page;\n\nexport default $page;\n"],"mappings":";;;AASA,MAAMA,kBAAiC,OAAO,IAAI,kBAAkB;AAEpE,SAAwB,WAA0B;AAEjD,KAAI,WAAW,qBAAqB,QAAW;EAE9C,MAAMC,UAAmB,OACxB;GACC,QAAQ;GACR,KAAK,IAAI,IAAI,mBAAmB;GAChC,MAAM,EAAE;GACR,OAAO,EACN,SAAS,IACT;GACD,EACD,EACC,SAAS,MACT,CACD;EACD,MAAMC,SAAsB;GAE3B,QAAQ;GACR,aAAa,EAAE;GAEf,gBAAgB,EAAE;GAClB;AAGD,aAAW,mBAAmB;GAC7B;GACA;GACA;;AAGF,QAAO,WAAW;;;;;ACxCnB,MAAMC,QAAmB,UAAU,CAAC;AAEpC,oBAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-CNdaKSPR.js","names":["path","path","fs","createViteServer","path","fs","e: any","types: Record<string, string>","path","fs","e: any","path"],"sources":["../src/site/manifest.ts","../src/run/runBuild.ts","../src/run/prepareTemplate.ts","../src/run/runDev.ts","../src/server/contentType.ts","../src/run/runPreview.ts","../src/run/run.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Plugin } from \"vite\";\nimport Site from \"./Site\";\n\nconst moduleId = \"@torpor/build/manifest\";\n\n/**\n * A Vite plugin that provides information about the app to both clientEntry and\n * serverEntry.\n */\nexport default function manifest(site: Site, server = false): Plugin {\n\treturn {\n\t\tname: \"torpor-manifest\",\n\t\tresolveId: {\n\t\t\torder: \"pre\",\n\t\t\thandler(id) {\n\t\t\t\tif (id === moduleId) {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// @ts-ignore\n\t\tload(id, viteOptions) {\n\t\t\tif (id === moduleId) {\n\t\t\t\tlet serverRequest = server && !!viteOptions?.ssr;\n\t\t\t\treturn `\n${!serverRequest ? \"const load = { default: { load: true } };\" : \"\"}\nexport default {\n routes: [\n ${site.routes\n\t\t\t.map((r) => {\n\t\t\t\tif (serverRequest || !/server\\.(ts|js)$/.test(r.file)) {\n\t\t\t\t\treturn `{ path: \"${r.path}\", type: ${r.type}, endPoint: ${serverRequest || !/server\\.(ts|js)$/.test(r.file) ? `() => import(/* @vite-ignore */ \"${path.join(site.root, r.file)}\")` : \"undefined\"} }`;\n\t\t\t\t} else {\n\t\t\t\t\t// On the client, for a server route, we need to check\n\t\t\t\t\t// whether there's a load function and set a dummy endPoint\n\t\t\t\t\t// if so. The correct endpoint will be hit in clientEntry\n\t\t\t\t\t// HACK: Should do this better than checking for `load:` in source...\n\t\t\t\t\tconst haveLoad = readFileSync(path.join(site.root, r.file)).includes(\"load:\");\n\t\t\t\t\treturn `{ path: \"${r.path}\", type: ${r.type}, endPoint: ${haveLoad ? \"() => load\" : \"undefined\"} }`;\n\t\t\t\t}\n\t\t\t})\n\t\t\t.join(\",\\n \")}\n ],\n};\n`;\n\t\t\t}\n\t\t},\n\t};\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { build, defineConfig } from \"vite\";\nimport Site from \"../site/Site\";\nimport manifest from \"../site/manifest.ts\";\n\n// TODO: Don't cache index.html in dev?\n// TODO: Multiple hook.server locations\n// TODO: Don't reload layouts during client routing\n// TODO: Call the correct +page and +server routes when in the same folder\n\nexport default async function runBuild(site: Site): Promise<void> {\n\t// Delete the dist folder if it exists\n\tconst distFolder = path.resolve(site.root, \"dist\");\n\tif (existsSync(distFolder)) {\n\t\tawait fs.rm(distFolder, { recursive: true });\n\t}\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// HOOK: Prebuild\n\tif (site.adapter.prebuild) {\n\t\tawait site.adapter.prebuild(site);\n\t}\n\n\t// TODO: From a setting\n\tlet siteHtml = path.resolve(site.root, \"src/site.html\");\n\n\t// TODO: Is this going to be the correct path after installing from npm?\n\tconst siteFolder = path.resolve(site.root, \"./node_modules/@torpor/build/src/site/\");\n\tlet clientScript = path.join(siteFolder, \"clientEntry.ts\");\n\tlet serverScript = path.join(siteFolder, \"serverEntry.ts\");\n\n\t// Build the client assets, including site.html and the route files\n\t// EXCLUDING anything with `server.js` in the name\n\tconst clientConfig = structuredClone(site.viteConfig ?? {});\n\tclientConfig.plugins = [manifest(site), torpor(), ...site.plugins];\n\tclientConfig.build ??= {};\n\tclientConfig.build.outDir = clientFolder;\n\tclientConfig.build.rollupOptions ??= {};\n\tclientConfig.build.rollupOptions.input = [\n\t\tsiteHtml,\n\t\tclientScript,\n\t\t...site.routes\n\t\t\t.filter((r) => !/server\\.(ts|js)$/.test(r.file))\n\t\t\t.map((r) => path.resolve(site.root, r.file)),\n\t\t...site.inputs.filter((f) => !/server\\.(ts|js)$/.test(f)),\n\t];\n\tclientConfig.build.ssrManifest = true;\n\tawait build(defineConfig(clientConfig));\n\n\t// Build the server assets, including the server entry script and the route\n\t// files\n\tconst serverConfig = structuredClone(site.viteConfig ?? {});\n\tserverConfig.plugins = [manifest(site, true), torpor(), ...site.plugins];\n\tserverConfig.build ??= {};\n\tserverConfig.build.outDir = serverFolder;\n\tserverConfig.build.rollupOptions ??= {};\n\tserverConfig.build.rollupOptions.input = [\n\t\tserverScript,\n\t\t...site.routes.map((r) => path.resolve(site.root, r.file)),\n\t\t...site.inputs,\n\t];\n\tserverConfig.build.ssr = serverScript;\n\tawait build(defineConfig(serverConfig));\n\n\t// Move the site.html file into /client\n\t// HACK: Should do this in Rollup if possible?\n\tsiteHtml = path.join(clientFolder, \"site.html\");\n\tawait fs.rename(path.join(clientFolder, \"src\", \"site.html\"), siteHtml);\n\tawait fs.rm(path.join(clientFolder, \"src\"), { recursive: true });\n\n\t// HOOK: Postbuild\n\tif (site.adapter.postbuild) {\n\t\tawait site.adapter.postbuild(site);\n\t}\n}\n","export default function prepareTemplate(template: string, clientScript: string): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet bodyStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)\\s+/);\n\tbodyStart = result.indexOf(\">\", bodyStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyStart === -1 || bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import estorpor from \"@torpor/unplugin/esbuild\";\nimport torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { createServer as createViteServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport connectMiddleware from \"../server/connect/connectMiddleware.ts\";\nimport Site from \"../site/Site.ts\";\nimport manifest from \"../site/manifest.ts\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\nexport default async function runDev(site: Site): Promise<void> {\n\tconst server = new Server();\n\n\t// Create the Vite server in middleware mode and configure the app type as\n\t// \"custom\", disabling Vite's own HTML serving logic so the parent server\n\t// can take control\n\tconst config = structuredClone(site.viteConfig ?? {});\n\tconfig.server = { middlewareMode: true };\n\tconfig.appType = \"custom\";\n\tconfig.plugins = [manifest(site, true), torpor(), ...site.plugins];\n\n\t// HACK: To be able to import `.torp` files from barrel files in\n\t// node_modules, we need to add their libraries to `ssr.noExternal` in\n\t// site.config.ts, and let esbuild know how to compile them here\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.extensions ??= [];\n\tconfig.optimizeDeps.extensions.push(\".torp\");\n\tconfig.optimizeDeps.esbuildOptions ??= {};\n\tconfig.optimizeDeps.esbuildOptions.plugins ??= [];\n\tconfig.optimizeDeps.esbuildOptions.plugins.push(estorpor());\n\n\tconst vite = await createViteServer(config);\n\n\t// Read site.html\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc)\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tlet template = await fs.readFile(templateFile, \"utf-8\");\n\n\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t// universal transform, not individual transforms for each route\n\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t// TODO: Is this going to be the correct path after installing from npm?\n\tconst siteFolder = path.resolve(site.root, \"./node_modules/@torpor/build/src/site/\");\n\tlet clientScript = path.join(siteFolder, \"clientEntry.ts\");\n\tlet serverScript = path.join(siteFolder, \"serverEntry.ts\");\n\n\t// Prepare site.html so that we can just splice components into it\n\ttemplate = prepareTemplate(template, clientScript);\n\n\t// Use Vite's Connect instance as middleware. We need to wrap it with\n\t// createMiddlewareHandler that converts Connect middleware to\n\t// Request/Response web handlers\n\tserver.use(connectMiddleware(vite.middlewares));\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Serve the site\n\tsite.adapter.serve(server, site);\n}\n","// From https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n\nexport default function contentType(extension: string): string {\n\treturn types[extension] || \"application/octet-stream\";\n}\n\nconst types: Record<string, string> = {\n\t\".aac\": \"audio/aac\",\n\t\".abw\": \"application/x-abiword\",\n\t\".apng\": \"image/apng\",\n\t\".arc\": \"application/x-freearc\",\n\t\".avif\": \"image/avif\",\n\t\".avi\": \"video/x-msvideo\",\n\t\".azw\": \"application/vnd.amazon.ebook\",\n\t\".bin\": \"application/octet-stream\",\n\t\".bmp\": \"image/bmp\",\n\t\".bz\": \"application/x-bzip\",\n\t\".bz2\": \"application/x-bzip2\",\n\t\".cda\": \"application/x-cdf\",\n\t\".csh\": \"application/x-csh\",\n\t\".css\": \"text/css\",\n\t\".csv\": \"text/csv\",\n\t\".doc\": \"application/msword\",\n\t\".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n\t\".eot\": \"application/vnd.ms-fontobject\",\n\t\".epub\": \"application/epub+zip\",\n\t\".gz\": \"application/gzip\",\n\t\".gif\": \"image/gif\",\n\t\".htm\": \"text/html\",\n\t\".html\": \"text/html\",\n\t\".ico\": \"image/vnd.microsoft.icon\",\n\t\".ics\": \"text/calendar\",\n\t\".jar\": \"application/java-archive\",\n\t\".jpeg\": \"image/jpeg\",\n\t\".jpg\": \"image/jpeg\",\n\t\".js\": \"text/javascript\",\n\t\".json\": \"application/json\",\n\t\".jsonld\": \"application/ld+json\",\n\t\".mid\": \"audio/midi\",\n\t\".midi\": \"audio/midi\",\n\t\".mjs\": \"text/javascript\",\n\t\".mp3\": \"audio/mpeg\",\n\t\".mp4\": \"video/mp4\",\n\t\".mpeg\": \"video/mpeg\",\n\t\".mpkg\": \"application/vnd.apple.installer+xml\",\n\t\".odp\": \"application/vnd.oasis.opendocument.presentation\",\n\t\".ods\": \"application/vnd.oasis.opendocument.spreadsheet\",\n\t\".odt\": \"application/vnd.oasis.opendocument.text\",\n\t\".oga\": \"audio/ogg\",\n\t\".ogv\": \"video/ogg\",\n\t\".ogx\": \"application/ogg\",\n\t\".opus\": \"audio/ogg\",\n\t\".otf\": \"font/otf\",\n\t\".png\": \"image/png\",\n\t\".pdf\": \"application/pdf\",\n\t\".php\": \"application/x-httpd-php\",\n\t\".ppt\": \"application/vnd.ms-powerpoint\",\n\t\".pptx\": \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n\t\".rar\": \"application/vnd.rar\",\n\t\".rtf\": \"application/rtf\",\n\t\".sh\": \"application/x-sh\",\n\t\".svg\": \"image/svg+xml\",\n\t\".tar\": \"application/x-tar\",\n\t\".tif\": \"image/tiff\",\n\t\".tiff\": \"image/tiff\",\n\t\".ts\": \"video/mp2t\",\n\t\".ttf\": \"font/ttf\",\n\t\".txt\": \"text/plain\",\n\t\".vsd\": \"application/vnd.visio\",\n\t\".wav\": \"audio/wav\",\n\t\".weba\": \"audio/webm\",\n\t\".webm\": \"video/webm\",\n\t\".webp\": \"image/webp\",\n\t\".woff\": \"font/woff\",\n\t\".woff2\": \"font/woff2\",\n\t\".xhtml\": \"application/xhtml+xml\",\n\t\".xls\": \"application/vnd.ms-excel\",\n\t\".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n\t\".xml\": \"application/xml\",\n\t\".xul\": \"application/vnd.mozilla.xul+xml\",\n\t\".zip\": \"application/zip\",\n\t\".3gp\": \"video/3gpp\",\n\t\".3g2\": \"video/3gpp2\",\n\t\".7z\": \"application/x-7z-compressed\",\n};\n","import { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport contentType from \"../server/contentType.ts\";\nimport Site from \"../site/Site\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\nimport runBuild from \"./runBuild\";\n\nexport default async function runPreview(site: Site): Promise<void> {\n\t// Build the site\n\tawait runBuild(site);\n\n\tconst distFolder = path.resolve(site.root, \"dist\");\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// Find the client script file in /assets\n\tlet clientScript = (await fs.readdir(path.join(clientFolder, \"assets\"))).find((f) =>\n\t\tf.startsWith(\"clientEntry-\"),\n\t);\n\tif (!clientScript) {\n\t\tthrow new Error(\"clientEntry.js not found\");\n\t}\n\tclientScript = `/assets/${clientScript}`;\n\n\t// Read site.html\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc)\n\tlet siteHtml = path.join(clientFolder, \"site.html\");\n\tlet template = await fs.readFile(siteHtml, \"utf-8\");\n\n\t// Prepare site.html so that we can just splice components into it\n\ttemplate = prepareTemplate(template, clientScript);\n\n\t// Configure the server\n\tconst server = new Server();\n\n\t// Serve dist/client/assets statically\n\tserver.add(\"/assets/*\", async (ev) => {\n\t\ttry {\n\t\t\tconst url = new URL(ev.request.url);\n\t\t\tconst file = path.join(site.root, \"dist\", \"client\", url.pathname);\n\t\t\tif (existsSync(file)) {\n\t\t\t\t// TODO: Stream the data?\n\t\t\t\tconst body = bufferToArrayBuffer(await fs.readFile(file));\n\t\t\t\treturn new Response(body, {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": contentType(path.extname(file)),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tconst serverScript = path.resolve(serverFolder, \"serverEntry.js\");\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry\n\t\t\tconst { load } = await import(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Serve the site\n\tsite.adapter.serve(server, site);\n}\n\n// From https://stackoverflow.com/a/79345620\n// No idea why it is needed\nfunction bufferToArrayBuffer(buffer: Buffer): ArrayBuffer {\n\treturn buffer.buffer.slice(\n\t\tbuffer.byteOffset,\n\t\tbuffer.byteOffset + buffer.byteLength,\n\t) as ArrayBuffer;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { transformWithEsbuild } from \"vite\";\nimport Site from \"../site/Site\";\nimport runBuild from \"./runBuild\";\nimport runDev from \"./runDev\";\nimport runPreview from \"./runPreview\";\n\nexport default async function run(\n\tfolder: string,\n\tmode: \"dev\" | \"build\" | \"preview\",\n): Promise<void> {\n\t// Look for and load a site.config.js/ts file in the working directory\n\tlet configFile = \"\";\n\tlet deleteConfigFile = false;\n\tconst jsConfigFile = path.join(folder, \"site.config.js\");\n\tconst tsConfigFile = path.join(folder, \"site.config.ts\");\n\tif (fs.existsSync(jsConfigFile)) {\n\t\t// If it's JS, we can just import it straight up\n\t\tconfigFile = jsConfigFile;\n\t} else if (fs.existsSync(tsConfigFile)) {\n\t\t// If it's TS, we need to convert it to JS\n\t\t// TODO: Put the generated file somewhere better (dist?)\n\t\tconfigFile = path.join(folder, \"site.config.temp.js\");\n\t\tlet source = fs.readFileSync(tsConfigFile, \"utf-8\");\n\t\tlet transformed = await transformWithEsbuild(source, tsConfigFile, {\n\t\t\tloader: \"ts\",\n\t\t});\n\t\tfs.writeFileSync(configFile, transformed.code);\n\t\tdeleteConfigFile = true;\n\t} else {\n\t\tthrow new Error(\"site.config file not found\");\n\t}\n\n\tconst site = (await import(configFile)).default as Site;\n\tif (!site || !site.root || !site.routes) {\n\t\tthrow new Error(\"Invalid site in config file\");\n\t}\n\tif (deleteConfigFile) {\n\t\tfs.rmSync(configFile);\n\t}\n\n\tswitch (mode) {\n\t\tcase \"dev\": {\n\t\t\tawait runDev(site);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"build\": {\n\t\t\tawait runBuild(site);\n\t\t\tbreak;\n\t\t}\n\t\tcase \"preview\": {\n\t\t\tawait runPreview(site);\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\n\t\t\tconsole.log(\"No mode passed, running in dev\");\n\t\t\tawait runDev(site);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;AAKA,MAAM,WAAW;;;;;AAMjB,SAAwB,SAAS,MAAY,SAAS,OAAe;AACpE,QAAO;EACN,MAAM;EACN,WAAW;GACV,OAAO;GACP,QAAQ,IAAI;AACX,QAAI,OAAO,SACV,QAAO;;GAGT;EAED,KAAK,IAAI,aAAa;AACrB,OAAI,OAAO,UAAU;IACpB,IAAI,gBAAgB,UAAU,CAAC,CAAC,aAAa;AAC7C,WAAO;EACT,CAAC,gBAAgB,8CAA8C,GAAG;;;MAG9D,KAAK,OACP,KAAK,MAAM;AACX,SAAI,iBAAiB,CAAC,mBAAmB,KAAK,EAAE,KAAK,CACpD,QAAO,YAAY,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,iBAAiB,CAAC,mBAAmB,KAAK,EAAE,KAAK,GAAG,oCAAoCA,MAAK,KAAK,KAAK,MAAM,EAAE,KAAK,CAAC,MAAM,YAAY;UAC3L;MAKN,MAAM,WAAW,aAAaA,MAAK,KAAK,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,SAAS,QAAQ;AAC7E,aAAO,YAAY,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,WAAW,eAAe,YAAY;;MAEhG,CACD,KAAK,UAAU,CAAC;;;;;;EAMlB;;;;;ACrCF,eAA8B,SAAS,MAA2B;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