rosetack 0.0.0 → 0.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 (50) hide show
  1. package/.github/workflows/ci.yml +72 -0
  2. package/.github/workflows/release.yml +122 -0
  3. package/LICENSE +21 -0
  4. package/benchmark.ts +227 -0
  5. package/deploy/Dockerfile.node +25 -0
  6. package/deploy/Dockerfile.static +34 -0
  7. package/deploy/api/rosetack.ts +29 -0
  8. package/deploy/docker-compose.yml +33 -0
  9. package/deploy/fly.toml +28 -0
  10. package/deploy/vercel.json +13 -0
  11. package/example/public/favicon.ico +0 -0
  12. package/example/public/logo.svg +148 -0
  13. package/example/public/rose-mark-black.png +0 -0
  14. package/example/public/rose-mark.png +0 -0
  15. package/example/public/rose-mono.png +0 -0
  16. package/example/rosetack.config.js +10 -0
  17. package/example/src/locales/en.json +8 -0
  18. package/example/src/locales/zh.json +8 -0
  19. package/example/src/pages/404.rose +15 -0
  20. package/example/src/pages/500.rose +10 -0
  21. package/example/src/pages/[lang]/about.rose +40 -0
  22. package/example/src/pages/_layout.rose +33 -0
  23. package/example/src/pages/_middleware.rose +37 -0
  24. package/example/src/pages/about.rose +67 -0
  25. package/example/src/pages/admin.rose +27 -0
  26. package/example/src/pages/api/hello.rose +19 -0
  27. package/example/src/pages/api/login.rose +55 -0
  28. package/example/src/pages/api/posts.rose +80 -0
  29. package/example/src/pages/api/secret.rose +14 -0
  30. package/example/src/pages/blog/[id].rose +25 -0
  31. package/example/src/pages/broken.rose +16 -0
  32. package/example/src/pages/fresh.rose +22 -0
  33. package/example/src/pages/garden.rose +27 -0
  34. package/example/src/pages/index.rose +84 -0
  35. package/example/src/pages/sign.rose +45 -0
  36. package/example/src/pages/thorn.rose +23 -0
  37. package/example/src/pages/vault.rose +14 -0
  38. package/go.mod +3 -0
  39. package/main.go +470 -0
  40. package/package.json +32 -11
  41. package/src/FRAMEWORK_VERSION +1 -0
  42. package/src/cli/edge.ts +127 -0
  43. package/src/cli/index.ts +777 -0
  44. package/src/cli/shell.ts +284 -0
  45. package/src/compiler/index.ts +1990 -0
  46. package/src/runtime/index.ts +624 -0
  47. package/tools/release-notes.mjs +113 -0
  48. package/tsconfig.json +17 -0
  49. package/README.md +0 -3
  50. package/index.js +0 -12
@@ -0,0 +1,284 @@
1
+ /**
2
+ * HTML shell - the document wrapper for every rosetack page.
3
+ *
4
+ * The client bundle is INLINED into the document, so a full page load costs
5
+ * exactly one request: the HTML itself. No other framework in the comparison
6
+ * set (Next.js, SvelteKit, Qwik City, SolidStart) achieves that - they all
7
+ * ship a separate JS bundle, doubling the round-trips before first paint.
8
+ */
9
+
10
+ import * as fs from 'fs';
11
+ import * as path from 'path';
12
+ import * as esbuild from 'esbuild';
13
+ import { createHash } from 'crypto';
14
+
15
+ const OUT_DIR = path.join(process.cwd(), 'dist');
16
+
17
+ let clientCache: { mtimeMs: number; source: string } | null = null;
18
+
19
+ // P0 §1: the bundle mode the last build decided ('inline' | 'split'). In split mode
20
+ // getClientSource() answers null - "nothing to inline" - so every shell caller …
21
+ let splitMode = false;
22
+ export function setBundleMode(mode: string): void {
23
+ splitMode = mode === 'split';
24
+ }
25
+
26
+ /** Read dist/client.js with an mtime-based cache (dev server rebuilds it). */
27
+ export function getClientSource(): string | null {
28
+ if (splitMode) return null; // mode B: the document references /client.js
29
+ const file = path.join(OUT_DIR, 'client.js');
30
+ try {
31
+ const st = fs.statSync(file);
32
+ if (!clientCache || clientCache.mtimeMs !== st.mtimeMs) {
33
+ clientCache = { mtimeMs: st.mtimeMs, source: fs.readFileSync(file, 'utf-8') };
34
+ }
35
+ return clientCache.source;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ let styleCache: { mtimeMs: number; source: string } | null = null;
42
+
43
+ /**
44
+ * Read dist/styles.css (every component's scoped <style>, merged at build
45
+ * time) with an mtime-based cache. '' when the app declares no component
46
+ * styles - the document then carries only the shell's own STYLES.
47
+ */
48
+ export function getStyles(): string {
49
+ const file = path.join(OUT_DIR, 'styles.css');
50
+ try {
51
+ const st = fs.statSync(file);
52
+ if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
53
+ styleCache = { mtimeMs: st.mtimeMs, source: fs.readFileSync(file, 'utf-8') };
54
+ }
55
+ return styleCache.source;
56
+ } catch {
57
+ return '';
58
+ }
59
+ }
60
+
61
+ // Bootstrap appended after the inlined bundle: client-side navigation. Distinct names avoid
62
+ // any collision with minified bundle identifiers.
63
+ const BOOTSTRAP = esbuild.transformSync(`
64
+ const __app = document.getElementById('app');
65
+ // Native View Transitions around client-side navigation (progressive:
66
+ // browsers without the API navigate normally, no polyfill, no CSS required).
67
+ function __navigate(pathname) {
68
+ const paint = () => start(__app, pathname);
69
+ if (document.startViewTransition) {
70
+ return document.startViewTransition(paint).updateCallbackDone;
71
+ }
72
+ return paint();
73
+ }
74
+ window.addEventListener('popstate', () => __navigate(window.location.pathname));
75
+ document.addEventListener('click', (e) => {
76
+ const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
77
+ if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
78
+ e.preventDefault();
79
+ history.pushState(null, '', a.getAttribute('href'));
80
+ __navigate(window.location.pathname);
81
+ }
82
+ });
83
+ // Prefetch the target route's full render (including $data) on hover, keyboard
84
+ // focus, or touch - the click that follows paints from cache: no await, no
85
+ // request. SvelteKit/Qwik prefetch data only; rosetack prefetches the render
86
+ // because the inlined bundle already contains every route.
87
+ function __prefetchHandler(e) {
88
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
89
+ if (a && prefetch) prefetch(a.getAttribute('href'), 'hover');
90
+ }
91
+ document.addEventListener('mouseover', __prefetchHandler);
92
+ document.addEventListener('focusin', __prefetchHandler);
93
+ document.addEventListener('touchstart', __prefetchHandler, { passive: true });
94
+ // Viewport + idle prefetch (Qwik-style): once a link scrolls into view and the
95
+ // browser is idle, its route renders ahead of any interaction. ponytail: both
96
+ // APIs are feature-detected; without them the hover/focus/touch path above
97
+ // still covers every link.
98
+ if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
99
+ const io = new IntersectionObserver((entries) => {
100
+ for (const e of entries) {
101
+ if (!e.isIntersecting) continue;
102
+ io.unobserve(e.target); // one-shot per element; fresh links re-observe after nav
103
+ requestIdleCallback(() => prefetch(e.target.getAttribute('href'), 'viewport'));
104
+ }
105
+ });
106
+ // observing an already-observed element is a no-op, so re-sweeping is cheap
107
+ const observeLinks = () => {
108
+ for (const a of document.querySelectorAll('a[href^="/"]')) io.observe(a);
109
+ };
110
+ observeLinks();
111
+ // navigation swaps the container's innerHTML: re-observe the fresh links
112
+ const __rawNav = __navigate;
113
+ __navigate = (p) => __rawNav(p).then(observeLinks, () => {});
114
+ }
115
+ // Progressive-enhancement forms: <form method="POST"> backed by a server
116
+ // action. With JS the submit is intercepted and handed to postForm (one
117
+ // request, in-place adopt). Without JS the browser performs the native POST
118
+ // and the server re-renders the page: the same form works with JavaScript
119
+ // disabled, which Server Actions in other frameworks do not.
120
+ document.addEventListener('submit', (e) => {
121
+ const f = e.target;
122
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
123
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
124
+ e.preventDefault();
125
+ postForm(new FormData(f));
126
+ });
127
+ // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
128
+ // If the document was rendered for a DIFFERENT route (a static-file server's
129
+ // SPA fallback serves index.html for unknown paths), adopt nothing - let the
130
+ // client router render the requested route from scratch.
131
+ const __st = document.getElementById('__rosetack_state');
132
+ const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
133
+ if (__state.__route === window.location.pathname) {
134
+ start(__app, window.location.pathname, true);
135
+ } else {
136
+ start(__app, window.location.pathname);
137
+ }
138
+ `, { minify: true }).code;
139
+
140
+ // The document inlines its entire runtime, so rosetack can ship a STRICT content security
141
+ // policy without 'unsafe-inline' in script-src …
142
+ let cspCache: { for: string | null; value: string } | null = null;
143
+ // The exact bytes between the external bootstrap's script tags - the single source of truth
144
+ // shared by the tag and the CSP hash …
145
+ const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm } from '/client.js';\n${BOOTSTRAP}`;
146
+ // The exact bytes between the module script's tags - the single source of truth shared by
147
+ // the tag and the CSP hash, so the policy can never drift from what actually ships.
148
+ function inlineScript(client: string): string {
149
+ return `\n${client}\n${BOOTSTRAP}`;
150
+ }
151
+ export function securityHeaders(client: string | null): Record<string, string> {
152
+ if (!cspCache || cspCache.for !== client) {
153
+ // client === null: split mode (or the edge without a built client.js). 'self' covers
154
+ // the external modules and chunks, the hash covers the inline bootstrap …
155
+ const scriptSrc = client
156
+ ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
157
+ : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
158
+ cspCache = {
159
+ for: client,
160
+ value: `script-src ${scriptSrc}; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`,
161
+ };
162
+ }
163
+ return { 'Content-Security-Policy': cspCache.value };
164
+ }
165
+
166
+ // An inline SVG favicon (the rose). Without it every browser requests /favicon.ico on every
167
+ // page load - one wasted request per visit.
168
+ const FAVICON = '<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEWsADn/M2Z/AH8AAADsHmT6IGvnHWLoHWLrHWPpHWLnHGLqHWP/AAD/AFX/AH3qGmX/AP/kHV7qHFyqAFXqJGTbH1/qIGLZF2D1J1jxIGjMAGbfGl3yIGflHF//AD/MM2ZAdgeTAAAAIHRSTlMEBQIA+P5Ob9GQMbEBAwITASoQAxESNxcKTwUxx20EBW1qAJ8AAAHfSURBVHjalVOLbtswDNRGiqRIWYqdV9u9/v8vd7TTAimGDRMSQ5SOx+NDhf6xyv8BlqX/DbDg7xt1+tr7HwCnM9Grqi/jnOY4fQLAFqtNJGlm+cTQx0+awcxTtZkKm5n35QOQu2mVayNVidoU+6Dl9AB02jQazuALEeK2wmLPm4MBwbkxi7A3eIt8V5jcrkCUU78E4GBoxHBt3nhDFGGu7H2UThPgGlHFuUnDz+TO1eFWnRYAXgwACUZ8WyO2aNhUSRkrnVMDAEyIDwUeNsEEURK7TgBOCwDmHoja/JukPmwzMM9+KjQIWdst3FNWU3wAWAGAUuplEHyq3blRqzUhyFlcEMUEmZUutQJxRWaeyhHOlG58OWSgK3koTSWLIWrQcUVKNusPhGYta4phlWtWA6yOQtUKOsl75tJ2QOiWdo171DyvcsnmVjBYPRBO8MwC7Ca7BbKPScU165TqxV/XOO7RL0mGFaVGJdt+CupQnEMA695gjMSgMt7Gr3de8FjT0BSaSzBKYDiT84M51TraediWI1X2iRNLIaa3Fw+uD76qiHBMFIBvc85NDSo0dj0Q8mV8TPU4Hg6UYS7p4gCZP7+LngsvAl3a0p7vV09vczzAYywfxvPj7QvWg/Fx9BsLaBn5YAGOoQAAAABJRU5ErkJggg==">';
169
+
170
+ // Shared by the buffered shell and the streaming shell-open so both produce
171
+ // byte-identical static markup.
172
+ const STYLES = `
173
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
174
+ button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
175
+ a { color: #e91e63; text-decoration: none; font-weight: bold; }
176
+ a:hover { text-decoration: underline; }
177
+ nav a { margin-right: 1rem; }
178
+ .rh { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; border-bottom: 2px solid #e91e63; margin-bottom: 1.5rem; padding-bottom: 0.75rem; }
179
+ .rb { font-size: 1.6rem; }
180
+ .rbrand { display: inline-flex; align-items: center; gap: 0.5em; }
181
+ .rlogo { height: 1em; width: 1em; vertical-align: -0.08em; margin-right: 0.2em; }
182
+ @media (max-width: 640px) {
183
+ .rh { flex-direction: column; align-items: flex-start; gap: 0.75rem; }
184
+ nav a:last-child { margin-right: 0; }
185
+ }
186
+ .rn { display: inline-block; margin-left: 1.5rem; }
187
+ .rf { margin-top: 2rem; color: #888; font-size: 0.85rem; }
188
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
189
+ `;
190
+
191
+ /**
192
+ * Merge the route chain's <head> blocks (document order: page first, then its
193
+ * layouts) into one clean <head> fragment. First occurrence wins per key, so a
194
+ * page overrides its layouts - matching the client's reverse-order applyHead.
195
+ */
196
+ function mergeHeadBlocks(blocks: string[]): string {
197
+ const byKey = new Map<string, string>();
198
+ const order: string[] = [];
199
+ // first occurrence wins: blocks arrive page-first (a page renders inside its
200
+ // layouts' <slot/>), so the page's title/meta override the layouts'
201
+ const put = (key: string, html: string) => {
202
+ if (!byKey.has(key)) {
203
+ byKey.set(key, html);
204
+ order.push(key);
205
+ }
206
+ };
207
+ for (const block of blocks) {
208
+ // title carries content, so it needs its own pattern
209
+ for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put('title', m[0]);
210
+ for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
211
+ const tag = m[1].toLowerCase();
212
+ const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
213
+ const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
214
+ // keyed tags carry their key (must match HEAD_ATTR in the runtime) so the client
215
+ // adopts these SSR-injected elements in place on the first navigation instead of …
216
+ const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
217
+ put(key, marked);
218
+ }
219
+ }
220
+ return order.map((k) => byKey.get(k)!).join('\n ');
221
+ }
222
+
223
+ /** The script tag carrying the inlined bundle (+ bootstrap), or the external fallback. */
224
+ export function clientScriptTag(client: string | null): string {
225
+ return client
226
+ ? `<script type="module">${inlineScript(client)}</script>`
227
+ : `<script type="module" src="/client.js"></script>\n<script type="module">${EXTERNAL_BOOTSTRAP}</script>`;
228
+ }
229
+
230
+ /**
231
+ * The static half of the document for streaming SSR: everything up to (and
232
+ * including) the open `<div id="app">`. No route tags - the route's <head>
233
+ * content is applied by the client at boot from the body's head markers.
234
+ */
235
+ export function shellOpen(styles: string = getStyles()): string {
236
+ const styleTag = styles ? `\n <style>${styles}</style>` : '';
237
+ return `<!DOCTYPE html>
238
+ <html lang="en">
239
+ <head>
240
+ <meta charset="UTF-8">
241
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
242
+ <title>RoseTack</title>
243
+ <style>${STYLES}</style>${styleTag}
244
+ ${FAVICON}
245
+ </head>
246
+ <body>
247
+ <div id="app">`;
248
+ }
249
+
250
+ /** Build the document from an explicit client source (edge runtimes have no fs). */
251
+ export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true): string {
252
+ const clientTag = clientScriptTag(client);
253
+
254
+ const mergedHead = mergeHeadBlocks(head);
255
+ // a route-provided <title> replaces the default one
256
+ const titleTag = /<title>/i.test(mergedHead) ? '' : '<title>RoseTack</title>';
257
+ // a route-provided icon replaces the inline favicon
258
+ const iconTag = /rel=["']?icon/i.test(mergedHead) ? '' : `\n ${FAVICON}`;
259
+ const headTags = mergedHead ? `\n ${mergedHead}` : '';
260
+ const styleTag = styles ? `\n <style>${styles}</style>` : '';
261
+ // js=false (a route exporting csr = false, innovation #25): the document ends at the
262
+ // container - no state script, no inlined bundle, zero JavaScript.
263
+ const jsTail = js
264
+ ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
265
+ : '';
266
+
267
+ return `<!DOCTYPE html>
268
+ <html lang="en">
269
+ <head>
270
+ <meta charset="UTF-8">
271
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
272
+ ${titleTag}
273
+ <style>${STYLES}</style>${styleTag}
274
+ </head>
275
+ <body>
276
+ <div id="app">${ssrHtml}</div>${jsTail}
277
+ </body>
278
+ </html>`;
279
+ }
280
+
281
+ /** Node entry: reads dist/client.js from disk (mtime-cached). */
282
+ export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true): string {
283
+ return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js);
284
+ }