noofpi 2.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +6 -2
  2. package/client.d.ts +2 -0
  3. package/dist/build-YRW44BZG.js +212 -0
  4. package/dist/{chunk-YJVMBHNL.js → chunk-JUVQEKLE.js} +43 -12
  5. package/dist/chunk-LJEKK4AK.js +51 -0
  6. package/dist/chunk-O5JRC252.js +245 -0
  7. package/dist/{chunk-G35DW4NA.js → chunk-PC3ZJN4D.js} +11 -1
  8. package/dist/{chunk-NHBXVKEQ.js → chunk-PL3CA2JF.js} +160 -86
  9. package/dist/{chunk-MN5PVHC5.js → chunk-W7ASRDAJ.js} +229 -7
  10. package/dist/{chunk-IE3WF5XF.js → chunk-YN4TKMDX.js} +87 -4
  11. package/dist/chunk-YN64WQ2B.js +562 -0
  12. package/dist/cli.js +21 -9
  13. package/dist/{dev-OAGCOGHA.js → dev-A7VK5V4H.js} +7 -6
  14. package/dist/{devtools-PLUN2DYV.js → devtools-C3PFU57C.js} +1 -1
  15. package/dist/handler-oYl9j0Qa.d.ts +26 -0
  16. package/dist/index.d.ts +26 -11
  17. package/dist/index.js +3 -2
  18. package/dist/payload-DfhHnXAn.d.ts +66 -0
  19. package/dist/{prepare-BN7NMCVQ.js → prepare-JT2NPD5S.js} +6 -5
  20. package/dist/runtime/entry-client.js +4 -4
  21. package/dist/runtime/entry-server.d.ts +6 -4
  22. package/dist/runtime/entry-server.js +88 -25
  23. package/dist/runtime/index.d.ts +24 -6
  24. package/dist/runtime/index.js +5 -3
  25. package/dist/server/bun.d.ts +3 -3
  26. package/dist/server/index.d.ts +35 -7
  27. package/dist/server/index.js +12 -7
  28. package/dist/server/node.d.ts +3 -3
  29. package/dist/session-CLvYihOU.d.ts +275 -0
  30. package/dist/{start-ITRND3BY.js → start-J6ZIUG66.js} +7 -6
  31. package/dist/{types-B6rQOOxS.d.ts → types-Czld0vOH.d.ts} +30 -5
  32. package/package.json +12 -7
  33. package/dist/build-WPHZ7TYZ.js +0 -49
  34. package/dist/chunk-MTXQR32N.js +0 -8
  35. package/dist/chunk-X3DYEZLK.js +0 -253
  36. package/dist/handler-C6NnwBfC.d.ts +0 -17
  37. package/dist/payload-CL6tYBin.d.ts +0 -121
  38. package/dist/route-rules-COilNsVT.d.ts +0 -127
package/README.md CHANGED
@@ -29,11 +29,12 @@ bun add noofpi doofpi
29
29
 
30
30
  Requires Node.js 20 or newer (or Bun). `doofpi` is a peer dependency (`>=1.3.1`).
31
31
 
32
- `tailwindcss`, `@tailwindcss/vite` and `sharp` are optional peer dependencies, install them when you use the feature:
32
+ `tailwindcss`, `@tailwindcss/vite`, `sharp` and `securegeer` are optional peer dependencies, install them when you use the feature:
33
33
 
34
34
  ```sh
35
35
  bun add tailwindcss @tailwindcss/vite # tailwind: true
36
36
  bun add sharp # importing images with ?image
37
+ bun add securegeer # session
37
38
  ```
38
39
 
39
40
  ## CLI
@@ -41,6 +42,7 @@ bun add sharp # importing images with ?image
41
42
  ```
42
43
  noofpi dev Start the dev server with live reload
43
44
  noofpi build Build for production into .output/
45
+ noofpi generate Prerender pages into static HTML files (github-pages, cloudflare-pages)
44
46
  noofpi start Run the production build
45
47
  noofpi preview Build, then run the production build
46
48
  noofpi prepare Generate the .noofpi/ type declarations
@@ -53,7 +55,9 @@ Options: `--root <dir>`, `--port <port>`, `--host <host>`, `--open`, `--preset <
53
55
 
54
56
  `noofpi typecheck` needs `vue-tsc` and `typescript` in the project. Arguments after `--` go to vue-tsc: `noofpi typecheck -- --project tsconfig.app.json`.
55
57
 
56
- `noofpi preview` works with the `node`, `bun` and `docker` presets.
58
+ `noofpi preview` works with the `node`, `bun`, `docker-node` and `docker-bun` presets.
59
+
60
+ `noofpi generate` renders the pages marked with `routeRules[...].prerender` (every static page when none is marked) and writes them as HTML files into `.output/public`, ready for static hosting.
57
61
 
58
62
  ## Documentation
59
63
 
package/client.d.ts CHANGED
@@ -10,6 +10,8 @@ declare module "virtual:noofpi/config" {
10
10
  routeRules: RouteRules;
11
11
  head: HeadConfig;
12
12
  doofpi: DoofpiConfig;
13
+ /** Whether sessions are on */
14
+ session: boolean;
13
15
  devtools: boolean;
14
16
  }
15
17
  export const publicConfig: VirtualConfig;
@@ -0,0 +1,212 @@
1
+ import {
2
+ OUTPUT_DIR,
3
+ createViteConfig,
4
+ finishPresetBuild,
5
+ resolveFonts,
6
+ scanPages,
7
+ unsupportedStaticRules
8
+ } from "./chunk-PL3CA2JF.js";
9
+ import {
10
+ extractLinks,
11
+ generatePreset,
12
+ planPrerender,
13
+ routeToFile
14
+ } from "./chunk-YN4TKMDX.js";
15
+ import {
16
+ createHandler
17
+ } from "./chunk-YN64WQ2B.js";
18
+ import "./chunk-LJEKK4AK.js";
19
+ import "./chunk-O5JRC252.js";
20
+ import "./chunk-PPUFFGCH.js";
21
+ import "./chunk-ELXCFUA4.js";
22
+ import "./chunk-EZPJF4D4.js";
23
+ import {
24
+ PROXY_PREFIX
25
+ } from "./chunk-PC3ZJN4D.js";
26
+ import {
27
+ usesFetchMode
28
+ } from "./chunk-W7ASRDAJ.js";
29
+ import {
30
+ filePathToRoute
31
+ } from "./chunk-Y3NBZ6DW.js";
32
+
33
+ // src/vite/build.ts
34
+ import { existsSync, readFileSync } from "fs";
35
+ import { rm } from "fs/promises";
36
+ import path2 from "path";
37
+ import { pathToFileURL } from "url";
38
+ import { build } from "vite";
39
+
40
+ // src/vite/prerender.ts
41
+ import { mkdir, writeFile } from "fs/promises";
42
+ import path from "path";
43
+ function prerenderOrigin(config) {
44
+ if (config.seo.siteUrl) return new URL(config.seo.siteUrl).origin;
45
+ const host = config.security.allowedHosts?.find(
46
+ (entry) => !entry.startsWith("*.")
47
+ );
48
+ return `http://${host ?? "localhost"}`;
49
+ }
50
+ function problemOf(response, reported) {
51
+ const isHtml = response.headers.get("content-type")?.includes("text/html");
52
+ if (response.status >= 300 && response.status < 400)
53
+ return `redirects to ${response.headers.get("location")}`;
54
+ if (!isHtml || response.status !== 200) return `answered ${response.status}`;
55
+ if (reported.length) {
56
+ const [first] = reported;
57
+ return `failed to render: ${first instanceof Error ? first.message : String(first)}`;
58
+ }
59
+ return void 0;
60
+ }
61
+ async function prerenderPages(options) {
62
+ const { mod, template, config, pages, publicDir, log } = options;
63
+ const plan = planPrerender({
64
+ pages,
65
+ rules: config.routeRules,
66
+ routes: config.prerender.routes,
67
+ ssr: config.ssr
68
+ });
69
+ const origin = prerenderOrigin(config);
70
+ let reported = [];
71
+ const handler = createHandler({
72
+ load: async () => mod,
73
+ getTemplate: async () => template,
74
+ prerender: true,
75
+ onError: (error) => reported.push(error)
76
+ });
77
+ const result = { written: [], skipped: [] };
78
+ const queue = plan.seeds.map((route) => ({ route, named: plan.marked }));
79
+ const seen = new Set(queue.map((entry) => entry.route));
80
+ const root = config.doofpi.root;
81
+ const isApi = (route) => route.startsWith(PROXY_PREFIX + "/") || route === root || route.startsWith(root + "/") || route.startsWith(root + ".");
82
+ for (let next = queue.shift(); next; next = queue.shift()) {
83
+ const { route, named } = next;
84
+ reported = [];
85
+ const response = await handler(
86
+ new Request(origin + route, { headers: { accept: "text/html" } })
87
+ );
88
+ const problem = problemOf(response, reported);
89
+ if (problem) {
90
+ if (named)
91
+ throw new Error(
92
+ `[noofpi] Could not prerender ${route}: it ${problem}. Fix it or set routeRules["${route}"].prerender to false`
93
+ );
94
+ result.skipped.push({ route, reason: problem });
95
+ continue;
96
+ }
97
+ const html = await response.text();
98
+ const file = path.join(publicDir, routeToFile(route));
99
+ await mkdir(path.dirname(file), { recursive: true });
100
+ await writeFile(file, html);
101
+ result.written.push(route);
102
+ log?.(
103
+ ` ${route} -> ${path.relative(publicDir, file).replace(/\\/g, "/")}`
104
+ );
105
+ if (!config.prerender.crawlLinks) continue;
106
+ for (const link of extractLinks(html)) {
107
+ if (seen.has(link) || isApi(link) || !plan.accepts(link)) continue;
108
+ seen.add(link);
109
+ queue.push({ route: link, named: false });
110
+ }
111
+ }
112
+ return result;
113
+ }
114
+
115
+ // src/vite/build.ts
116
+ function hasPrerenderRules(config) {
117
+ return config.prerender.routes.length > 0 || Object.values(config.routeRules).some((rule) => rule.prerender === true);
118
+ }
119
+ function assertNoServerFetch(root, config, what) {
120
+ const { fetch } = config.doofpi;
121
+ for (const mode of ["lfetch", "pfetch", "sfetch"]) {
122
+ if (!usesFetchMode(fetch, config.routeRules, mode)) continue;
123
+ if (mode === "lfetch" && !existsSync(path2.join(root, "server/doofpi.ts")))
124
+ continue;
125
+ throw new Error(
126
+ `[noofpi] ${what} has no server, so doofpi fetch "${mode}" cannot be used (use "dfetch")`
127
+ );
128
+ }
129
+ }
130
+ async function buildApp(root, resolved, preset = resolved.build.preset, options = {}) {
131
+ const config = { ...resolved, build: { ...resolved.build, preset } };
132
+ const generate = options.generate || preset === "github-pages" && hasPrerenderRules(resolved);
133
+ if (generate) {
134
+ const target = generatePreset(preset, preset);
135
+ if (!config.ssr)
136
+ throw new Error(
137
+ "[noofpi] Prerendering needs server rendering: remove ssr: false from the config"
138
+ );
139
+ assertNoServerFetch(root, config, `The ${target} static build`);
140
+ await generateApp(root, config, target);
141
+ return;
142
+ }
143
+ const isStatic = preset === "github-pages";
144
+ if (isStatic) {
145
+ assertNoServerFetch(root, config, "The github-pages preset");
146
+ config.ssr = false;
147
+ } else if (hasPrerenderRules(resolved)) {
148
+ console.log(
149
+ `
150
+ noofpi: prerender rules are only used by \`noofpi generate\` (the ${preset} preset renders pages when they are requested)`
151
+ );
152
+ }
153
+ const fonts = await resolveFonts(root, config);
154
+ await rm(path2.join(root, OUTPUT_DIR), { recursive: true, force: true });
155
+ console.log(`
156
+ noofpi: building client (preset: ${preset})...`);
157
+ await build(createViteConfig(root, config, "client", fonts));
158
+ if (!isStatic) {
159
+ console.log("\nnoofpi: building server...");
160
+ await build(createViteConfig(root, config, "server", fonts));
161
+ }
162
+ const next = await finishPresetBuild(root, config, preset);
163
+ console.log(`
164
+ noofpi: build complete -> .output/ (${next})
165
+ `);
166
+ }
167
+ async function generateApp(root, config, preset) {
168
+ const outDir = path2.join(root, OUTPUT_DIR);
169
+ const fonts = await resolveFonts(root, config);
170
+ await rm(outDir, { recursive: true, force: true });
171
+ console.log(`
172
+ noofpi: building client (preset: ${preset}, generate)...`);
173
+ await build(createViteConfig(root, config, "client", fonts));
174
+ console.log("\nnoofpi: building the server to prerender with...");
175
+ await build(
176
+ createViteConfig(
177
+ root,
178
+ { ...config, build: { ...config.build, preset: "node" } },
179
+ "server",
180
+ fonts
181
+ )
182
+ );
183
+ const publicDir = path2.join(outDir, "public");
184
+ const template = readFileSync(path2.join(publicDir, "index.html"), "utf-8");
185
+ const next = await finishPresetBuild(root, config, preset, {
186
+ generated: true
187
+ });
188
+ const mod = await import(pathToFileURL(path2.join(outDir, "server/index.mjs")).href);
189
+ console.log("\nnoofpi: prerendering pages...");
190
+ const { written, skipped } = await prerenderPages({
191
+ mod,
192
+ template,
193
+ config,
194
+ pages: Object.keys(scanPages(root, () => true)).map(filePathToRoute),
195
+ publicDir,
196
+ log: console.log
197
+ });
198
+ await rm(path2.join(outDir, "server"), { recursive: true, force: true });
199
+ for (const { route, reason } of skipped)
200
+ console.warn(`noofpi: skipped ${route}: it ${reason}`);
201
+ for (const rule of unsupportedStaticRules(config, preset))
202
+ console.warn(`noofpi: ${preset} cannot apply routeRules ${rule}`);
203
+ console.log(
204
+ `
205
+ noofpi: generated ${written.length} page${written.length === 1 ? "" : "s"} -> .output/public (${next})
206
+ `
207
+ );
208
+ }
209
+ export {
210
+ buildApp,
211
+ hasPrerenderRules
212
+ };
@@ -22,14 +22,15 @@ import {
22
22
  import {
23
23
  HEAD_ATTRS_ATTR,
24
24
  HEAD_TAG_ATTR,
25
+ SESSION_PATH,
25
26
  resolveHead
26
- } from "./chunk-G35DW4NA.js";
27
+ } from "./chunk-PC3ZJN4D.js";
27
28
  import {
28
29
  FETCH_MODES,
29
30
  isServerRendered,
30
31
  resolveFetchMode,
31
32
  usesFetchMode
32
- } from "./chunk-MN5PVHC5.js";
33
+ } from "./chunk-W7ASRDAJ.js";
33
34
 
34
35
  // src/runtime/async-data.ts
35
36
  import {
@@ -281,15 +282,15 @@ function createDoofpiClients(config, rules, ctx) {
281
282
  function createDoofpiClient(config, ctx) {
282
283
  const { server, origin } = ctx;
283
284
  const cookie = server && ctx.cookie ? { headers: { cookie: ctx.cookie } } : void 0;
284
- const track = (fetch) => ctx.log ? recordFetch(
285
- fetch ?? ((input, init) => globalThis.fetch(input, init)),
285
+ const track = (fetch2) => ctx.log ? recordFetch(
286
+ fetch2 ?? ((input, init) => globalThis.fetch(input, init)),
286
287
  ctx.log,
287
288
  {
288
289
  side: server ? "server" : "browser",
289
290
  mode: config.fetch,
290
- transport: fetch && fetch === ctx.fetch ? "in-process" : "http"
291
+ transport: fetch2 && fetch2 === ctx.fetch ? "in-process" : "http"
291
292
  }
292
- ) : fetch;
293
+ ) : fetch2;
293
294
  switch (config.fetch) {
294
295
  case "dfetch":
295
296
  return createClient({
@@ -477,12 +478,7 @@ function collectState(payload) {
477
478
  if (value.value !== void 0) state[key] = value.value;
478
479
  return state;
479
480
  }
480
- function useState(key, init) {
481
- const payload = currentPayload();
482
- if (!payload)
483
- throw new Error(
484
- "[noofpi] useState() must be called while rendering a request or in the browser"
485
- );
481
+ function stateOf(payload, key, init) {
486
482
  const registry = registryOf(payload);
487
483
  let state = registry.get(key);
488
484
  if (!state) {
@@ -493,6 +489,35 @@ function useState(key, init) {
493
489
  if (state.value === void 0 && init) state.value = init();
494
490
  return state;
495
491
  }
492
+ function seedState(payload, key, value) {
493
+ stateOf(payload, key).value = value;
494
+ }
495
+ function useState(key, init) {
496
+ const payload = currentPayload();
497
+ if (!payload)
498
+ throw new Error(
499
+ "[noofpi] useState() must be called while rendering a request or in the browser"
500
+ );
501
+ return stateOf(payload, key, init);
502
+ }
503
+
504
+ // src/runtime/session.ts
505
+ var SESSION_STATE_KEY = "noofpi:session";
506
+ async function refreshSession(state) {
507
+ if (typeof window === "undefined") return;
508
+ const response = await fetch(SESSION_PATH, {
509
+ headers: { accept: "application/json" },
510
+ credentials: "same-origin"
511
+ });
512
+ if (!response.ok)
513
+ throw new Error(`[noofpi] Could not load the session (${response.status})`);
514
+ const body = await response.json();
515
+ state.value = body.data ?? {};
516
+ }
517
+ function useSession() {
518
+ const data = useState(SESSION_STATE_KEY, () => ({}));
519
+ return { data, refresh: () => refreshSession(data) };
520
+ }
496
521
 
497
522
  // src/runtime/cookie.ts
498
523
  import { customRef, inject as inject7 } from "vue";
@@ -738,6 +763,8 @@ function createNoofpiApp(ctx) {
738
763
  ...hydrate ? readPayload() : { data: {}, errors: {} }
739
764
  };
740
765
  app.provide(PAYLOAD_KEY, payload);
766
+ if (ctx.server && ctx.session && Object.keys(ctx.session).length)
767
+ seedState(payload, SESSION_STATE_KEY, ctx.session);
741
768
  const loaders = installLoaders(router, {
742
769
  payload,
743
770
  run: (to, call) => {
@@ -752,6 +779,9 @@ function createNoofpiApp(ctx) {
752
779
  });
753
780
  app.provide(LOADER_KEY, loaders.state);
754
781
  if (!ctx.server) setBrowserState(payload);
782
+ if (!ctx.server && !hydrate && publicConfig.session)
783
+ refreshSession(stateOf(payload, SESSION_STATE_KEY)).catch(() => {
784
+ });
755
785
  if (log && payload.requests) addEntries(log, payload.requests);
756
786
  const error = ref5(payload.error ?? null);
757
787
  app.provide(ERROR_KEY, error);
@@ -799,6 +829,7 @@ export {
799
829
  setServerStateSource,
800
830
  collectState,
801
831
  useState,
832
+ useSession,
802
833
  useCookies,
803
834
  useCookie,
804
835
  defineMessages,
@@ -0,0 +1,51 @@
1
+ // src/server/cache.ts
2
+ var MAX_ENTRIES = 500;
3
+ var PageCache = class {
4
+ entries = /* @__PURE__ */ new Map();
5
+ inflight = /* @__PURE__ */ new Map();
6
+ get(key) {
7
+ return this.entries.get(key);
8
+ }
9
+ set(key, page) {
10
+ this.entries.delete(key);
11
+ this.entries.set(key, page);
12
+ if (this.entries.size > MAX_ENTRIES)
13
+ this.entries.delete(this.entries.keys().next().value);
14
+ }
15
+ clear() {
16
+ this.entries.clear();
17
+ }
18
+ /** Runs `render` for `key` unless one is running already: concurrent requests share its result instead of each rendering */
19
+ share(key, render) {
20
+ let running = this.inflight.get(key);
21
+ if (!running) {
22
+ running = render().finally(() => this.inflight.delete(key));
23
+ this.inflight.set(key, running);
24
+ }
25
+ return running;
26
+ }
27
+ isRendering(key) {
28
+ return this.inflight.has(key);
29
+ }
30
+ };
31
+ function cacheState(page, rule, now) {
32
+ const age = (now - page.storedAt) / 1e3;
33
+ if (age < rule.maxAge) return "fresh";
34
+ return age < rule.maxAge + (rule.swr ?? 0) ? "stale" : "expired";
35
+ }
36
+ function cacheControl(rule) {
37
+ const parts = ["public", `max-age=${rule.maxAge}`];
38
+ if (rule.swr) parts.push(`stale-while-revalidate=${rule.swr}`);
39
+ return parts.join(", ");
40
+ }
41
+ function cacheKey(url, request, vary = []) {
42
+ const headers = vary.map((name) => name.toLowerCase()).sort().map((name) => `${name}=${request.headers.get(name) ?? ""}`);
43
+ return [url.pathname + url.search, ...headers].join("\n");
44
+ }
45
+
46
+ export {
47
+ PageCache,
48
+ cacheState,
49
+ cacheControl,
50
+ cacheKey
51
+ };
@@ -0,0 +1,245 @@
1
+ // src/optional.ts
2
+ async function importOptional(load, packages, feature) {
3
+ try {
4
+ return await load();
5
+ } catch (error) {
6
+ const { code, message } = error ?? {};
7
+ const missing = code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || message?.startsWith("Could not resolve ");
8
+ if (missing && packages.some((name) => message?.includes(name)))
9
+ throw new Error(
10
+ `[noofpi] ${feature} needs ${packages.join(" and ")}: install ${packages.length > 1 ? "them" : "it"} with your package manager (for example \`bun add ${packages.join(" ")}\`)`,
11
+ { cause: error }
12
+ );
13
+ throw error;
14
+ }
15
+ }
16
+
17
+ // src/session.ts
18
+ var SESSION_SECRET_ENV = "NOOFPI_SESSION_SECRET";
19
+ var SESSION_PREVIOUS_SECRETS_ENV = "NOOFPI_SESSION_SECRET_PREVIOUS";
20
+ var DEFAULT_MAX_AGE = 7 * 24 * 60 * 60;
21
+ var MIN_SECRET_LENGTH = 32;
22
+ var COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
23
+ var UNSAFE_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
24
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
25
+ function copyPath(source, target, path) {
26
+ if (Object.hasOwn(source, path)) {
27
+ if (!UNSAFE_SEGMENTS.has(path)) target[path] = source[path];
28
+ return;
29
+ }
30
+ const segments = path.split(".");
31
+ if (segments.length < 2 || segments.some((s) => UNSAFE_SEGMENTS.has(s)))
32
+ return;
33
+ let from = source;
34
+ for (const segment of segments) {
35
+ if (!isPlainObject(from) || !Object.hasOwn(from, segment)) return;
36
+ from = from[segment];
37
+ }
38
+ let to = target;
39
+ for (const segment of segments.slice(0, -1)) {
40
+ const next = Object.hasOwn(to, segment) ? to[segment] : void 0;
41
+ if (isPlainObject(next)) to = next;
42
+ else {
43
+ const created = {};
44
+ to[segment] = created;
45
+ to = created;
46
+ }
47
+ }
48
+ to[segments[segments.length - 1]] = from;
49
+ }
50
+ function resolveSession(input) {
51
+ if (input === void 0 || input === false) return void 0;
52
+ const config = input === true ? {} : input;
53
+ if (typeof config !== "object" || config === null)
54
+ throw new Error("[noofpi] session must be a boolean or an object");
55
+ const name = config.name ?? "noofpi_session";
56
+ if (!COOKIE_NAME.test(name))
57
+ throw new Error(
58
+ `[noofpi] session.name is not a valid cookie name ("${name}")`
59
+ );
60
+ const maxAge = config.maxAge ?? DEFAULT_MAX_AGE;
61
+ if (!Number.isInteger(maxAge) || maxAge <= 0)
62
+ throw new Error(
63
+ `[noofpi] session.maxAge must be a positive number of seconds (got ${String(maxAge)})`
64
+ );
65
+ const mode = config.mode ?? "encrypted";
66
+ if (mode !== "encrypted" && mode !== "signed")
67
+ throw new Error(
68
+ `[noofpi] session.mode must be "encrypted" or "signed" (got "${String(mode)}")`
69
+ );
70
+ const expose = config.expose ?? [];
71
+ if (!Array.isArray(expose) || expose.some((key) => typeof key !== "string"))
72
+ throw new Error(
73
+ "[noofpi] session.expose must be a list of data keys or dot paths"
74
+ );
75
+ const cookie = config.cookie ?? {};
76
+ if (cookie.sameSite !== void 0 && !["lax", "strict", "none"].includes(cookie.sameSite))
77
+ throw new Error(
78
+ `[noofpi] session.cookie.sameSite must be lax, strict or none (got "${String(cookie.sameSite)}")`
79
+ );
80
+ return {
81
+ name,
82
+ maxAge,
83
+ mode,
84
+ expose,
85
+ cookie: {
86
+ sameSite: cookie.sameSite,
87
+ secure: cookie.secure,
88
+ domain: cookie.domain,
89
+ path: cookie.path
90
+ }
91
+ };
92
+ }
93
+ var securegeer;
94
+ function loadSecuregeer() {
95
+ securegeer ??= (async () => {
96
+ const [encryption, hmac] = await importOptional(
97
+ () => Promise.all([
98
+ import("securegeer/encryption"),
99
+ import("securegeer/hmac")
100
+ ]),
101
+ ["securegeer"],
102
+ "session"
103
+ );
104
+ return { encryption, hmac };
105
+ })();
106
+ securegeer.catch(() => securegeer = void 0);
107
+ return securegeer;
108
+ }
109
+ var readEnv = (env, name) => {
110
+ const fromBinding = env?.[name];
111
+ if (typeof fromBinding === "string" && fromBinding) return fromBinding;
112
+ const fromProcess = typeof process !== "undefined" ? process.env?.[name] : void 0;
113
+ return fromProcess || void 0;
114
+ };
115
+ var devSecret;
116
+ async function resolveSessionSecrets(env) {
117
+ const current = readEnv(env, SESSION_SECRET_ENV);
118
+ const previous = (readEnv(env, SESSION_PREVIOUS_SECRETS_ENV) ?? "").split(/[\s,]+/).filter(Boolean);
119
+ const secrets = [...current ? [current] : [], ...previous];
120
+ for (const secret of secrets)
121
+ if (secret.length < MIN_SECRET_LENGTH)
122
+ throw new Error(
123
+ `[noofpi] Session secrets must be at least ${MIN_SECRET_LENGTH} characters (generate one with \`openssl rand -base64 32\`)`
124
+ );
125
+ if (current) return secrets;
126
+ if (typeof process !== "undefined" && process.env?.NODE_ENV === "production")
127
+ throw new Error(
128
+ `[noofpi] Sessions need the ${SESSION_SECRET_ENV} environment variable (at least ${MIN_SECRET_LENGTH} characters, e.g. from \`openssl rand -base64 32\`)`
129
+ );
130
+ if (!devSecret) {
131
+ const { encryption } = await loadSecuregeer();
132
+ if (!devSecret) {
133
+ devSecret = encryption.generateSecret();
134
+ console.warn(
135
+ `[noofpi] ${SESSION_SECRET_ENV} is not set: sessions use a random secret that changes on every restart. Set it in .env.`
136
+ );
137
+ }
138
+ }
139
+ return [devSecret, ...secrets];
140
+ }
141
+ var encoder = new TextEncoder();
142
+ var decoder = new TextDecoder();
143
+ var toBase64Url = (text) => {
144
+ let binary = "";
145
+ for (const byte of encoder.encode(text)) binary += String.fromCharCode(byte);
146
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
147
+ };
148
+ var fromBase64Url = (value) => {
149
+ const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/"));
150
+ return decoder.decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
151
+ };
152
+ var isEnvelope = (value) => typeof value === "object" && value !== null && typeof value.e === "number" && typeof value.d === "object" && value.d !== null && !Array.isArray(value.d);
153
+ async function seal(envelope, mode, secret) {
154
+ const { encryption, hmac } = await loadSecuregeer();
155
+ if (mode === "encrypted") return encryption.encrypt(envelope, secret);
156
+ const payload = toBase64Url(JSON.stringify(envelope));
157
+ return `${payload}.${await hmac.hmacSign(payload, secret)}`;
158
+ }
159
+ async function unseal(value, mode, secrets) {
160
+ const { encryption, hmac } = await loadSecuregeer();
161
+ for (const secret of secrets) {
162
+ try {
163
+ let parsed;
164
+ if (mode === "encrypted")
165
+ parsed = await encryption.decryptJSON(value, secret);
166
+ else {
167
+ const dot = value.lastIndexOf(".");
168
+ const payload = value.slice(0, dot);
169
+ if (dot < 1 || !await hmac.hmacVerify(payload, value.slice(dot + 1), secret))
170
+ continue;
171
+ parsed = JSON.parse(fromBase64Url(payload));
172
+ }
173
+ if (isEnvelope(parsed)) return parsed;
174
+ } catch {
175
+ }
176
+ }
177
+ return void 0;
178
+ }
179
+ async function openSession(options) {
180
+ const { config, cookies } = options;
181
+ const secrets = await options.secrets;
182
+ await loadSecuregeer();
183
+ const now = options.now ?? Date.now();
184
+ const raw = cookies.get(config.name);
185
+ let data = {};
186
+ if (raw) {
187
+ const envelope = await unseal(raw, config.mode, secrets);
188
+ if (envelope && envelope.e > now) data = envelope.d;
189
+ }
190
+ const initial = JSON.stringify(data);
191
+ let cleared = false;
192
+ const session = {
193
+ data,
194
+ update(patch) {
195
+ Object.assign(session.data, patch);
196
+ },
197
+ clear() {
198
+ cleared = true;
199
+ session.data = {};
200
+ },
201
+ get isEmpty() {
202
+ return Object.keys(session.data).length === 0;
203
+ }
204
+ };
205
+ const cookieOptions = {
206
+ ...config.cookie,
207
+ httpOnly: true
208
+ };
209
+ return {
210
+ session,
211
+ async commit() {
212
+ const changed = JSON.stringify(session.data) !== initial;
213
+ if (!changed && !cleared) return;
214
+ if (session.isEmpty) {
215
+ if (raw !== void 0)
216
+ cookies.remove(config.name, {
217
+ path: config.cookie.path,
218
+ domain: config.cookie.domain
219
+ });
220
+ return;
221
+ }
222
+ const value = await seal(
223
+ { d: session.data, e: now + config.maxAge * 1e3 },
224
+ config.mode,
225
+ secrets[0]
226
+ );
227
+ cookies.set(config.name, value, {
228
+ ...cookieOptions,
229
+ maxAge: config.maxAge
230
+ });
231
+ },
232
+ exposed() {
233
+ const visible = {};
234
+ for (const path of config.expose) copyPath(session.data, visible, path);
235
+ return visible;
236
+ }
237
+ };
238
+ }
239
+
240
+ export {
241
+ importOptional,
242
+ resolveSession,
243
+ resolveSessionSecrets,
244
+ openSession
245
+ };
@@ -1,3 +1,9 @@
1
+ // src/server/types.ts
2
+ var PROXY_PREFIX = "/_noofpi/proxy";
3
+ var SESSION_PATH = "/_noofpi/session";
4
+ var SSR_OUTLET = "<!--ssr-outlet-->";
5
+ var isStreamResult = (result) => "body" in result;
6
+
1
7
  // src/head.ts
2
8
  var DEFAULT_TITLE = "noofpi";
3
9
  var HEAD_TAG_ATTR = "data-noofpi-head";
@@ -125,5 +131,9 @@ export {
125
131
  HEAD_TAG_ATTR,
126
132
  HEAD_ATTRS_ATTR,
127
133
  resolveHead,
128
- applyHead
134
+ applyHead,
135
+ PROXY_PREFIX,
136
+ SESSION_PATH,
137
+ SSR_OUTLET,
138
+ isStreamResult
129
139
  };