rosetack 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rosetack",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
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": {
@@ -11,6 +11,14 @@
11
11
  "release:notes": "node tools/release-notes.mjs",
12
12
  "pack": "node pack.mjs",
13
13
  "prepublishOnly": "npm run pack",
14
+ "benchmark": "tsx tests/benchmark.ts",
15
+ "test": "tsx src/cli/index.ts build example && tsx tests/test-client.ts",
16
+ "test:cli": "node tests/test-cli.mjs",
17
+ "test:e2e": "tsx tests/test-e2e.ts",
18
+ "test:edge": "tsx tests/test-edge.ts",
19
+ "test:harness": "tsx tests/test-harness.ts",
20
+ "test:go": "tsx src/cli/index.ts build example && node tests/test-go.mjs",
21
+ "test:pack": "node tests/test-pack.mjs",
14
22
  "build:go": "go build -o rosetack-server ."
15
23
  },
16
24
  "bin": {
@@ -1 +1 @@
1
- 0.1.3
1
+ 0.1.5
@@ -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
@@ -42,7 +42,9 @@ type ServerModule = {
42
42
  setQuery(query: Record<string, string>): void;
43
43
  };
44
44
 
45
- // CSRF: the edge twin of the Node server's guard.
45
+ export { onShutdown, runShutdownHooks, shutdownHookCount } from './shutdown.js';
46
+
47
+ // CSRF guard: a state-changing request that did not come from this site is refused before middleware, hooks and routing see it.
46
48
  function crossSiteWrite(request: Request): Response | null {
47
49
  const m = request.method;
48
50
  if (m !== 'POST' && m !== 'PUT' && m !== 'PATCH' && m !== 'DELETE') return null;
@@ -90,6 +92,7 @@ export async function createEdgeHandler(
90
92
  client = null;
91
93
  }
92
94
  }
95
+ if (client && client.includes('chunks/')) client = null;
93
96
  if (preloaded && 'styles' in preloaded) {
94
97
  styles = preloaded.styles ?? '';
95
98
  } else {
@@ -112,7 +115,8 @@ export async function createEdgeHandler(
112
115
 
113
116
  const pageHeaders = (pathname: string, nonce = ''): Record<string, string> => {
114
117
  const headers: Record<string, string> = {};
115
- if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
118
+ for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
119
+ if (!headers['cache-control']) headers['cache-control'] = 'no-cache';
116
120
  const own = mod.headersFor?.(pathname);
117
121
  if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
118
122
  return headers;
@@ -139,10 +143,18 @@ export async function createEdgeHandler(
139
143
  if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
140
144
  }
141
145
  if (mod.isApi(pathname)) {
146
+ if (request.method !== 'GET') {
147
+ const fn = (mod as any).invalidateRenderCache;
148
+ if (typeof fn === 'function') fn();
149
+ }
142
150
  const apiRes = await mod.handleApi(request.method, pathname, request);
143
151
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
144
152
  }
145
153
  const form = request.method === 'POST' ? await request.formData() : undefined;
154
+ if (form) {
155
+ const fn = (mod as any).invalidateRenderCache;
156
+ if (typeof fn === 'function') fn();
157
+ }
146
158
  if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
147
159
  const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
148
160
  const streamed = new Response(null, {
@@ -165,7 +177,13 @@ export async function createEdgeHandler(
165
177
  });
166
178
  return new Response(stream, { status: head.status, headers: head.headers });
167
179
  }
168
- const page = await mod.renderPage(pathname, form);
180
+ const cookieHeader = request.headers.get('cookie') || '';
181
+ const memoHit = !form && (mod as any).isCachedRoute?.(pathname)
182
+ ? (mod as any).peekRenderCache?.(pathname, cookieHeader)
183
+ : null;
184
+ const page = memoHit ?? ((mod as any).renderPageCached && !form
185
+ ? await (mod as any).renderPageCached(pathname, cookieHeader)
186
+ : await mod.renderPage(pathname, form));
169
187
  const nonce = mod.cspNonce?.(pathname) ? mintNonce() : '';
170
188
  const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
171
189
  const buffered = new Response(html, {
@@ -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
+ }