rosetack 0.1.2 → 0.1.4

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 (57) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/netlify/functions/rosetack.ts +38 -0
  4. package/deploy/netlify.toml +17 -0
  5. package/devtools/devtools.html +7 -0
  6. package/devtools/devtools.js +1 -0
  7. package/devtools/manifest.json +8 -0
  8. package/devtools/panel.html +28 -0
  9. package/devtools/panel.js +54 -0
  10. package/dist-cli/compiler.mjs +2194 -561
  11. package/dist-cli/edge.mjs +159 -48
  12. package/dist-cli/rosetack.mjs +2899 -739
  13. package/dist-cli/runtime.mjs +305 -43
  14. package/dist-cli/test.mjs +2332 -630
  15. package/package.json +4 -3
  16. package/src/FRAMEWORK_VERSION +1 -1
  17. package/src/cli/content.ts +186 -0
  18. package/src/cli/edge.ts +78 -62
  19. package/src/cli/image-size.ts +83 -0
  20. package/src/cli/index.ts +391 -334
  21. package/src/cli/prod-server.ts +324 -0
  22. package/src/cli/prompt.ts +51 -20
  23. package/src/cli/shell.ts +105 -74
  24. package/src/cli/test.ts +9 -70
  25. package/src/compiler/index.ts +2107 -913
  26. package/src/runtime/index.ts +367 -168
  27. package/src/types/rosetack.d.ts +16 -66
  28. package/templates/admin/package.json +14 -0
  29. package/templates/admin/rosetack.config.js +1 -0
  30. package/templates/admin/src/pages/_middleware.rose +33 -0
  31. package/templates/admin/src/pages/api/items.rose +37 -0
  32. package/templates/admin/src/pages/api/login.rose +25 -0
  33. package/templates/admin/src/pages/index.rose +79 -0
  34. package/templates/api/package.json +14 -0
  35. package/templates/api/rosetack.config.js +1 -0
  36. package/templates/api/src/pages/api/health.rose +7 -0
  37. package/templates/api/src/pages/api/items.rose +46 -0
  38. package/templates/api/src/pages/api/login.rose +24 -0
  39. package/templates/api/src/pages/index.rose +25 -0
  40. package/templates/blog/package.json +14 -0
  41. package/templates/blog/rosetack.config.js +1 -0
  42. package/templates/blog/src/pages/404.rose +2 -0
  43. package/templates/blog/src/pages/_layout.rose +42 -0
  44. package/templates/blog/src/pages/_middleware.rose +74 -0
  45. package/templates/blog/src/pages/admin.rose +85 -0
  46. package/templates/blog/src/pages/api/login.rose +46 -0
  47. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  48. package/templates/blog/src/pages/api/posts.rose +72 -0
  49. package/templates/blog/src/pages/index.rose +31 -0
  50. package/templates/blog/src/pages/post/[id].rose +36 -0
  51. package/templates/site/package.json +14 -0
  52. package/templates/site/rosetack.config.js +1 -0
  53. package/templates/site/src/pages/404.rose +2 -0
  54. package/templates/site/src/pages/_layout.rose +40 -0
  55. package/templates/site/src/pages/about.rose +6 -0
  56. package/templates/site/src/pages/index.rose +13 -0
  57. package/templates/site/src/pages/pricing.rose +8 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rosetack",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Zero-hydration full-stack web framework with compile-time reactivity and zero-JS content routes.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -26,9 +26,9 @@
26
26
  "dist-cli",
27
27
  "src",
28
28
  "deploy",
29
+ "templates",
30
+ "devtools",
29
31
  "pack.mjs",
30
- "README.md",
31
- "VERSIONING.md",
32
32
  "LICENSE"
33
33
  ],
34
34
  "license": "MIT",
@@ -41,6 +41,7 @@
41
41
  "devDependencies": {
42
42
  "@types/node": "^22.0.0",
43
43
  "jsdom": "^29.1.1",
44
+ "pg": "^8.23.0",
44
45
  "tsx": "^4.7.0",
45
46
  "typescript": "^5.6.0"
46
47
  },
@@ -1 +1 @@
1
- 0.1.2
1
+ 0.1.4
@@ -0,0 +1,186 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export interface ContentEntry {
5
+ slug: string;
6
+ frontmatter: Record<string, string | string[]>;
7
+ /** markdown source, unrendered (the page renders it, highlight applies) */
8
+ body: string;
9
+ /** rendered html with heading anchors (T20-free: ids for TOC deep links) */
10
+ html: string;
11
+ readingTime: number;
12
+ wordCount: number;
13
+ toc: { level: number; text: string; id: string }[];
14
+ excerpt: string;
15
+ }
16
+
17
+ /** Parse `---`-delimited frontmatter: `key: value` lines, `[a, b]` arrays. */
18
+ export function parseFrontmatter(raw: string): {
19
+ frontmatter: Record<string, string | string[]>;
20
+ body: string;
21
+ } {
22
+ if (!raw.startsWith("---")) return { frontmatter: {}, body: raw };
23
+ const end = raw.indexOf("\n---", 3);
24
+ if (end < 0) return { frontmatter: {}, body: raw };
25
+ const head = raw.slice(4, end);
26
+ const body = raw.slice(raw.indexOf("\n", end + 1) + 1).replace(/^\s*\n/, "");
27
+ const frontmatter: Record<string, string | string[]> = {};
28
+ for (const line of head.split("\n")) {
29
+ const m = /^(\w[\w-]*):\s*(.*)$/.exec(line.trim());
30
+ if (!m) continue;
31
+ const [, k, v] = m;
32
+ const arr = /^\[(.+)\]$/.exec(v.trim());
33
+ frontmatter[k] = arr
34
+ ? arr[1].split(",").map((x) => x.trim().replace(/^["']|["']$/g, ""))
35
+ : v.trim().replace(/^["']|["']$/g, "");
36
+ }
37
+ return { frontmatter, body };
38
+ }
39
+
40
+ /** Mini-markdown → HTML: headings, fenced code, lists, bold/italic/code,
41
+ * links, paragraphs. Zero dependencies; ~100 lines cover the blog 90%. */
42
+ function interpolate(md: string, vars: Record<string, unknown>): string {
43
+ return md.replace(/{{(\w[\w.]*)}}/g, (_m, k) => {
44
+ const v = k.split(".").reduce((o: any, p) => (o == null ? o : o[p]), vars as any);
45
+ return v === undefined || v === null ? "" : String(v);
46
+ });
47
+ }
48
+
49
+ export function renderMarkdown(md: string, vars?: Record<string, unknown>): string {
50
+ if (vars) md = interpolate(md, vars);
51
+ const blocks: string[] = [];
52
+ let src = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, lang, code) => {
53
+ blocks.push(
54
+ `<pre data-lang="${lang}"><code>${code
55
+ .replace(/&/g, "&amp;")
56
+ .replace(/</g, "&lt;")
57
+ .replace(/>/g, "&gt;")}</code></pre>`,
58
+ );
59
+ return `\u0000CODE${blocks.length - 1}\u0000`;
60
+ });
61
+
62
+ const inline = (s: string) =>
63
+ s
64
+ .replace(/&/g, "&amp;")
65
+ .replace(/</g, "&lt;")
66
+ .replace(/>/g, "&gt;")
67
+ .replace(/`([^`]+)`/g, "<code>$1</code>")
68
+ .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
69
+ .replace(/\*([^*]+)\*/g, "<em>$1</em>")
70
+ .replace(
71
+ /\[([^\]]+)\]\(([^)]+)\)/g,
72
+ '<a href="$2" rel="noopener">$1</a>',
73
+ );
74
+
75
+ const out: string[] = [];
76
+ let listOpen: "ul" | "ol" | null = null;
77
+ const closeList = () => {
78
+ if (listOpen) { out.push(`</${listOpen}>`); listOpen = null; }
79
+ };
80
+ for (const line of src.split("\n")) {
81
+ const h = /^(#{1,4})\s+(.*)$/.exec(line);
82
+ const li = /^\s*[-*]\s+(.*)$/.exec(line);
83
+ const oli = /^\s*\d+\.\s+(.*)$/.exec(line);
84
+ if (h) { closeList(); out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`); }
85
+ else if (li) {
86
+ if (listOpen !== "ul") { closeList(); out.push("<ul>"); listOpen = "ul"; }
87
+ out.push(`<li>${inline(li[1])}</li>`);
88
+ } else if (oli) {
89
+ if (listOpen !== "ol") { closeList(); out.push("<ol>"); listOpen = "ol"; }
90
+ out.push(`<li>${inline(oli[1])}</li>`);
91
+ } else if (line.trim() === "") { closeList(); }
92
+ else if (line.startsWith("\u0000CODE")) { closeList(); out.push(line); }
93
+ else { closeList(); out.push(`<p>${inline(line)}</p>`); }
94
+ }
95
+ closeList();
96
+ return out
97
+ .join("\n")
98
+ .replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => blocks[Number(i)]);
99
+ }
100
+
101
+ /** Scan src/content/<collection>/*.md into entries (slug = filename). */
102
+ export function scanContentDir(contentDir: string): Record<string, ContentEntry[]> {
103
+ const collections: Record<string, ContentEntry[]> = {};
104
+ if (!fs.existsSync(contentDir)) return collections;
105
+ for (const coll of fs.readdirSync(contentDir, { withFileTypes: true })) {
106
+ if (!coll.isDirectory()) continue;
107
+ const entries: ContentEntry[] = [];
108
+ const dir = path.join(contentDir, coll.name);
109
+ for (const f of fs.readdirSync(dir)) {
110
+ if (!f.endsWith(".md")) continue;
111
+ const raw = fs.readFileSync(path.join(dir, f), "utf-8");
112
+ const { frontmatter, body } = parseFrontmatter(raw);
113
+ if (String(frontmatter.draft ?? "").toLowerCase() === "true") continue;
114
+ const slug = f.replace(/\.md$/, "");
115
+ const html = renderMarkdown(body);
116
+ const words = body.replace(/[#*`\[\]()>-]/g, " ").split(/\s+/).filter(Boolean).length;
117
+ const headings: { level: number; text: string; id: string }[] = [];
118
+ const tocHtml = html.replace(/<h([1-4])>([^<]+)<\/h\1>/g, (_m, lvl: string, txt: string) => {
119
+ const id = txt.toLowerCase().replace(/[^\w\s-]/g, "").trim().replace(/\s+/g, "-");
120
+ headings.push({ level: Number(lvl), text: txt, id });
121
+ return `<h${lvl} id="${id}">${txt}</h${lvl}>`;
122
+ });
123
+ entries.push({
124
+ slug, frontmatter,
125
+ body, html: tocHtml,
126
+ readingTime: Math.max(1, Math.round(words / 200)),
127
+ wordCount: words,
128
+ toc: headings,
129
+ excerpt: String(frontmatter.summary ?? "") || (html.match(/<p>([\s\S]*?)<\/p>/)?.[1] ?? "").replace(/<[^>]+>/g, "").slice(0, 160),
130
+ });
131
+ }
132
+ entries.sort((a, b) =>
133
+ String(b.frontmatter.date ?? "").localeCompare(String(a.frontmatter.date ?? "")),
134
+ );
135
+ collections[coll.name] = entries;
136
+ }
137
+ return collections;
138
+ }
139
+
140
+ /** Prev/next navigation within a collection (date-descending order). */
141
+ export function prevNext(
142
+ entries: ContentEntry[],
143
+ slug: string,
144
+ ): { prev: ContentEntry | null; next: ContentEntry | null } {
145
+ const i = entries.findIndex((e) => e.slug === slug);
146
+ return { prev: i > 0 ? entries[i - 1] : null, next: i >= 0 && i < entries.length - 1 ? entries[i + 1] : null };
147
+ }
148
+
149
+ /** Group a collection by a frontmatter array field (tags/categories). */
150
+ export function byTag(
151
+ entries: ContentEntry[],
152
+ field: string,
153
+ ): Record<string, ContentEntry[]> {
154
+ const out: Record<string, ContentEntry[]> = {};
155
+ for (const e of entries) {
156
+ for (const t of (e.frontmatter[field] as string[] | undefined) ?? []) {
157
+ (out[t] ??= []).push(e);
158
+ }
159
+ }
160
+ return out;
161
+ }
162
+
163
+ globalThis.__rosetackContentMk = renderMarkdown;
164
+
165
+ /** RSS 2.0 feed from a collection - wire to /feed.xml or /api/feed. */
166
+ export function buildRss(
167
+ entries: ContentEntry[],
168
+ opts: { title: string; origin: string; description?: string; pathPrefix?: string },
169
+ ): string {
170
+ const esc = (v: unknown) =>
171
+ String(v ?? "")
172
+ .replace(/&/g, "&amp;")
173
+ .replace(/</g, "&lt;")
174
+ .replace(/>/g, "&gt;")
175
+ .replace(/"/g, "&quot;");
176
+ const prefix = opts.pathPrefix ?? "/";
177
+ const items = entries
178
+ .map((e) => {
179
+ const url = `${opts.origin}${prefix}${e.slug}`;
180
+ const pub = e.frontmatter.date ? new Date(String(e.frontmatter.date)).toUTCString() : "";
181
+ const excerpt = e.excerpt ? `<description>${esc(e.excerpt)}</description>` : "";
182
+ return ` <item>\n <title>${esc(e.frontmatter.title)}</title>\n <link>${esc(url)}</link>\n <guid isPermaLink="true">${esc(url)}</guid>\n ${pub ? `<pubDate>${pub}</pubDate>\n ` : ""}${excerpt}\n </item>`;
183
+ })
184
+ .join("\n");
185
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0"><channel>\n<title>${esc(opts.title)}</title>\n<link>${esc(opts.origin)}${prefix}</link>\n<description>${esc(opts.description ?? "")}</description>\n${items}\n</channel></rss>`;
186
+ }
package/src/cli/edge.ts CHANGED
@@ -1,31 +1,16 @@
1
- /**
2
- * rosetack Edge adapter - Web-standard fetch handler.
3
- *
4
- * Works on any edge runtime that supports the Fetch API standard
5
- * (Cloudflare Workers, Deno Deploy, Vercel Edge, Bun, Node 18+):
6
- *
7
- * import { createEdgeHandler } from 'rosetack/edge';
8
- * const handle = createEdgeHandler('./dist');
9
- * export default { fetch: handle };
10
- *
11
- * The generated dist/server.js has zero Node built-in imports, so the same
12
- * bundle that runs the Node server runs at the edge. Static routes can be
13
- * served by the platform's asset layer; everything else renders on demand.
14
- * GETs to known routes stream (the static shell flushes before the render
15
- * completes, still one request); routes known-broken at build time
16
- * (dist/broken.json) stay buffered so their real 500 status survives, and
17
- * csr = false routes buffer so their document is complete without a client.
18
- */
1
+ // rosetack Edge adapter - Web-standard fetch handler.
19
2
 
20
3
  import { pathToFileURL } from 'url';
21
4
  import { join } from 'path';
22
5
  import { buildShell, shellOpen, clientScriptTag, securityHeaders, mintNonce } from './shell.js';
23
6
 
24
7
  type ServerModule = {
25
- renderPage(pathname: string, form?: FormData): Promise<{ html: string; state: string; head: string[]; status?: number; csr?: boolean; lang?: string; dir?: string }>;
8
+ renderPage(pathname: string, form?: FormData): Promise<{ html: string; state: string; head: string[]; status?: number; csr?: boolean; shell?: boolean; lang?: string; dir?: string }>;
26
9
  renderPageStream(pathname: string, write: (chunk: string) => void, shellOpen: string, clientTag: string): Promise<number>;
27
10
  canStream(pathname: string): boolean;
28
11
  isNoJs(pathname: string): boolean;
12
+ /** the matched route exported `shell = false` - the streaming shell must ask before it flushes */
13
+ shellOff?(pathname: string): boolean;
29
14
  /** P0-2: routes that exported `buffer = true` - buffered, never streamed */
30
15
  isBuffered(pathname: string): boolean;
31
16
  isApi(pathname: string): boolean;
@@ -57,33 +42,75 @@ type ServerModule = {
57
42
  setQuery(query: Record<string, string>): void;
58
43
  };
59
44
 
45
+ // CSRF: the edge twin of the Node server's guard.
46
+ function crossSiteWrite(request: Request): Response | null {
47
+ const m = request.method;
48
+ if (m !== 'POST' && m !== 'PUT' && m !== 'PATCH' && m !== 'DELETE') return null;
49
+ const origin = request.headers.get('origin');
50
+ if (origin) {
51
+ let host: string;
52
+ try {
53
+ host = new URL(origin).host;
54
+ } catch {
55
+ return new Response('Cross-site request blocked (unparsable Origin header)', { status: 403 });
56
+ }
57
+ return host === new URL(request.url).host
58
+ ? null
59
+ : new Response('Cross-site request blocked (Origin does not match Host)', { status: 403 });
60
+ }
61
+ const site = request.headers.get('sec-fetch-site');
62
+ if (site && site !== 'same-origin' && site !== 'same-site' && site !== 'none') {
63
+ return new Response(`Cross-site request blocked (sec-fetch-site: ${site})`, { status: 403 });
64
+ }
65
+ return null;
66
+ }
67
+
60
68
  /**
61
69
  * Create a fetch handler from a built rosetack project.
62
70
  * @param outDir directory containing server.js and client.js
71
+ * @param preloaded for runtimes with NO filesystem (Cloudflare Workers /
72
+ * Pages): the caller statically imports the server bundle (so the deploy
73
+ * compiler bundles it in) and fetches the site's own static assets once
74
+ * per isolate. Anything provided here is used verbatim; anything absent
75
+ * falls back to reading it from outDir, exactly as before.
63
76
  */
64
- export async function createEdgeHandler(outDir: string): Promise<(request: Request) => Promise<Response>> {
65
- const mod: ServerModule = await import(pathToFileURL(join(outDir, 'server.js')).href);
77
+ export async function createEdgeHandler(
78
+ outDir: string,
79
+ preloaded?: { server?: ServerModule; client?: string; styles?: string; broken?: string[] },
80
+ ): Promise<(request: Request) => Promise<Response>> {
81
+ const mod: ServerModule = preloaded?.server ?? await import(pathToFileURL(join(outDir, 'server.js')).href);
66
82
  let client: string | null = null;
67
83
  let styles = '';
68
- try {
69
- client = await (await import('fs/promises')).readFile(join(outDir, 'client.js'), 'utf-8');
70
- } catch {
71
- client = null; // no fs (Workers): platform should inline the bundle at deploy time
84
+ if (preloaded && 'client' in preloaded) {
85
+ client = preloaded.client ?? null;
86
+ } else {
87
+ try {
88
+ client = await (await import('fs/promises')).readFile(join(outDir, 'client.js'), 'utf-8');
89
+ } catch {
90
+ client = null;
91
+ }
72
92
  }
73
- try {
74
- styles = await (await import('fs/promises')).readFile(join(outDir, 'styles.css'), 'utf-8');
75
- } catch {
76
- styles = ''; // no component styles (or no fs): shell STYLES only
93
+ if (client && client.includes('chunks/')) client = null;
94
+ if (preloaded && 'styles' in preloaded) {
95
+ styles = preloaded.styles ?? '';
96
+ } else {
97
+ try {
98
+ styles = await (await import('fs/promises')).readFile(join(outDir, 'styles.css'), 'utf-8');
99
+ } catch {
100
+ styles = '';
101
+ }
77
102
  }
78
- // routes whose render failed at build time: buffered, so the 500 survives
79
103
  let broken = new Set<string>();
80
- try {
81
- broken = new Set(JSON.parse(await (await import('fs/promises')).readFile(join(outDir, 'broken.json'), 'utf-8')));
82
- } catch {
83
- broken = new Set(); // no manifest: nothing known-broken
104
+ if (preloaded && 'broken' in preloaded) {
105
+ broken = new Set(preloaded.broken);
106
+ } else {
107
+ try {
108
+ broken = new Set(JSON.parse(await (await import('fs/promises')).readFile(join(outDir, 'broken.json'), 'utf-8')));
109
+ } catch {
110
+ broken = new Set();
111
+ }
84
112
  }
85
113
 
86
- // Response headers for a page document: the strict CSP hashed over the exact inlined bytes …
87
114
  const pageHeaders = (pathname: string, nonce = ''): Record<string, string> => {
88
115
  const headers: Record<string, string> = {};
89
116
  if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
@@ -93,12 +120,14 @@ export async function createEdgeHandler(outDir: string): Promise<(request: Reque
93
120
  };
94
121
 
95
122
  return async function handle(request: Request): Promise<Response> {
123
+ const refused = crossSiteWrite(request);
124
+ if (refused) return refused;
96
125
  const { pathname, searchParams } = new URL(request.url);
97
- // P0-1: the query reaches the render through $query() - routing itself
98
- // matches the pathname, exactly as the Node server does.
126
+ const canonical = pathname.replace(/\/+$/, '') || '/';
127
+ if (canonical !== pathname) {
128
+ return new Response(null, { status: 308, headers: { location: canonical + new URL(request.url).search } });
129
+ }
99
130
  mod.setQuery?.(Object.fromEntries(searchParams));
100
- // Runtime hooks: onRequest runs before middleware and routing and may short-circuit with
101
- // its own Response - an auth wall, a rate limit.
102
131
  const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks
103
132
  ? { request, url: new URL(request.url), method: request.method, pathname, state: {} as Record<string, unknown> }
104
133
  : null;
@@ -106,28 +135,18 @@ export async function createEdgeHandler(outDir: string): Promise<(request: Reque
106
135
  const short = await mod.runRequestHooks(hookCtx);
107
136
  if (short) return mod.runResponseHooks(hookCtx, short);
108
137
  }
109
- // Middleware (pages/_middleware.rose) runs exactly once per request, before anything
110
- // else: a returned Response short-circuits the whole request (a redirect, an auth wall) …
111
138
  if (mod.middleware) {
112
139
  const mw = await mod.runMiddleware(request);
113
140
  if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
114
141
  }
115
- // API routes (pages/api/*.rose): the /api namespace answers JSON, never the HTML shell …
116
142
  if (mod.isApi(pathname)) {
117
143
  const apiRes = await mod.handleApi(request.method, pathname, request);
118
144
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
119
145
  }
120
- // POST: progressive-enhancement form - run the route's server action with
121
- // the submitted FormData and re-render the page (works without JS).
122
146
  const form = request.method === 'POST' ? await request.formData() : undefined;
123
- // csr = false routes buffer too: a streamed no-JS document would carry the shell's default
124
- // <title> - the route head is applied client-side at boot, and there is no client.
147
+ if (form) (mod as any).invalidateRenderCache?.();
125
148
  if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
126
- // The nonce is minted before the Response exists, because its headers are fixed from then
127
- // on - and the document's script tag is written into that same stream …
128
149
  const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
129
- // streaming GET: one chunked Response, still exactly one request. onResponse runs
130
- // before the stream is created, while the status and headers can still change …
131
150
  const streamed = new Response(null, {
132
151
  status: 200,
133
152
  headers: { 'content-type': 'text/html; charset=utf-8', ...pageHeaders(pathname, nonce) }
@@ -136,13 +155,11 @@ export async function createEdgeHandler(outDir: string): Promise<(request: Reque
136
155
  const encoder = new TextEncoder();
137
156
  const stream = new ReadableStream<Uint8Array>({
138
157
  async start(controller) {
139
- // The shell opens before the render, so its <html lang>/<dir>
140
- // come from the pathname (the server bundle's docAttrs)
141
158
  const doc = mod.docAttrs(pathname);
142
159
  await mod.renderPageStream(
143
160
  pathname,
144
161
  (chunk) => controller.enqueue(encoder.encode(chunk)),
145
- shellOpen(styles, doc.lang, doc.dir),
162
+ shellOpen(styles, doc.lang, doc.dir, !mod.shellOff?.(pathname)),
146
163
  clientScriptTag(client, nonce)
147
164
  );
148
165
  controller.close();
@@ -150,16 +167,15 @@ export async function createEdgeHandler(outDir: string): Promise<(request: Reque
150
167
  });
151
168
  return new Response(stream, { status: head.status, headers: head.headers });
152
169
  }
153
- // buffered: POST actions, unmatched routes (404), known-broken routes (500).
154
- // The middleware already ran at the top of this handler, so the render
155
- // below sees its context.
156
- const page = await mod.renderPage(pathname, form);
157
- // '' for every hashed route, so the document is byte-identical to
158
- // what it was before nonce mode existed.
170
+ const cookieHeader = request.headers.get('cookie') || '';
171
+ const memoHit = !form && (mod as any).isCachedRoute?.(pathname)
172
+ ? (mod as any).peekRenderCache?.(pathname, cookieHeader)
173
+ : null;
174
+ const page = memoHit ?? ((mod as any).renderPageCached && !form
175
+ ? await (mod as any).renderPageCached(pathname, cookieHeader)
176
+ : await mod.renderPage(pathname, form));
159
177
  const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
160
- // js = page.csr !== false: a csr = false route ships no bundle, no state script - the
161
- // document is HTML + CSS only .
162
- const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce);
178
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
163
179
  const buffered = new Response(html, {
164
180
  status: page.status ?? 200,
165
181
  headers: { 'content-type': 'text/html; charset=utf-8', ...pageHeaders(pathname, nonce) }
@@ -0,0 +1,83 @@
1
+ import fs from "node:fs";
2
+
3
+ export interface ImageDims {
4
+ width: number;
5
+ height: number;
6
+ }
7
+
8
+ /** Parse dimensions from the leading bytes of an image file. */
9
+ export function readImageSize(filePath: string): ImageDims | null {
10
+ try {
11
+ const fd = fs.openSync(filePath, "r");
12
+ const buf = Buffer.alloc(64);
13
+ const read = fs.readSync(fd, buf, 0, 64, 0);
14
+ fs.closeSync(fd);
15
+ if (read < 24) return null;
16
+
17
+ if (
18
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47
19
+ ) {
20
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
21
+ }
22
+
23
+ if (buf.slice(0, 3).toString("latin1") === "GIF") {
24
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
25
+ }
26
+
27
+ if (
28
+ buf.slice(0, 4).toString("latin1") === "RIFF" &&
29
+ buf.slice(8, 12).toString("latin1") === "WEBP"
30
+ ) {
31
+ return parseWebP(buf);
32
+ }
33
+
34
+ if (buf[0] === 0xff && buf[1] === 0xd8) {
35
+ return parseJpeg(filePath);
36
+ }
37
+
38
+ return null;
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ function parseWebP(buf: Buffer): ImageDims | null {
45
+ const format = buf.slice(12, 16).toString("latin1");
46
+ if (format === "VP8 ") {
47
+ return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
48
+ }
49
+ if (format === "VP8L") {
50
+ const b = buf.readUInt32LE(21);
51
+ return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 };
52
+ }
53
+ if (format === "VP8X") {
54
+ const w = buf.readUIntLE(24, 3) + 1;
55
+ const h = buf.readUIntLE(27, 3) + 1;
56
+ return { width: w, height: h };
57
+ }
58
+ return null;
59
+ }
60
+
61
+ function parseJpeg(filePath: string): ImageDims | null {
62
+ const fd = fs.openSync(filePath, "r");
63
+ try {
64
+ const buf = Buffer.alloc(4);
65
+ let pos = 2;
66
+ for (let guard = 0; guard < 64; guard++) {
67
+ if (fs.readSync(fd, buf, 0, 4, pos) < 4) return null;
68
+ if (buf[0] !== 0xff) { pos += 1; continue; }
69
+ const marker = buf[1];
70
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { pos += 2; continue; }
71
+ const len = fs.readSync(fd, buf, 0, 2, pos + 2) < 2 ? 0 : buf.readUInt16BE(2);
72
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
73
+ const seg = Buffer.alloc(8);
74
+ fs.readSync(fd, seg, 0, 8, pos + 4);
75
+ return { width: seg.readUInt16BE(3), height: seg.readUInt16BE(1) };
76
+ }
77
+ pos += 2 + len;
78
+ }
79
+ return null;
80
+ } finally {
81
+ fs.closeSync(fd);
82
+ }
83
+ }