@torpor/build 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +1 -1
  2. package/dist/{SessionHelper-MaodMaLU.d.mts → CacheOptions-C4-ebVt9.d.mts} +58 -8
  3. package/dist/CacheOptions-C4-ebVt9.d.mts.map +1 -0
  4. package/dist/{MiddlewareFunction-7rIvFkjl.d.mts → MiddlewareFunction-DMYxjzF4.d.mts} +25 -2
  5. package/dist/MiddlewareFunction-DMYxjzF4.d.mts.map +1 -0
  6. package/dist/{Router-Bxm7K20d.d.mts → Router-DyK3DTWQ.d.mts} +2 -2
  7. package/dist/{Router-Bxm7K20d.d.mts.map → Router-DyK3DTWQ.d.mts.map} +1 -1
  8. package/dist/{Server-Djd9-NkU.mjs → Server-BCijhgZp.mjs} +3 -3
  9. package/dist/{Server-Djd9-NkU.mjs.map → Server-BCijhgZp.mjs.map} +1 -1
  10. package/dist/{Server-hwbZ7P2g.d.mts → Server-ClwvuilS.d.mts} +2 -2
  11. package/dist/{Server-hwbZ7P2g.d.mts.map → Server-ClwvuilS.d.mts.map} +1 -1
  12. package/dist/{ServerEvent-L0rT_mBJ.mjs → ServerEvent-BBRkd4Ya.mjs} +127 -31
  13. package/dist/ServerEvent-BBRkd4Ya.mjs.map +1 -0
  14. package/dist/{ServerHook-CyVEr5OL.d.mts → ServerHook-DY-NSG6n.d.mts} +2 -2
  15. package/dist/{ServerHook-CyVEr5OL.d.mts.map → ServerHook-DY-NSG6n.d.mts.map} +1 -1
  16. package/dist/{ServerLoadEvent-F60w1TZt.d.mts → ServerLoadEvent-CpcgsKCU.d.mts} +19 -5
  17. package/dist/ServerLoadEvent-CpcgsKCU.d.mts.map +1 -0
  18. package/dist/{Site-CAeAqjkk.d.mts → Site-BEMQW1_y.d.mts} +31 -11
  19. package/dist/Site-BEMQW1_y.d.mts.map +1 -0
  20. package/dist/{basePath-DQnbHc7o.mjs → basePath-B6hmOMl4.mjs} +89 -4
  21. package/dist/basePath-B6hmOMl4.mjs.map +1 -0
  22. package/dist/bin/index.js +1 -1
  23. package/dist/clientEntry.mjs +10 -5
  24. package/dist/clientEntry.mjs.map +1 -1
  25. package/dist/dev.d.mts +2 -2
  26. package/dist/dev.mjs +2 -2
  27. package/dist/{devPlugin-D9b5uhzm.mjs → devPlugin-BGrTpcC2.mjs} +3 -3
  28. package/dist/{devPlugin-D9b5uhzm.mjs.map → devPlugin-BGrTpcC2.mjs.map} +1 -1
  29. package/dist/discovery.d.mts +1 -1
  30. package/dist/discovery.mjs +1 -1
  31. package/dist/index.d.mts +22 -6
  32. package/dist/index.d.mts.map +1 -1
  33. package/dist/index.mjs +10 -0
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/{load-BODDzmH0.mjs → load-Dw187nJ_.mjs} +95 -52
  36. package/dist/load-Dw187nJ_.mjs.map +1 -0
  37. package/dist/nav.d.mts +2 -1
  38. package/dist/nav.d.mts.map +1 -1
  39. package/dist/nav.mjs +3 -3
  40. package/dist/nodeDev.d.mts +1 -1
  41. package/dist/nodeDev.mjs +1 -1
  42. package/dist/openapi.d.mts +2 -2
  43. package/dist/{read-DxMVAh5Y.mjs → read-CPW2iPum.mjs} +21 -2
  44. package/dist/read-CPW2iPum.mjs.map +1 -0
  45. package/dist/{response-C5EZsszY.mjs → response-B4UoOJvv.mjs} +3 -24
  46. package/dist/response-B4UoOJvv.mjs.map +1 -0
  47. package/dist/response.mjs +2 -2
  48. package/dist/run.d.mts +1 -1
  49. package/dist/run.d.mts.map +1 -1
  50. package/dist/run.mjs +1 -1
  51. package/dist/{runHooks-D5p1Rh7i.mjs → runHooks-C7kt7SEo.mjs} +36 -2
  52. package/dist/runHooks-C7kt7SEo.mjs.map +1 -0
  53. package/dist/{runOpenApi-BZ314IiI.mjs → runOpenApi-DK-QnYEr.mjs} +239 -18
  54. package/dist/runOpenApi-DK-QnYEr.mjs.map +1 -0
  55. package/dist/server/Server.d.mts +1 -1
  56. package/dist/server/Server.mjs +1 -1
  57. package/dist/server.d.mts +30 -6
  58. package/dist/server.d.mts.map +1 -1
  59. package/dist/server.mjs +47 -3
  60. package/dist/server.mjs.map +1 -1
  61. package/dist/{serverEntry-Da1PFlIU.d.mts → serverEntry-BFad1k1C.d.mts} +3 -3
  62. package/dist/serverEntry-BFad1k1C.d.mts.map +1 -0
  63. package/dist/{serverEntry-8YnfpKTj.mjs → serverEntry-DAT7o7o2.mjs} +3 -5
  64. package/dist/serverEntry-DAT7o7o2.mjs.map +1 -0
  65. package/dist/serverEntry.d.mts +1 -1
  66. package/dist/serverEntry.mjs +1 -1
  67. package/dist/{serverHandlers-Ba_35jpO.mjs → serverHandlers-B1L8I72-.mjs} +398 -192
  68. package/dist/serverHandlers-B1L8I72-.mjs.map +1 -0
  69. package/dist/{sitemap-CnIYTLhu.d.mts → sitemap-CKmagPyL.d.mts} +2 -2
  70. package/dist/{sitemap-CnIYTLhu.d.mts.map → sitemap-CKmagPyL.d.mts.map} +1 -1
  71. package/dist/{sitemap-4imxJVrG.mjs → sitemap-DdzFjGlo.mjs} +2 -2
  72. package/dist/{sitemap-4imxJVrG.mjs.map → sitemap-DdzFjGlo.mjs.map} +1 -1
  73. package/dist/state.d.mts +1 -4
  74. package/dist/state.d.mts.map +1 -1
  75. package/dist/state.mjs +1 -1
  76. package/dist/test.d.mts +2 -2
  77. package/dist/test.mjs +2 -2
  78. package/dist/{unprocessable-DwAG44Rh.mjs → unprocessable-BZXwyN0n.mjs} +23 -2
  79. package/dist/unprocessable-BZXwyN0n.mjs.map +1 -0
  80. package/package.json +3 -3
  81. package/src/types/manifest.d.ts +3 -0
  82. package/dist/MiddlewareFunction-7rIvFkjl.d.mts.map +0 -1
  83. package/dist/ServerEvent-L0rT_mBJ.mjs.map +0 -1
  84. package/dist/ServerLoadEvent-F60w1TZt.d.mts.map +0 -1
  85. package/dist/SessionHelper-MaodMaLU.d.mts.map +0 -1
  86. package/dist/Site-CAeAqjkk.d.mts.map +0 -1
  87. package/dist/_page-CW6SLuT4.mjs +0 -14
  88. package/dist/_page-CW6SLuT4.mjs.map +0 -1
  89. package/dist/basePath-DQnbHc7o.mjs.map +0 -1
  90. package/dist/load-BODDzmH0.mjs.map +0 -1
  91. package/dist/read-DxMVAh5Y.mjs.map +0 -1
  92. package/dist/response-C5EZsszY.mjs.map +0 -1
  93. package/dist/runHooks-D5p1Rh7i.mjs.map +0 -1
  94. package/dist/runOpenApi-BZ314IiI.mjs.map +0 -1
  95. package/dist/serverEntry-8YnfpKTj.mjs.map +0 -1
  96. package/dist/serverEntry-Da1PFlIU.d.mts.map +0 -1
  97. package/dist/serverHandlers-Ba_35jpO.mjs.map +0 -1
  98. package/dist/unprocessable-DwAG44Rh.mjs.map +0 -1
package/README.md CHANGED
@@ -33,7 +33,7 @@ npm run dev
33
33
  - Schema validation for endpoints (`@torpor/build/schema`)
34
34
  - Form helpers (`@torpor/build/form`) and client side navigation helpers
35
35
  (`@torpor/build/nav`)
36
- - `$page` state for pages (`@torpor/build/state`) and response helpers
36
+ - `$page` state for pages (`let { $page } = $context`) and response helpers
37
37
  (`@torpor/build/response`)
38
38
 
39
39
  ## Folder structure
@@ -3,8 +3,20 @@ import { SerializeOptions } from "cookie";
3
3
  declare class CookieHelper {
4
4
  request: Request;
5
5
  cookies: Map<string, string>;
6
+ /**
7
+ * Whether anything read a cookie during the request, which makes the
8
+ * response depend on who asked for it (see `CacheOptions`)
9
+ */
10
+ read: boolean;
6
11
  constructor(request: Request);
7
12
  get(name: string): string | undefined;
13
+ /**
14
+ * Gets a cookie's value without marking the response as depending on
15
+ * cookies. For framework reads whose result only matters when the cookie
16
+ * is there (the flash message, which deletes the cookie when it's found).
17
+ * @internal
18
+ */
19
+ peek(name: string): string | undefined;
8
20
  set(name: string, value: string, options?: SerializeOptions): void;
9
21
  delete(name: string, options?: SerializeOptions): void;
10
22
  }
@@ -13,7 +25,7 @@ declare class CookieHelper {
13
25
  /**
14
26
  * A one-time values store set in a form action and shown on the next page
15
27
  * render, which survives the redirect. Available as `event.flash`; the
16
- * framework reads it into `$page.flash` when a page is rendered, so
28
+ * framework reads it into `$context.$page.flash` when a page is rendered, so
17
29
  * components display it reactively:
18
30
  *
19
31
  * ```ts
@@ -28,6 +40,8 @@ declare class CookieHelper {
28
40
  * ```
29
41
  *
30
42
  * ```torp
43
+ * let { $page } = $context;
44
+ *
31
45
  * @if ($page.flash?.message) {
32
46
  * <p class="flash">{$page.flash.message}</p>
33
47
  * }
@@ -116,15 +130,17 @@ declare class SessionHelper {
116
130
  get id(): string | undefined;
117
131
  /**
118
132
  * Reads and verifies the session, returning its data, or undefined when
119
- * there is no cookie, the signature doesn't match, or the session has
120
- * expired.
133
+ * there is no cookie, the signature doesn't match, the value is malformed,
134
+ * or the session has expired.
121
135
  */
122
136
  get(): Promise<SessionData | undefined>;
123
137
  /**
124
138
  * Writes the session, signing the data and setting the cookie. Keeps
125
- * the current session id, minting one when there isn't a valid session
126
- * yet. Call `regenerate` instead when the session's identity should
127
- * change (e.g. at login, to prevent session fixation).
139
+ * the current session id, reading (and verifying) the existing cookie
140
+ * when it hasn't been read yet in this request, and minting one when
141
+ * there isn't a valid session. Call `regenerate` instead when the
142
+ * session's identity should change (e.g. at login, to prevent session
143
+ * fixation).
128
144
  */
129
145
  set(data: SessionData, options?: {
130
146
  maxAge?: number;
@@ -144,5 +160,39 @@ declare class SessionHelper {
144
160
  destroy(): Promise<void>;
145
161
  }
146
162
  //#endregion
147
- export { CookieHelper as i, HeaderHelper as n, FlashHelper as r, SessionHelper as t };
148
- //# sourceMappingURL=SessionHelper-MaodMaLU.d.mts.map
163
+ //#region src/server/types/CacheOptions.d.ts
164
+ /**
165
+ * How a response may be cached, set with `event.cache(...)`. Several calls
166
+ * in one request (e.g. from a layout's load and the page's load) are merged
167
+ * so that the most restrictive wins: the smallest ages, `private` or
168
+ * `noStore` if any call asks for it, and the union of the `vary` headers.
169
+ *
170
+ * It's applied to successful (2xx) GET responses: pages, client data
171
+ * requests and endpoints. Without it, a response that read or set a cookie
172
+ * (the session, say) gets `Cache-Control: private, no-cache`, and other
173
+ * responses get no `Cache-Control` at all.
174
+ */
175
+ interface CacheOptions {
176
+ /** Seconds that browsers and shared caches may serve the response for */
177
+ maxAge?: number;
178
+ /** Seconds that shared caches (CDNs) may serve it for, overriding `maxAge` */
179
+ sMaxAge?: number;
180
+ /**
181
+ * Seconds that a cache may serve the response stale for after it expires,
182
+ * while it fetches a fresh one in the background
183
+ */
184
+ staleWhileRevalidate?: number;
185
+ /**
186
+ * Whether only the user's browser may cache the response. Responses that
187
+ * read or set cookies are private by default; set `false` to let shared
188
+ * caches store one anyway (only when its content doesn't depend on them)
189
+ */
190
+ private?: boolean;
191
+ /** Whether the response mustn't be stored at all */
192
+ noStore?: boolean;
193
+ /** Request headers that the response depends on, sent as `Vary` */
194
+ vary?: string[];
195
+ }
196
+ //#endregion
197
+ export { CookieHelper as a, FlashHelper as i, SessionHelper as n, HeaderHelper as r, CacheOptions as t };
198
+ //# sourceMappingURL=CacheOptions-C4-ebVt9.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CacheOptions-C4-ebVt9.d.mts","names":[],"sources":["../src/server/CookieHelper.ts","../src/server/FlashHelper.ts","../src/server/HeaderHelper.ts","../src/server/SessionHelper.ts","../src/server/types/CacheOptions.ts"],"mappings":";;cAUqB;EACpB,SAAS;EACT,SAAS;;;;;EAKT;EAEA,YAAY,SAAS;EAIrB,IAAI;;;;;;;EAWJ,KAAK;EAaL,IAAI,cAAc,eAAe,UAAU;EAU3C,OAAO,cAAc,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cCnBX;;EAGpB,YAAY,SAAS;;;;;;;;EAWrB,OAAO;;;;;EAqBP,IAAI,gBAAgB;;;;;EASpB;;;;cClFoB;EACpB,SAAS;EACT,SAAS;EAET,YAAY,SAAS;EAIrB,IAAI;EASJ,IAAI,cAAc;EAIlB,OAAO;;;;;;;;KCXH,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;cAqCE;;EAIpB,YAAY,SAAS;;;;;;MASjB;;;;;;EASJ,OAAa,QAAQ;;;;;;;;;EAarB,IAAU,MAAM,aAAa;IAAY;MAAoB;;;;;;EAkB7D,WAAiB,OAAM,aAAkB;IAAY;MAAoB;;;;;EAUzE,WAAiB;;;;;;;;;;;;;;;UCnGO;;EAExB;;EAEA;;;;;EAKA;;;;;;EAMA;;EAEA;;EAEA"}
@@ -1,4 +1,4 @@
1
- import { i as CookieHelper, n as HeaderHelper, r as FlashHelper, t as SessionHelper } from "./SessionHelper-MaodMaLU.mjs";
1
+ import { a as CookieHelper, i as FlashHelper, n as SessionHelper, r as HeaderHelper, t as CacheOptions } from "./CacheOptions-C4-ebVt9.mjs";
2
2
  //#region src/server/ServerEvent.d.ts
3
3
  declare class ServerEvent {
4
4
  #private;
@@ -11,6 +11,13 @@ declare class ServerEvent {
11
11
  */
12
12
  error: unknown;
13
13
  params?: Record<string, string>;
14
+ /**
15
+ * Data shared by everything that handles this request: middleware, folder
16
+ * hooks (as `event.appData`), and the loads and actions they run around.
17
+ * Folder hooks run before route middleware, so a route's guard can read
18
+ * e.g. the user that an auth hook loaded.
19
+ */
20
+ appData: Record<string, any>;
14
21
  adapter: any;
15
22
  cookies: CookieHelper;
16
23
  headers: HeaderHelper;
@@ -20,6 +27,22 @@ declare class ServerEvent {
20
27
  get url(): URL;
21
28
  constructor(request: Request, params?: Record<string, string>, url?: URL);
22
29
  addHeaders(): void;
30
+ /**
31
+ * Sets how the response may be cached (`Cache-Control` and `Vary`). Calls
32
+ * are merged, with the most restrictive setting winning. See
33
+ * `CacheOptions`.
34
+ */
35
+ cache(options: CacheOptions): void;
36
+ /** The merged `cache()` settings, if any were set. */
37
+ get cacheOptions(): CacheOptions | undefined;
38
+ /**
39
+ * Keeps background work running after the response is sent, e.g.
40
+ * refreshing a cache or logging. On Cloudflare this is the worker's
41
+ * `ctx.waitUntil`, without which the work would be cut off; elsewhere the
42
+ * promise just runs on. Either way a rejection is logged rather than left
43
+ * unhandled.
44
+ */
45
+ waitUntil(promise: Promise<unknown>): void;
23
46
  /**
24
47
  * Reads the request body as JSON.
25
48
  */
@@ -53,4 +76,4 @@ type MiddlewareFunction = {
53
76
  };
54
77
  //#endregion
55
78
  export { ServerEvent as n, MiddlewareFunction as t };
56
- //# sourceMappingURL=MiddlewareFunction-7rIvFkjl.d.mts.map
79
+ //# sourceMappingURL=MiddlewareFunction-DMYxjzF4.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MiddlewareFunction-DMYxjzF4.d.mts","names":[],"sources":["../src/server/ServerEvent.ts","../src/server/types/MiddlewareFunction.ts"],"mappings":";;cAQqB;;EACpB,SAAS;EACT,UAAU;;;;;;EAMV;EAEA,SAAS;;;;;;;EAOT,SAAS;EAET;EAEA,SAAS;EACT,SAAS;EACT,SAAS;EACT,OAAO;;MAeH,OAAO;EAIX,YAAY,SAAS,SAAS,SAAS,wBAAwB,MAAM;EAcrE;;;;;;EA+CA,MAAM,SAAS;;MAqBX,gBAAgB;;;;;;;;EAWpB,UAAU,SAAS;;;;EAUnB,QAAQ;;;;;;EASR,YAAY,QAAQ;;;;KCjKhB;;;;;;EAMJ,SAAS,IAAI,gBAAgB,kBAAkB,QAAQ;;;;;;;;;;EAUvD,QAAQ,IAAI,gBAAgB,kBAAkB,QAAQ"}
@@ -1,4 +1,4 @@
1
- import { t as ServerHook } from "./ServerHook-CyVEr5OL.mjs";
1
+ import { t as ServerHook } from "./ServerHook-DY-NSG6n.mjs";
2
2
  //#region src/types/ManifestRoute.d.ts
3
3
  interface ManifestRoute {
4
4
  path: string;
@@ -56,4 +56,4 @@ interface RouteMatch {
56
56
  }
57
57
  //#endregion
58
58
  export { Router as t };
59
- //# sourceMappingURL=Router-Bxm7K20d.d.mts.map
59
+ //# sourceMappingURL=Router-DyK3DTWQ.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Router-Bxm7K20d.d.mts","names":[],"sources":["../src/types/ManifestRoute.ts","../src/types/RouteLayoutHandler.ts","../src/types/RouteHandler.ts","../src/site/Router.ts"],"mappings":";;UAAyB;EACxB;EACA;EACA,gBAAgB;EAChB;;;;UCJwB;EACxB;EACA,gBAAgB;EAChB,uBAAuB;;;;;;;UCGC;EACxB;EACA;EACA,gBAAgB;EAChB;EAEA;EACA,UAAU;EACV,uBAAuB;EACvB,qBAAqB;EAQrB;EACA;EACA,gBAAgB;;;;;;;cCjBI;;EACpB,QAAQ;EAMR;EAOA,SAAS,QAAQ;EAQjB,QAAQ,cAAc,cAAc,gBAAgB,cAAc;EAuBlE,MAAM,cAAc,OAAO,kBAAkB;;cA2GxC;EACL;EACA,SAAS;EAET,YAAY,cAAc,SAAS;;UAM1B;EACT,SAAS;EACT,SAAS;EACT,OAAO"}
1
+ {"version":3,"file":"Router-DyK3DTWQ.d.mts","names":[],"sources":["../src/types/ManifestRoute.ts","../src/types/RouteLayoutHandler.ts","../src/types/RouteHandler.ts","../src/site/Router.ts"],"mappings":";;UAAyB;EACxB;EACA;EACA,gBAAgB;EAChB;;;;UCJwB;EACxB;EACA,gBAAgB;EAChB,uBAAuB;;;;;;;UCGC;EACxB;EACA;EACA,gBAAgB;EAChB;EAEA;EACA,UAAU;EACV,uBAAuB;EACvB,qBAAqB;EAQrB;EACA;EACA,gBAAgB;;;;;;;cCjBI;;EACpB,QAAQ;EAMR;EAOA,SAAS,QAAQ;EAQjB,QAAQ,cAAc,cAAc,gBAAgB,cAAc;EAuBlE,MAAM,cAAc,OAAO,kBAAkB;;cA2GxC;EACL;EACA,SAAS;EAET,YAAY,cAAc,SAAS;;UAM1B;EACT,SAAS;EACT,SAAS;EACT,OAAO"}
@@ -1,6 +1,6 @@
1
1
  import { t as PathTrie } from "./pathTrie-D4Ax2Mu9.mjs";
2
- import { t as ServerEvent } from "./ServerEvent-L0rT_mBJ.mjs";
3
- import { t as runHooks } from "./runHooks-D5p1Rh7i.mjs";
2
+ import { t as runHooks } from "./runHooks-C7kt7SEo.mjs";
3
+ import { t as ServerEvent } from "./ServerEvent-BBRkd4Ya.mjs";
4
4
  //#region src/server/Server.ts
5
5
  /**
6
6
  * A Fetch API Request/Response server.
@@ -83,4 +83,4 @@ var RouteHandler = class {
83
83
  //#endregion
84
84
  export { Server as t };
85
85
 
86
- //# sourceMappingURL=Server-Djd9-NkU.mjs.map
86
+ //# sourceMappingURL=Server-BCijhgZp.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Server-Djd9-NkU.mjs","names":[],"sources":["../src/server/Server.ts"],"sourcesContent":["import PathTrie from \"../utils/pathTrie\";\nimport ServerEvent from \"./ServerEvent\";\nimport runHooks from \"./runHooks\";\nimport type MiddlewareFunction from \"./types/MiddlewareFunction\";\nimport type ServerFunction from \"./types/ServerFunction\";\n\n/**\n * A Fetch API Request/Response server.\n */\nexport default class Server {\n\t// TODO: We don't use any of the routes, just add(\"*\") in runDev/runBuild...\n\troutes: RouteHandler[] = [];\n\t// Match index for the routes above\n\t#trie = new PathTrie<RouteHandler>();\n\t// TODO: We only use the Vite middleware here\n\tmiddleware: MiddlewareFunction[] = [];\n\n\tconstructor() {\n\t\tthis.routes = [];\n\t\tthis.middleware = [];\n\t}\n\n\t/**\n\t * The standard Fetch API method that should work in any runtime (including\n\t * Node with polyfills).\n\t * @returns\n\t */\n\tfetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n\t\t// Use the request as-is when we were given one, so that the adapter\n\t\t// doesn't pay for constructing it twice\n\t\tconst request = input instanceof Request && !init ? input : new Request(input, init);\n\t\tconst url = new URL(request.url);\n\t\tconst match = this.match(url.pathname);\n\t\tlet ev = new ServerEvent(request, match?.params, url);\n\n\t\tif (this.middleware.length) {\n\t\t\t// Route-scoped middleware is set on server endpoints (or globally on\n\t\t\t// `site.middleware`); this list is the low-level, per-Server primitive\n\t\t\tconst { response, error } = await runHooks(\n\t\t\t\t[{ hooks: this.middleware, arg: ev }],\n\t\t\t\tasync (): Promise<Response | undefined> => {\n\t\t\t\t\tif (!match) return undefined;\n\t\t\t\t\treturn (await match.fn(ev)) || undefined;\n\t\t\t\t},\n\t\t\t\t{ event: ev },\n\t\t\t);\n\t\t\tif (error && !response) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else if (match) {\n\t\t\tev.response = await match.fn(ev);\n\t\t} else {\n\t\t\treturn new Response(null, { status: 404 });\n\t\t}\n\n\t\t// TODO: Should I be returning 200 if there's no response? Because it's not an error??\n\t\tev.response ??= new Response(null, { status: 200 });\n\t\tev.addHeaders();\n\n\t\treturn ev.response;\n\t};\n\n\t/**\n\t * Adds a server function at a route path.\n\t * @param path The route path pattern.\n\t * @param fn The function to call when the pattern is matched.\n\t * @returns\n\t */\n\tadd(path: string, fn: ServerFunction): Server {\n\t\tlet handler = new RouteHandler(path, fn);\n\t\tthis.routes.push(handler);\n\t\tthis.#trie.insert(path, handler);\n\t\tthis.#sortRoutes();\n\t\treturn this;\n\t}\n\n\tmatch(path: string): Match | undefined {\n\t\tconst found = this.#trie.match(path);\n\t\tif (found) {\n\t\t\treturn {\n\t\t\t\tfn: found.value.fn,\n\t\t\t\tparams: found.params,\n\t\t\t};\n\t\t}\n\t\tconsole.log(`Server path not found: ${path}`);\n\t}\n\n\t// TODO:\n\t//use(path: string, ...fn: MiddlewareFunction[])\n\tuse(...fn: MiddlewareFunction[]): Server {\n\t\tthis.middleware = this.middleware.concat(fn);\n\t\treturn this;\n\t}\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\nclass RouteHandler {\n\tpath: string;\n\tfn: ServerFunction;\n\n\tconstructor(path: string, fn: ServerFunction) {\n\t\tthis.path = path;\n\t\tthis.fn = fn;\n\t}\n}\n\n//class MiddlewareHandler {\n//\tpath: string;\n//\tregex: RegExp;\n//\tfn: MiddlewareFunction;\n//\n//\tconstructor(path: string, fn: MiddlewareFunction) {\n//\t\tthis.path = path;\n//\t\tthis.regex = pathToRegex(path);\n//\t\tthis.fn = fn;\n//\t}\n//}\n\ninterface Match {\n\tfn: ServerFunction;\n\tparams?: Record<string, string>;\n}\n"],"mappings":";;;;;;;AASA,IAAqB,SAArB,MAA4B;CAE3B,SAAyB,CAAC;CAE1B,QAAQ,IAAI,SAAuB;CAEnC,aAAmC,CAAC;CAEpC,cAAc;EACb,KAAK,SAAS,CAAC;EACf,KAAK,aAAa,CAAC;CACpB;;;;;;CAOA,QAAQ,OAAO,OAA0B,SAA0C;EAGlF,MAAM,UAAU,iBAAiB,WAAW,CAAC,OAAO,QAAQ,IAAI,QAAQ,OAAO,IAAI;EACnF,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAC/B,MAAM,QAAQ,KAAK,MAAM,IAAI,QAAQ;EACrC,IAAI,KAAK,IAAI,YAAY,SAAS,OAAO,QAAQ,GAAG;EAEpD,IAAI,KAAK,WAAW,QAAQ;GAG3B,MAAM,EAAE,UAAU,UAAU,MAAM,SACjC,CAAC;IAAE,OAAO,KAAK;IAAY,KAAK;GAAG,CAAC,GACpC,YAA2C;IAC1C,IAAI,CAAC,OAAO,OAAO,KAAA;IACnB,OAAQ,MAAM,MAAM,GAAG,EAAE,KAAM,KAAA;GAChC,GACA,EAAE,OAAO,GAAG,CACb;GACA,IAAI,SAAS,CAAC,UACb,MAAM;EAER,OAAO,IAA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server-BCijhgZp.mjs","names":[],"sources":["../src/server/Server.ts"],"sourcesContent":["import PathTrie from \"../utils/pathTrie\";\nimport ServerEvent from \"./ServerEvent\";\nimport runHooks from \"./runHooks\";\nimport type MiddlewareFunction from \"./types/MiddlewareFunction\";\nimport type ServerFunction from \"./types/ServerFunction\";\n\n/**\n * A Fetch API Request/Response server.\n */\nexport default class Server {\n\t// TODO: We don't use any of the routes, just add(\"*\") in runDev/runBuild...\n\troutes: RouteHandler[] = [];\n\t// Match index for the routes above\n\t#trie = new PathTrie<RouteHandler>();\n\t// TODO: We only use the Vite middleware here\n\tmiddleware: MiddlewareFunction[] = [];\n\n\tconstructor() {\n\t\tthis.routes = [];\n\t\tthis.middleware = [];\n\t}\n\n\t/**\n\t * The standard Fetch API method that should work in any runtime (including\n\t * Node with polyfills).\n\t * @returns\n\t */\n\tfetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n\t\t// Use the request as-is when we were given one, so that the adapter\n\t\t// doesn't pay for constructing it twice\n\t\tconst request = input instanceof Request && !init ? input : new Request(input, init);\n\t\tconst url = new URL(request.url);\n\t\tconst match = this.match(url.pathname);\n\t\tlet ev = new ServerEvent(request, match?.params, url);\n\n\t\tif (this.middleware.length) {\n\t\t\t// Route-scoped middleware is set on server endpoints (or globally on\n\t\t\t// `site.middleware`); this list is the low-level, per-Server primitive\n\t\t\tconst { response, error } = await runHooks(\n\t\t\t\t[{ hooks: this.middleware, arg: ev }],\n\t\t\t\tasync (): Promise<Response | undefined> => {\n\t\t\t\t\tif (!match) return undefined;\n\t\t\t\t\treturn (await match.fn(ev)) || undefined;\n\t\t\t\t},\n\t\t\t\t{ event: ev },\n\t\t\t);\n\t\t\tif (error && !response) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else if (match) {\n\t\t\tev.response = await match.fn(ev);\n\t\t} else {\n\t\t\treturn new Response(null, { status: 404 });\n\t\t}\n\n\t\t// TODO: Should I be returning 200 if there's no response? Because it's not an error??\n\t\tev.response ??= new Response(null, { status: 200 });\n\t\tev.addHeaders();\n\n\t\treturn ev.response;\n\t};\n\n\t/**\n\t * Adds a server function at a route path.\n\t * @param path The route path pattern.\n\t * @param fn The function to call when the pattern is matched.\n\t * @returns\n\t */\n\tadd(path: string, fn: ServerFunction): Server {\n\t\tlet handler = new RouteHandler(path, fn);\n\t\tthis.routes.push(handler);\n\t\tthis.#trie.insert(path, handler);\n\t\tthis.#sortRoutes();\n\t\treturn this;\n\t}\n\n\tmatch(path: string): Match | undefined {\n\t\tconst found = this.#trie.match(path);\n\t\tif (found) {\n\t\t\treturn {\n\t\t\t\tfn: found.value.fn,\n\t\t\t\tparams: found.params,\n\t\t\t};\n\t\t}\n\t\tconsole.log(`Server path not found: ${path}`);\n\t}\n\n\t// TODO:\n\t//use(path: string, ...fn: MiddlewareFunction[])\n\tuse(...fn: MiddlewareFunction[]): Server {\n\t\tthis.middleware = this.middleware.concat(fn);\n\t\treturn this;\n\t}\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\nclass RouteHandler {\n\tpath: string;\n\tfn: ServerFunction;\n\n\tconstructor(path: string, fn: ServerFunction) {\n\t\tthis.path = path;\n\t\tthis.fn = fn;\n\t}\n}\n\n//class MiddlewareHandler {\n//\tpath: string;\n//\tregex: RegExp;\n//\tfn: MiddlewareFunction;\n//\n//\tconstructor(path: string, fn: MiddlewareFunction) {\n//\t\tthis.path = path;\n//\t\tthis.regex = pathToRegex(path);\n//\t\tthis.fn = fn;\n//\t}\n//}\n\ninterface Match {\n\tfn: ServerFunction;\n\tparams?: Record<string, string>;\n}\n"],"mappings":";;;;;;;AASA,IAAqB,SAArB,MAA4B;CAE3B,SAAyB,CAAC;CAE1B,QAAQ,IAAI,SAAuB;CAEnC,aAAmC,CAAC;CAEpC,cAAc;EACb,KAAK,SAAS,CAAC;EACf,KAAK,aAAa,CAAC;CACpB;;;;;;CAOA,QAAQ,OAAO,OAA0B,SAA0C;EAGlF,MAAM,UAAU,iBAAiB,WAAW,CAAC,OAAO,QAAQ,IAAI,QAAQ,OAAO,IAAI;EACnF,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAC/B,MAAM,QAAQ,KAAK,MAAM,IAAI,QAAQ;EACrC,IAAI,KAAK,IAAI,YAAY,SAAS,OAAO,QAAQ,GAAG;EAEpD,IAAI,KAAK,WAAW,QAAQ;GAG3B,MAAM,EAAE,UAAU,UAAU,MAAM,SACjC,CAAC;IAAE,OAAO,KAAK;IAAY,KAAK;GAAG,CAAC,GACpC,YAA2C;IAC1C,IAAI,CAAC,OAAO,OAAO,KAAA;IACnB,OAAQ,MAAM,MAAM,GAAG,EAAE,KAAM,KAAA;GAChC,GACA,EAAE,OAAO,GAAG,CACb;GACA,IAAI,SAAS,CAAC,UACb,MAAM;EAER,OAAO,IAAI,OACV,GAAG,WAAW,MAAM,MAAM,GAAG,EAAE;OAE/B,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAI1C,GAAG,aAAa,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAClD,GAAG,WAAW;EAEd,OAAO,GAAG;CACX;;;;;;;CAQA,IAAI,MAAc,IAA4B;EAC7C,IAAI,UAAU,IAAI,aAAa,MAAM,EAAE;EACvC,KAAK,OAAO,KAAK,OAAO;EACxB,KAAK,MAAM,OAAO,MAAM,OAAO;EAC/B,KAAK,YAAY;EACjB,OAAO;CACR;CAEA,MAAM,MAAiC;EACtC,MAAM,QAAQ,KAAK,MAAM,MAAM,IAAI;EACnC,IAAI,OACH,OAAO;GACN,IAAI,MAAM,MAAM;GAChB,QAAQ,MAAM;EACf;EAED,QAAQ,IAAI,0BAA0B,MAAM;CAC7C;CAIA,IAAI,GAAG,IAAkC;EACxC,KAAK,aAAa,KAAK,WAAW,OAAO,EAAE;EAC3C,OAAO;CACR;CAEA,cAAc;EACb,KAAK,SAAS,KAAK,OAAO,MAAM,GAAG,MAAM;GAGxC,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IAAI,EAAE,KAAK,QAAQ,EAAE,KAAK,MAAM,GAAG,KAC3D,IAAI,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,KACtC,OAAO;QACD,IAAI,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,KAC7C,OAAO;QACD,IAAI,EAAE,KAAK,OAAO,EAAE,KAAK,IAAI,CAEpC,OACC,OAAO,EAAE,KAAK,EAAE,CAAC,cAAc,EAAE,KAAK,EAAE;GAG1C,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK;EAC/B,CAAC;CACF;AACD;AAEA,IAAM,eAAN,MAAmB;CAClB;CACA;CAEA,YAAY,MAAc,IAAoB;EAC7C,KAAK,OAAO;EACZ,KAAK,KAAK;CACX;AACD"}
@@ -1,4 +1,4 @@
1
- import { n as ServerEvent, t as MiddlewareFunction } from "./MiddlewareFunction-7rIvFkjl.mjs";
1
+ import { n as ServerEvent, t as MiddlewareFunction } from "./MiddlewareFunction-DMYxjzF4.mjs";
2
2
  //#region src/server/types/ServerFunction.d.ts
3
3
  type ServerFunction = (e: ServerEvent) => Response | undefined | void | Promise<Response | undefined | void>;
4
4
  //#endregion
@@ -38,4 +38,4 @@ interface Match {
38
38
  }
39
39
  //#endregion
40
40
  export { Server as t };
41
- //# sourceMappingURL=Server-hwbZ7P2g.d.mts.map
41
+ //# sourceMappingURL=Server-ClwvuilS.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Server-hwbZ7P2g.d.mts","names":[],"sources":["../src/server/types/ServerFunction.ts","../src/server/Server.ts"],"mappings":";;KAEK,kBACJ,GAAG,gBACC,8BAA8B,QAAQ;;;;;;cCKtB;;EAEpB,QAAQ;EAIR,YAAY;EAEZ;;;;;;EAUA,QAAe,OAAO,cAAc,KAAK,OAAO,gBAAc,QAAQ;;;;;;;EAyCtE,IAAI,cAAc,IAAI,iBAAiB;EAQvC,MAAM,eAAe;EAarB,OAAO,IAAI,uBAAuB;;cAyB7B;EACL;EACA,IAAI;EAEJ,YAAY,cAAc,IAAI;;UAkBrB;EACT,IAAI;EACJ,SAAS"}
1
+ {"version":3,"file":"Server-ClwvuilS.d.mts","names":[],"sources":["../src/server/types/ServerFunction.ts","../src/server/Server.ts"],"mappings":";;KAEK,kBACJ,GAAG,gBACC,8BAA8B,QAAQ;;;;;;cCKtB;;EAEpB,QAAQ;EAIR,YAAY;EAEZ;;;;;;EAUA,QAAe,OAAO,cAAc,KAAK,OAAO,gBAAc,QAAQ;;;;;;;EAyCtE,IAAI,cAAc,IAAI,iBAAiB;EAQvC,MAAM,eAAe;EAarB,OAAO,IAAI,uBAAuB;;cAyB7B;EACL;EACA,IAAI;EAEJ,YAAY,cAAc,IAAI;;UAkBrB;EACT,IAAI;EACJ,SAAS"}
@@ -1,14 +1,37 @@
1
1
  import { t as env } from "./env-C2SUAwAq.mjs";
2
- import { n as getBasePath, t as addBaseToPath } from "./basePath-DQnbHc7o.mjs";
2
+ import { t as addBaseToPath } from "./basePath-B6hmOMl4.mjs";
3
+ import { n as requestBase } from "./runHooks-C7kt7SEo.mjs";
3
4
  import { parseCookie, stringifySetCookie } from "cookie";
4
5
  //#region src/server/CookieHelper.ts
6
+ /**
7
+ * Browsers silently drop `Set-Cookie` headers above ~4096 bytes, so a cookie
8
+ * this large is a bug in the caller (the session helper, flash messages, or
9
+ * app code) rather than a header worth sending. Throwing here makes the
10
+ * failure visible instead of losing the cookie with no trace.
11
+ */
12
+ const MAX_COOKIE_BYTES = 4096;
5
13
  var CookieHelper = class {
6
14
  request;
7
15
  cookies = /* @__PURE__ */ new Map();
16
+ /**
17
+ * Whether anything read a cookie during the request, which makes the
18
+ * response depend on who asked for it (see `CacheOptions`)
19
+ */
20
+ read = false;
8
21
  constructor(request) {
9
22
  this.request = request;
10
23
  }
11
24
  get(name) {
25
+ this.read = true;
26
+ return this.peek(name);
27
+ }
28
+ /**
29
+ * Gets a cookie's value without marking the response as depending on
30
+ * cookies. For framework reads whose result only matters when the cookie
31
+ * is there (the flash message, which deletes the cookie when it's found).
32
+ * @internal
33
+ */
34
+ peek(name) {
12
35
  if (this.cookies.has(name)) return parseCookie(this.cookies.get(name))[name];
13
36
  const header = this.request.headers.get("Cookie");
14
37
  return parseCookie(header ?? "")[name];
@@ -16,34 +39,44 @@ var CookieHelper = class {
16
39
  set(name, value, options) {
17
40
  options ??= {};
18
41
  options.httpOnly ??= true;
19
- options.secure ??= true;
42
+ options.secure ??= isHttps(this.request);
20
43
  options.sameSite ??= "lax";
21
- this.cookies.set(name, stringifySetCookie({
22
- name,
23
- value,
24
- ...options
25
- }));
44
+ this.cookies.set(name, serializeCookie(name, value, options));
26
45
  }
27
46
  delete(name, options) {
28
47
  options ??= {};
29
48
  options.httpOnly ??= true;
30
- options.secure ??= true;
49
+ options.secure ??= isHttps(this.request);
31
50
  options.sameSite ??= "lax";
32
51
  options.expires = /* @__PURE__ */ new Date(0);
33
- this.cookies.set(name, stringifySetCookie({
34
- name,
35
- value: "",
36
- ...options
37
- }));
52
+ this.cookies.set(name, serializeCookie(name, "", options));
38
53
  }
39
54
  };
55
+ /**
56
+ * Whether the request itself was served over HTTPS, so `Secure` can default to
57
+ * on without breaking plain-`http://localhost` development (browsers --
58
+ * notably older Safari -- refuse `Secure` cookies set over http).
59
+ */
60
+ function isHttps(request) {
61
+ return new URL(request.url).protocol === "https:";
62
+ }
63
+ function serializeCookie(name, value, options) {
64
+ const serialized = stringifySetCookie({
65
+ name,
66
+ value,
67
+ ...options
68
+ });
69
+ const bytes = new TextEncoder().encode(serialized).length;
70
+ if (bytes > MAX_COOKIE_BYTES) throw new Error(`The "${name}" cookie is too large (${bytes} bytes; browsers limit a cookie to ${MAX_COOKIE_BYTES} bytes) and would be silently dropped. No cookie was set; store less data, or keep it server-side instead.`);
71
+ return serialized;
72
+ }
40
73
  //#endregion
41
74
  //#region src/server/FlashHelper.ts
42
75
  const COOKIE_NAME$1 = "torpor-flash";
43
76
  /**
44
77
  * A one-time values store set in a form action and shown on the next page
45
78
  * render, which survives the redirect. Available as `event.flash`; the
46
- * framework reads it into `$page.flash` when a page is rendered, so
79
+ * framework reads it into `$context.$page.flash` when a page is rendered, so
47
80
  * components display it reactively:
48
81
  *
49
82
  * ```ts
@@ -58,6 +91,8 @@ const COOKIE_NAME$1 = "torpor-flash";
58
91
  * ```
59
92
  *
60
93
  * ```torp
94
+ * let { $page } = $context;
95
+ *
61
96
  * @if ($page.flash?.message) {
62
97
  * <p class="flash">{$page.flash.message}</p>
63
98
  * }
@@ -85,7 +120,7 @@ var FlashHelper = class {
85
120
  * ever reaching the browser.)
86
121
  */
87
122
  get() {
88
- const cookie = this.#cookies.get(COOKIE_NAME$1);
123
+ const cookie = this.#cookies.peek(COOKIE_NAME$1);
89
124
  if (!cookie) return void 0;
90
125
  this.#cookies.delete(COOKIE_NAME$1, { path: "/" });
91
126
  try {
@@ -176,27 +211,25 @@ var SessionHelper = class {
176
211
  }
177
212
  /**
178
213
  * Reads and verifies the session, returning its data, or undefined when
179
- * there is no cookie, the signature doesn't match, or the session has
180
- * expired.
214
+ * there is no cookie, the signature doesn't match, the value is malformed,
215
+ * or the session has expired.
181
216
  */
182
217
  async get() {
183
- const value = this.#cookies.get(COOKIE_NAME);
184
- if (!value) return void 0;
185
- const payload = await verifyValue(value);
186
- if (!payload) return void 0;
187
- this.#id = payload.id;
188
- return payload.data;
218
+ return (await this.#readPayload())?.data;
189
219
  }
190
220
  /**
191
221
  * Writes the session, signing the data and setting the cookie. Keeps
192
- * the current session id, minting one when there isn't a valid session
193
- * yet. Call `regenerate` instead when the session's identity should
194
- * change (e.g. at login, to prevent session fixation).
222
+ * the current session id, reading (and verifying) the existing cookie
223
+ * when it hasn't been read yet in this request, and minting one when
224
+ * there isn't a valid session. Call `regenerate` instead when the
225
+ * session's identity should change (e.g. at login, to prevent session
226
+ * fixation).
195
227
  */
196
228
  async set(data, options) {
229
+ if (this.#id === void 0) await this.#readPayload();
197
230
  const id = this.#id ?? crypto.randomUUID();
198
- this.#id = id;
199
231
  await this.#write(id, data, options);
232
+ this.#id = id;
200
233
  }
201
234
  /**
202
235
  * Writes the session with a fresh id, replacing any existing one. Use
@@ -205,8 +238,8 @@ var SessionHelper = class {
205
238
  */
206
239
  async regenerate(data = {}, options) {
207
240
  const id = crypto.randomUUID();
208
- this.#id = id;
209
241
  await this.#write(id, data, options);
242
+ this.#id = id;
210
243
  }
211
244
  /**
212
245
  * Deletes the session cookie. Note that a server-side record (if you
@@ -216,6 +249,15 @@ var SessionHelper = class {
216
249
  this.#id = void 0;
217
250
  this.#cookies.delete(COOKIE_NAME, { path: "/" });
218
251
  }
252
+ /** Reads, verifies and caches the current session payload (and its id). */
253
+ async #readPayload() {
254
+ const value = this.#cookies.get(COOKIE_NAME);
255
+ if (!value) return void 0;
256
+ const payload = await verifyValue(value);
257
+ if (!payload) return void 0;
258
+ this.#id = payload.id;
259
+ return payload;
260
+ }
219
261
  async #write(id, data, options) {
220
262
  const maxAge = options?.maxAge ?? DEFAULT_MAX_AGE;
221
263
  const payload = {
@@ -256,7 +298,14 @@ async function verifyValue(value) {
256
298
  const dot = value.lastIndexOf(".");
257
299
  if (dot === -1) return void 0;
258
300
  const encoded = value.slice(0, dot);
259
- if (!await crypto.subtle.verify("HMAC", await signingKey(), decodeBase64Url(value.slice(dot + 1)), new TextEncoder().encode(encoded))) return void 0;
301
+ const key = await signingKey();
302
+ let valid;
303
+ try {
304
+ valid = await crypto.subtle.verify("HMAC", key, decodeBase64Url(value.slice(dot + 1)), new TextEncoder().encode(encoded));
305
+ } catch {
306
+ return;
307
+ }
308
+ if (!valid) return void 0;
260
309
  let payload;
261
310
  try {
262
311
  payload = JSON.parse(new TextDecoder().decode(decodeBase64Url(encoded)));
@@ -289,6 +338,13 @@ var ServerEvent = class {
289
338
  */
290
339
  error;
291
340
  params;
341
+ /**
342
+ * Data shared by everything that handles this request: middleware, folder
343
+ * hooks (as `event.appData`), and the loads and actions they run around.
344
+ * Folder hooks run before route middleware, so a route's guard can read
345
+ * e.g. the user that an auth hook loaded.
346
+ */
347
+ appData = {};
292
348
  adapter;
293
349
  cookies;
294
350
  headers;
@@ -296,6 +352,7 @@ var ServerEvent = class {
296
352
  flash;
297
353
  #url;
298
354
  #formData;
355
+ #cache;
299
356
  /** The request URL, parsed lazily. */
300
357
  get url() {
301
358
  return this.#url ??= new URL(this.request.url);
@@ -323,7 +380,7 @@ var ServerEvent = class {
323
380
  #addHeaders() {
324
381
  for (let cookie of this.cookies.cookies.values()) this.response.headers.append("set-cookie", cookie);
325
382
  for (let header of this.headers.headers.entries()) this.response.headers.append(header[0], header[1]);
326
- const base = getBasePath();
383
+ const base = requestBase(this);
327
384
  if (base) {
328
385
  const location = this.response.headers.get("Location");
329
386
  if (location) {
@@ -333,6 +390,45 @@ var ServerEvent = class {
333
390
  }
334
391
  }
335
392
  /**
393
+ * Sets how the response may be cached (`Cache-Control` and `Vary`). Calls
394
+ * are merged, with the most restrictive setting winning. See
395
+ * `CacheOptions`.
396
+ */
397
+ cache(options) {
398
+ const current = this.#cache;
399
+ if (!current) {
400
+ this.#cache = {
401
+ ...options,
402
+ vary: options.vary ? [...options.vary] : void 0
403
+ };
404
+ return;
405
+ }
406
+ const min = (a, b) => a === void 0 ? b : b === void 0 ? a : Math.min(a, b);
407
+ current.maxAge = min(current.maxAge, options.maxAge);
408
+ current.sMaxAge = min(current.sMaxAge, options.sMaxAge);
409
+ current.staleWhileRevalidate = min(current.staleWhileRevalidate, options.staleWhileRevalidate);
410
+ if (options.private !== void 0) current.private = current.private === true || options.private;
411
+ current.noStore = current.noStore || options.noStore;
412
+ if (options.vary) current.vary = Array.from(/* @__PURE__ */ new Set([...current.vary ?? [], ...options.vary]));
413
+ }
414
+ /** The merged `cache()` settings, if any were set. */
415
+ get cacheOptions() {
416
+ return this.#cache;
417
+ }
418
+ /**
419
+ * Keeps background work running after the response is sent, e.g.
420
+ * refreshing a cache or logging. On Cloudflare this is the worker's
421
+ * `ctx.waitUntil`, without which the work would be cut off; elsewhere the
422
+ * promise just runs on. Either way a rejection is logged rather than left
423
+ * unhandled.
424
+ */
425
+ waitUntil(promise) {
426
+ const handled = promise.catch((error) => {
427
+ console.error("[torpor] Background work failed:", error);
428
+ });
429
+ this.adapter?.ctx?.waitUntil?.(handled);
430
+ }
431
+ /**
336
432
  * Reads the request body as JSON.
337
433
  */
338
434
  json() {
@@ -350,4 +446,4 @@ var ServerEvent = class {
350
446
  //#endregion
351
447
  export { HeaderHelper as n, CookieHelper as r, ServerEvent as t };
352
448
 
353
- //# sourceMappingURL=ServerEvent-L0rT_mBJ.mjs.map
449
+ //# sourceMappingURL=ServerEvent-BBRkd4Ya.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ServerEvent-BBRkd4Ya.mjs","names":["COOKIE_NAME"],"sources":["../src/server/CookieHelper.ts","../src/server/FlashHelper.ts","../src/server/HeaderHelper.ts","../src/server/SessionHelper.ts","../src/server/ServerEvent.ts"],"sourcesContent":["import { type SerializeOptions, parseCookie, stringifySetCookie } from \"cookie\";\n\n/**\n * Browsers silently drop `Set-Cookie` headers above ~4096 bytes, so a cookie\n * this large is a bug in the caller (the session helper, flash messages, or\n * app code) rather than a header worth sending. Throwing here makes the\n * failure visible instead of losing the cookie with no trace.\n */\nconst MAX_COOKIE_BYTES = 4096;\n\nexport default class CookieHelper {\n\trequest: Request;\n\tcookies: Map<string, string> = new Map();\n\t/**\n\t * Whether anything read a cookie during the request, which makes the\n\t * response depend on who asked for it (see `CacheOptions`)\n\t */\n\tread = false;\n\n\tconstructor(request: Request) {\n\t\tthis.request = request;\n\t}\n\n\tget(name: string): string | undefined {\n\t\tthis.read = true;\n\t\treturn this.peek(name);\n\t}\n\n\t/**\n\t * Gets a cookie's value without marking the response as depending on\n\t * cookies. For framework reads whose result only matters when the cookie\n\t * is there (the flash message, which deletes the cookie when it's found).\n\t * @internal\n\t */\n\tpeek(name: string): string | undefined {\n\t\t// If it's been set, return the value from the map\n\t\tif (this.cookies.has(name)) {\n\t\t\t// The stored value is a serialized Set-Cookie header; pull the\n\t\t\t// \"name=value\" prefix off and re-parse to get just the value\n\t\t\treturn parseCookie(this.cookies.get(name)!)[name];\n\t\t}\n\n\t\t// Otherwise, return the value from the `cookie` header\n\t\tconst header = this.request.headers.get(\"Cookie\");\n\t\treturn parseCookie(header ?? \"\")[name];\n\t}\n\n\tset(name: string, value: string, options?: SerializeOptions): void {\n\t\t// Set a cookie header with some default values for security\n\t\toptions ??= {};\n\t\toptions.httpOnly ??= true;\n\t\toptions.secure ??= isHttps(this.request);\n\t\toptions.sameSite ??= \"lax\";\n\n\t\tthis.cookies.set(name, serializeCookie(name, value, options));\n\t}\n\n\tdelete(name: string, options?: SerializeOptions): void {\n\t\t// Set a cookie header with an empty value and an immediate expiry date.\n\t\t// Apply the same secure defaults as `set` so a previously-set Secure\n\t\t// cookie is actually overridden by the deletion.\n\t\toptions ??= {};\n\t\toptions.httpOnly ??= true;\n\t\toptions.secure ??= isHttps(this.request);\n\t\toptions.sameSite ??= \"lax\";\n\t\toptions.expires = new Date(0);\n\n\t\tthis.cookies.set(name, serializeCookie(name, \"\", options));\n\t}\n}\n\n/**\n * Whether the request itself was served over HTTPS, so `Secure` can default to\n * on without breaking plain-`http://localhost` development (browsers --\n * notably older Safari -- refuse `Secure` cookies set over http).\n */\nfunction isHttps(request: Request): boolean {\n\treturn new URL(request.url).protocol === \"https:\";\n}\n\nfunction serializeCookie(name: string, value: string, options: SerializeOptions): string {\n\tconst serialized = stringifySetCookie({ name, value, ...options });\n\tconst bytes = new TextEncoder().encode(serialized).length;\n\tif (bytes > MAX_COOKIE_BYTES) {\n\t\tthrow new Error(\n\t\t\t`The \"${name}\" cookie is too large (${bytes} bytes; browsers limit a cookie to ` +\n\t\t\t\t`${MAX_COOKIE_BYTES} bytes) and would be silently dropped. No cookie was set; ` +\n\t\t\t\t\"store less data, or keep it server-side instead.\",\n\t\t);\n\t}\n\treturn serialized;\n}\n","import CookieHelper from \"./CookieHelper\";\n\nconst COOKIE_NAME = \"torpor-flash\";\n\n/**\n * A one-time values store set in a form action and shown on the next page\n * render, which survives the redirect. Available as `event.flash`; the\n * framework reads it into `$context.$page.flash` when a page is rendered, so\n * components display it reactively:\n *\n * ```ts\n * actions: {\n * \tsave: async (event) => {\n * \t\t// ...save...\n * \t\tevent.flash.set(\"Project saved\"); // { message: \"Project saved\" }\n * \t\tevent.flash.set({ error: \"Import failed\", retryable: true });\n * \t\treturn seeOther(`/projects/${id}`);\n * \t},\n * }\n * ```\n *\n * ```torp\n * let { $page } = $context;\n *\n * @if ($page.flash?.message) {\n * \t<p class=\"flash\">{$page.flash.message}</p>\n * }\n * ```\n *\n * The values ride in a (session-lifetime) cookie that is deleted when it is\n * read, so a page refresh shows them once. No signing: the only person who\n * can fake a flash is the one seeing it, and values are rendered as text.\n * They must be JSON-safe and small enough to fit in the cookie (~4KB). A\n * common shape for a styled banner is `{ type, message }`, for use e.g.\n * with the Notification component -- but the framework only requires the\n * values to be an object. Without cookies the message is simply lost --\n * the action itself still completes.\n */\nexport default class FlashHelper {\n\t#cookies: CookieHelper;\n\n\tconstructor(cookies: CookieHelper) {\n\t\tthis.#cookies = cookies;\n\t}\n\n\t/**\n\t * Reads the flash values, if any, and clears them: the same response\n\t * deletes the cookie, so the message shows exactly once. (When the\n\t * message was set during this same request, e.g. a form action that\n\t * re-renders instead of redirecting, the cookie is consumed without it\n\t * ever reaching the browser.)\n\t */\n\tget(): Record<string, unknown> | undefined {\n\t\t// A flash that's found deletes its cookie, and that Set-Cookie makes\n\t\t// the response private; one that isn't there leaves it cacheable\n\t\tconst cookie = this.#cookies.peek(COOKIE_NAME);\n\t\tif (!cookie) return undefined;\n\t\tthis.#cookies.delete(COOKIE_NAME, { path: \"/\" });\n\t\ttry {\n\t\t\tconst decoded = JSON.parse(decodeURIComponent(cookie));\n\t\t\tif (typeof decoded !== \"object\" || decoded === null || Array.isArray(decoded)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn decoded as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Sets the flash values. A string is stored as `{ message: value }`, an\n\t * object as-is, e.g. `flash.set({ error: \"Import failed\" })`.\n\t */\n\tset(value: string | Record<string, unknown>): void {\n\t\tconst data = typeof value === \"string\" ? { message: value } : value;\n\t\tthis.#cookies.set(COOKIE_NAME, encodeURIComponent(JSON.stringify(data)), { path: \"/\" });\n\t}\n\n\t/**\n\t * Clears an unread flash message, e.g. so it isn't shown on a later\n\t * re-render of the same page.\n\t */\n\tclear(): void {\n\t\tthis.#cookies.delete(COOKIE_NAME, { path: \"/\" });\n\t}\n}\n","export default class HeaderHelper {\n\trequest: Request;\n\theaders: Map<string, string> = new Map();\n\n\tconstructor(request: Request) {\n\t\tthis.request = request;\n\t}\n\n\tget(name: string): string | undefined {\n\t\t// If it's been set, return the updated value\n\t\tif (this.headers.has(name)) {\n\t\t\treturn this.headers.get(name);\n\t\t}\n\t\t// Otherwise, return the value from the header\n\t\treturn this.request.headers.get(name) ?? undefined;\n\t}\n\n\tset(name: string, value: string): void {\n\t\tthis.headers.set(name, value);\n\t}\n\n\tdelete(name: string): void {\n\t\tthis.headers.delete(name);\n\t}\n}\n","import env from \"../env\";\nimport CookieHelper from \"./CookieHelper\";\n\nconst COOKIE_NAME = \"torpor-session\";\nconst DEFAULT_MAX_AGE = 30 * 24 * 60 * 60; // 30 days, in seconds\n\n/**\n * The data stored in the session. Must be JSON-safe, and small enough to\n * fit in a cookie (4KB) along with the id, expiry and signature.\n */\ntype SessionData = Record<string, unknown>;\n\ntype SessionPayload = {\n\tid: string;\n\tdata: SessionData;\n\t/** Expiry, as a Unix epoch in milliseconds */\n\texp: number;\n};\n\n// The imported signing key, cached per secret so repeated calls (per\n// request) don't re-import\nconst keys = new Map<string, Promise<CryptoKey>>();\n\n/**\n * A helper for reading and writing the signed session cookie, available as\n * `event.session` in load functions, actions, +server endpoints and hooks.\n *\n * The value is signed with HMAC-SHA256 using `TORPOR_SESSION_SECRET` from\n * the environment, so it can't be forged or tampered with -- but it is\n * still client-side storage: everything rides in the cookie, it can't be\n * revoked individually, and it is limited to ~4KB. When you need\n * revocation, store `session.id` in your database, check it on each\n * authed request (e.g. in a `_hook.server.ts`), and delete the row to\n * revoke.\n *\n * ```ts\n * // Login action\n * const user = await checkPassword(event.form());\n * await event.session.regenerate({ userId: user.id });\n *\n * // Root hook\n * const session = await event.session.get();\n * if (session) {\n * \tevent.appData.user = await getUser(session.userId);\n * }\n * ```\n */\nexport default class SessionHelper {\n\t#cookies: CookieHelper;\n\t#id: string | undefined;\n\n\tconstructor(cookies: CookieHelper) {\n\t\tthis.#cookies = cookies;\n\t}\n\n\t/**\n\t * The id embedded in the current session cookie, or undefined when\n\t * there is no valid session. Stable across `set` calls, so it can be\n\t * used as a database key; `regenerate` mints a new one.\n\t */\n\tget id(): string | undefined {\n\t\treturn this.#id;\n\t}\n\n\t/**\n\t * Reads and verifies the session, returning its data, or undefined when\n\t * there is no cookie, the signature doesn't match, the value is malformed,\n\t * or the session has expired.\n\t */\n\tasync get(): Promise<SessionData | undefined> {\n\t\tconst payload = await this.#readPayload();\n\t\treturn payload?.data;\n\t}\n\n\t/**\n\t * Writes the session, signing the data and setting the cookie. Keeps\n\t * the current session id, reading (and verifying) the existing cookie\n\t * when it hasn't been read yet in this request, and minting one when\n\t * there isn't a valid session. Call `regenerate` instead when the\n\t * session's identity should change (e.g. at login, to prevent session\n\t * fixation).\n\t */\n\tasync set(data: SessionData, options?: { maxAge?: number }): Promise<void> {\n\t\tif (this.#id === undefined) {\n\t\t\t// `id` is documented as stable, and callers may key a database row\n\t\t\t// on it without calling `get()` first (e.g. writing from a hook).\n\t\t\t// Read the existing cookie so `set` keeps its id instead of\n\t\t\t// silently replacing it.\n\t\t\tawait this.#readPayload();\n\t\t}\n\t\tconst id = this.#id ?? crypto.randomUUID();\n\t\tawait this.#write(id, data, options);\n\t\tthis.#id = id;\n\t}\n\n\t/**\n\t * Writes the session with a fresh id, replacing any existing one. Use\n\t * it when a session's privilege level changes (login, permission\n\t * upgrade), so a cookie that was set before the change can't be reused.\n\t */\n\tasync regenerate(data: SessionData = {}, options?: { maxAge?: number }): Promise<void> {\n\t\tconst id = crypto.randomUUID();\n\t\tawait this.#write(id, data, options);\n\t\tthis.#id = id;\n\t}\n\n\t/**\n\t * Deletes the session cookie. Note that a server-side record (if you\n\t * keep one) must be deleted or revoked separately.\n\t */\n\tasync destroy(): Promise<void> {\n\t\tthis.#id = undefined;\n\t\tthis.#cookies.delete(COOKIE_NAME, { path: \"/\" });\n\t}\n\n\t/** Reads, verifies and caches the current session payload (and its id). */\n\tasync #readPayload(): Promise<SessionPayload | undefined> {\n\t\tconst value = this.#cookies.get(COOKIE_NAME);\n\t\tif (!value) return undefined;\n\t\tconst payload = await verifyValue(value);\n\t\tif (!payload) return undefined;\n\t\tthis.#id = payload.id;\n\t\treturn payload;\n\t}\n\n\tasync #write(\n\t\tid: string,\n\t\tdata: SessionData,\n\t\toptions: { maxAge?: number } | undefined,\n\t): Promise<void> {\n\t\tconst maxAge = options?.maxAge ?? DEFAULT_MAX_AGE;\n\t\tconst payload: SessionPayload = { id, data, exp: Date.now() + maxAge * 1000 };\n\t\tconst encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify(payload)));\n\t\tconst signature = await sign(encoded);\n\t\tthis.#cookies.set(COOKIE_NAME, `${encoded}.${signature}`, { path: \"/\", maxAge });\n\t}\n}\n\nfunction secret(): string {\n\tconst value = env().TORPOR_SESSION_SECRET;\n\tif (!value) {\n\t\tthrow new Error(\n\t\t\t\"TORPOR_SESSION_SECRET is not set. Add it to the environment (or to a .env \" +\n\t\t\t\t\"file in dev and preview) to use sessions.\",\n\t\t);\n\t}\n\treturn value;\n}\n\nfunction signingKey(): Promise<CryptoKey> {\n\tconst value = secret();\n\tlet key = keys.get(value);\n\tif (!key) {\n\t\tkey = crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tnew TextEncoder().encode(value),\n\t\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\t\tfalse,\n\t\t\t[\"sign\", \"verify\"],\n\t\t);\n\t\tkeys.set(value, key);\n\t}\n\treturn key;\n}\n\nasync function sign(payload: string): Promise<string> {\n\tconst signature = await crypto.subtle.sign(\n\t\t\"HMAC\",\n\t\tawait signingKey(),\n\t\tnew TextEncoder().encode(payload),\n\t);\n\treturn encodeBase64Url(new Uint8Array(signature));\n}\n\nasync function verifyValue(value: string): Promise<SessionPayload | undefined> {\n\tconst dot = value.lastIndexOf(\".\");\n\tif (dot === -1) return undefined;\n\tconst encoded = value.slice(0, dot);\n\n\t// A tampered, truncated or older-format cookie can contain characters\n\t// that aren't valid base64url. `atob` (and, for some inputs,\n\t// `crypto.subtle.verify`) can throw on those; a bad cookie must read as\n\t// \"no session\", not turn every request into a 500. Keep `signingKey()`\n\t// outside the try so a missing/invalid secret still surfaces as the\n\t// configuration error it is.\n\tconst key = await signingKey();\n\tlet valid: boolean;\n\ttry {\n\t\tvalid = await crypto.subtle.verify(\n\t\t\t\"HMAC\",\n\t\t\tkey,\n\t\t\tdecodeBase64Url(value.slice(dot + 1)),\n\t\t\tnew TextEncoder().encode(encoded),\n\t\t);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!valid) return undefined;\n\n\tlet payload: SessionPayload;\n\ttry {\n\t\tpayload = JSON.parse(new TextDecoder().decode(decodeBase64Url(encoded)));\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (\n\t\ttypeof payload?.id !== \"string\" ||\n\t\ttypeof payload?.exp !== \"number\" ||\n\t\ttypeof payload?.data !== \"object\" ||\n\t\tpayload.data === null ||\n\t\tpayload.exp < Date.now()\n\t) {\n\t\treturn undefined;\n\t}\n\treturn payload;\n}\n\nfunction encodeBase64Url(bytes: Uint8Array): string {\n\t// btoa can't take raw bytes, and long argument lists overflow, so\n\t// convert in chunks\n\tlet binary = \"\";\n\tfor (let i = 0; i < bytes.length; i += 0x1000) {\n\t\tbinary += String.fromCharCode(...bytes.subarray(i, i + 0x1000));\n\t}\n\treturn btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nfunction decodeBase64Url(value: string): Uint8Array<ArrayBuffer> {\n\tconst binary = atob(value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\"));\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n","import { addBaseToPath } from \"../site/basePath\";\nimport { requestBase } from \"../site/requestBase\";\nimport CookieHelper from \"./CookieHelper\";\nimport FlashHelper from \"./FlashHelper\";\nimport HeaderHelper from \"./HeaderHelper\";\nimport SessionHelper from \"./SessionHelper\";\nimport type CacheOptions from \"./types/CacheOptions\";\n\nexport default class ServerEvent {\n\trequest: Request;\n\tresponse: Response | undefined | void;\n\t/**\n\t * Set when the route handler (or a middleware enter hook) threw an\n\t * error. Exit hooks can return a Response to handle it; if none does,\n\t * the error is rethrown to the caller.\n\t */\n\terror: unknown;\n\t// TODO: Should we cast types??\n\tparams?: Record<string, string>;\n\t/**\n\t * Data shared by everything that handles this request: middleware, folder\n\t * hooks (as `event.appData`), and the loads and actions they run around.\n\t * Folder hooks run before route middleware, so a route's guard can read\n\t * e.g. the user that an auth hook loaded.\n\t */\n\tappData: Record<string, any> = {};\n\n\tadapter: any;\n\n\tcookies: CookieHelper;\n\theaders: HeaderHelper;\n\tsession: SessionHelper;\n\tflash: FlashHelper;\n\n\t// Parsed once per request; Server.fetch passes the URL it already needed\n\t// for matching so it isn't parsed twice\n\t#url: URL | undefined;\n\n\t// The request's form body, parsed at most once per request: the schema\n\t// validation and the event's `form()`/`formData()` accessors share a\n\t// single read, since a request body can't be read twice\n\t#formData: Promise<FormData> | undefined;\n\n\t// The merged `cache()` settings, if any\n\t#cache: CacheOptions | undefined;\n\n\t/** The request URL, parsed lazily. */\n\tget url(): URL {\n\t\treturn (this.#url ??= new URL(this.request.url));\n\t}\n\n\tconstructor(request: Request, params?: Record<string, string>, url?: URL) {\n\t\tthis.request = request;\n\t\tthis.params = params;\n\t\tthis.#url = url;\n\t\tthis.cookies = new CookieHelper(request);\n\t\tthis.headers = new HeaderHelper(request);\n\t\tthis.session = new SessionHelper(this.cookies);\n\t\tthis.flash = new FlashHelper(this.cookies);\n\n\t\t// Adapters may have added the `adapter` property to globalThis\n\t\t// @ts-ignore\n\t\tthis.adapter = globalThis.adapter;\n\t}\n\n\taddHeaders(): void {\n\t\tif (!this.response) {\n\t\t\tthrow new Error(\"Response not created yet\");\n\t\t}\n\n\t\ttry {\n\t\t\tthis.#addHeaders();\n\t\t} catch (e) {\n\t\t\t// The headers of a Response obtained from `fetch()` are immutable,\n\t\t\t// so an endpoint that returns a fetched Response directly would\n\t\t\t// otherwise kill the whole request (and process) -- swap in a\n\t\t\t// mutable clone and write the headers to that instead\n\t\t\tif (!(e instanceof TypeError)) throw e;\n\t\t\tthis.response = new Response(this.response.body, this.response);\n\t\t\tthis.#addHeaders();\n\t\t}\n\t}\n\n\t#addHeaders(): void {\n\t\tfor (let cookie of this.cookies.cookies.values()) {\n\t\t\tthis.response!.headers.append(\"set-cookie\", cookie);\n\t\t}\n\n\t\tfor (let header of this.headers.headers.entries()) {\n\t\t\tthis.response!.headers.append(header[0], header[1]);\n\t\t}\n\n\t\t// Redirect locations are written base-free, so that user code isn't\n\t\t// aware of the base path. The base belongs to the site handling this\n\t\t// request, not to module state (several sites can share a process)\n\t\tconst base = requestBase(this);\n\t\tif (base) {\n\t\t\tconst location = this.response!.headers.get(\"Location\");\n\t\t\tif (location) {\n\t\t\t\tconst rewritten = addBaseToPath(location, base);\n\t\t\t\tif (rewritten !== location) {\n\t\t\t\t\tthis.response!.headers.set(\"Location\", rewritten);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sets how the response may be cached (`Cache-Control` and `Vary`). Calls\n\t * are merged, with the most restrictive setting winning. See\n\t * `CacheOptions`.\n\t */\n\tcache(options: CacheOptions): void {\n\t\tconst current = this.#cache;\n\t\tif (!current) {\n\t\t\tthis.#cache = { ...options, vary: options.vary ? [...options.vary] : undefined };\n\t\t\treturn;\n\t\t}\n\t\tconst min = (a?: number, b?: number) =>\n\t\t\ta === undefined ? b : b === undefined ? a : Math.min(a, b);\n\t\tcurrent.maxAge = min(current.maxAge, options.maxAge);\n\t\tcurrent.sMaxAge = min(current.sMaxAge, options.sMaxAge);\n\t\tcurrent.staleWhileRevalidate = min(current.staleWhileRevalidate, options.staleWhileRevalidate);\n\t\tif (options.private !== undefined) {\n\t\t\tcurrent.private = current.private === true || options.private;\n\t\t}\n\t\tcurrent.noStore = current.noStore || options.noStore;\n\t\tif (options.vary) {\n\t\t\tcurrent.vary = Array.from(new Set([...(current.vary ?? []), ...options.vary]));\n\t\t}\n\t}\n\n\t/** The merged `cache()` settings, if any were set. */\n\tget cacheOptions(): CacheOptions | undefined {\n\t\treturn this.#cache;\n\t}\n\n\t/**\n\t * Keeps background work running after the response is sent, e.g.\n\t * refreshing a cache or logging. On Cloudflare this is the worker's\n\t * `ctx.waitUntil`, without which the work would be cut off; elsewhere the\n\t * promise just runs on. Either way a rejection is logged rather than left\n\t * unhandled.\n\t */\n\twaitUntil(promise: Promise<unknown>): void {\n\t\tconst handled = promise.catch((error) => {\n\t\t\tconsole.error(\"[torpor] Background work failed:\", error);\n\t\t});\n\t\tthis.adapter?.ctx?.waitUntil?.(handled);\n\t}\n\n\t/**\n\t * Reads the request body as JSON.\n\t */\n\tjson(): Promise<unknown> {\n\t\treturn this.request.json();\n\t}\n\n\t/**\n\t * Reads the request body as the web standard FormData object. The body is\n\t * parsed at most once per request, so that everything that reads the form\n\t * (schema validation, `event.form()`, `event.formData()`) shares the read.\n\t */\n\tformData(): Promise<FormData> {\n\t\treturn (this.#formData ??= this.request.formData());\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAM,mBAAmB;AAEzB,IAAqB,eAArB,MAAkC;CACjC;CACA,0BAA+B,IAAI,IAAI;;;;;CAKvC,OAAO;CAEP,YAAY,SAAkB;EAC7B,KAAK,UAAU;CAChB;CAEA,IAAI,MAAkC;EACrC,KAAK,OAAO;EACZ,OAAO,KAAK,KAAK,IAAI;CACtB;;;;;;;CAQA,KAAK,MAAkC;EAEtC,IAAI,KAAK,QAAQ,IAAI,IAAI,GAGxB,OAAO,YAAY,KAAK,QAAQ,IAAI,IAAI,CAAE,CAAC,CAAC;EAI7C,MAAM,SAAS,KAAK,QAAQ,QAAQ,IAAI,QAAQ;EAChD,OAAO,YAAY,UAAU,EAAE,CAAC,CAAC;CAClC;CAEA,IAAI,MAAc,OAAe,SAAkC;EAElE,YAAY,CAAC;EACb,QAAQ,aAAa;EACrB,QAAQ,WAAW,QAAQ,KAAK,OAAO;EACvC,QAAQ,aAAa;EAErB,KAAK,QAAQ,IAAI,MAAM,gBAAgB,MAAM,OAAO,OAAO,CAAC;CAC7D;CAEA,OAAO,MAAc,SAAkC;EAItD,YAAY,CAAC;EACb,QAAQ,aAAa;EACrB,QAAQ,WAAW,QAAQ,KAAK,OAAO;EACvC,QAAQ,aAAa;EACrB,QAAQ,0BAAU,IAAI,KAAK,CAAC;EAE5B,KAAK,QAAQ,IAAI,MAAM,gBAAgB,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,IAAI,GAAG,CAAC;EAC1D,QAAQ,SAAS,IAAI,QAAQ,QAAQ,QAAQ,MAAM;EACnD,QAAQ,UAAU,IAAI,QAAQ,SAAS,QAAQ,OAAO;EACtD,QAAQ,uBAAuB,IAAI,QAAQ,sBAAsB,QAAQ,oBAAoB;EAC7F,IAAI,QAAQ,YAAY,KAAA,GACvB,QAAQ,UAAU,QAAQ,YAAY,QAAQ,QAAQ;EAEvD,QAAQ,UAAU,QAAQ,WAAW,QAAQ;EAC7C,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,qBAAK,IAAI,IAAI,CAAC,GAAI,QAAQ,QAAQ,CAAC,GAAI,GAAG,QAAQ,IAAI,CAAC,CAAC;CAE/E;;CAGA,IAAI,eAAyC;EAC5C,OAAO,KAAK;CACb;;;;;;;;CASA,UAAU,SAAiC;EAC1C,MAAM,UAAU,QAAQ,OAAO,UAAU;GACxC,QAAQ,MAAM,oCAAoC,KAAK;EACxD,CAAC;EACD,KAAK,SAAS,KAAK,YAAY,OAAO;CACvC;;;;CAKA,OAAyB;EACxB,OAAO,KAAK,QAAQ,KAAK;CAC1B;;;;;;CAOA,WAA8B;EAC7B,OAAQ,KAAK,cAAc,KAAK,QAAQ,SAAS;CAClD;AACD"}
@@ -1,4 +1,4 @@
1
- import { r as ServerLoadEvent } from "./ServerLoadEvent-F60w1TZt.mjs";
1
+ import { r as ServerLoadEvent } from "./ServerLoadEvent-CpcgsKCU.mjs";
2
2
  //#region src/types/ServerHook.d.ts
3
3
  /**
4
4
  * For _hook.server.
@@ -18,4 +18,4 @@ interface ServerHook<Route extends string | undefined = undefined> {
18
18
  }
19
19
  //#endregion
20
20
  export { ServerHook as t };
21
- //# sourceMappingURL=ServerHook-CyVEr5OL.d.mts.map
21
+ //# sourceMappingURL=ServerHook-DY-NSG6n.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ServerHook-CyVEr5OL.d.mts","names":[],"sources":["../src/types/ServerHook.ts"],"mappings":";;;;;UAKyB,WAAW;;;;;;EAMnC,SAAS,OAAO,gBAAgB,WAAW,QAAQ,mBAAmB;;;;;EAKtE,QAAQ,OAAO,gBAAgB,WAAW"}
1
+ {"version":3,"file":"ServerHook-DY-NSG6n.d.mts","names":[],"sources":["../src/types/ServerHook.ts"],"mappings":";;;;;UAKyB,WAAW;;;;;;EAMnC,SAAS,OAAO,gBAAgB,WAAW,QAAQ,mBAAmB;;;;;EAKtE,QAAQ,OAAO,gBAAgB,WAAW"}