rosetack 0.1.0 → 0.1.1

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 (49) hide show
  1. package/dist-cli/compiler.mjs +2302 -0
  2. package/dist-cli/edge.mjs +297 -0
  3. package/dist-cli/rosetack.mjs +3411 -0
  4. package/dist-cli/runtime.mjs +619 -0
  5. package/dist-cli/test.mjs +2696 -0
  6. package/pack.mjs +49 -0
  7. package/package.json +25 -7
  8. package/src/FRAMEWORK_VERSION +1 -1
  9. package/src/cli/edge.ts +58 -23
  10. package/src/cli/index.ts +521 -65
  11. package/src/cli/shell.ts +75 -22
  12. package/src/cli/test.ts +400 -0
  13. package/src/compiler/index.ts +1277 -191
  14. package/src/runtime/index.ts +356 -65
  15. package/src/types/rosetack.d.ts +142 -0
  16. package/.github/workflows/ci.yml +0 -72
  17. package/.github/workflows/release.yml +0 -122
  18. package/benchmark.ts +0 -227
  19. package/example/public/favicon.ico +0 -0
  20. package/example/public/logo.svg +0 -148
  21. package/example/public/rose-mark-black.png +0 -0
  22. package/example/public/rose-mark.png +0 -0
  23. package/example/public/rose-mono.png +0 -0
  24. package/example/rosetack.config.js +0 -10
  25. package/example/src/locales/en.json +0 -8
  26. package/example/src/locales/zh.json +0 -8
  27. package/example/src/pages/404.rose +0 -15
  28. package/example/src/pages/500.rose +0 -10
  29. package/example/src/pages/[lang]/about.rose +0 -40
  30. package/example/src/pages/_layout.rose +0 -33
  31. package/example/src/pages/_middleware.rose +0 -37
  32. package/example/src/pages/about.rose +0 -67
  33. package/example/src/pages/admin.rose +0 -27
  34. package/example/src/pages/api/hello.rose +0 -19
  35. package/example/src/pages/api/login.rose +0 -55
  36. package/example/src/pages/api/posts.rose +0 -80
  37. package/example/src/pages/api/secret.rose +0 -14
  38. package/example/src/pages/blog/[id].rose +0 -25
  39. package/example/src/pages/broken.rose +0 -16
  40. package/example/src/pages/fresh.rose +0 -22
  41. package/example/src/pages/garden.rose +0 -27
  42. package/example/src/pages/index.rose +0 -84
  43. package/example/src/pages/sign.rose +0 -45
  44. package/example/src/pages/thorn.rose +0 -23
  45. package/example/src/pages/vault.rose +0 -14
  46. package/go.mod +0 -3
  47. package/main.go +0 -470
  48. package/tools/release-notes.mjs +0 -113
  49. package/tsconfig.json +0 -17
@@ -0,0 +1,297 @@
1
+ // src/cli/edge.ts
2
+ import { pathToFileURL } from "url";
3
+ import { join as join2 } from "path";
4
+
5
+ // src/cli/shell.ts
6
+ import * as fs from "fs";
7
+ import * as path from "path";
8
+ import * as esbuild from "esbuild";
9
+ import { createHash } from "crypto";
10
+ var OUT_DIR = path.join(process.cwd(), "dist");
11
+ var styleCache = null;
12
+ function getStyles() {
13
+ const file = path.join(OUT_DIR, "styles.css");
14
+ try {
15
+ const st = fs.statSync(file);
16
+ if (!styleCache || styleCache.mtimeMs !== st.mtimeMs) {
17
+ styleCache = { mtimeMs: st.mtimeMs, source: fs.readFileSync(file, "utf-8") };
18
+ }
19
+ return styleCache.source;
20
+ } catch {
21
+ return "";
22
+ }
23
+ }
24
+ var BOOTSTRAP = esbuild.transformSync(`
25
+ const __app = document.getElementById('app');
26
+ // Native View Transitions around client-side navigation (progressive:
27
+ // browsers without the API navigate normally, no polyfill, no CSS required).
28
+ function __navigate(pathname) {
29
+ const paint = () => start(__app, pathname);
30
+ if (document.startViewTransition) {
31
+ return document.startViewTransition(paint).updateCallbackDone;
32
+ }
33
+ return paint();
34
+ }
35
+ window.addEventListener('popstate', () => __navigate(window.location.pathname));
36
+ document.addEventListener('click', (e) => {
37
+ const a = e.target.tagName === 'A' ? e.target : e.target.closest && e.target.closest('a');
38
+ if (a && a.getAttribute('href') && a.getAttribute('href').startsWith('/')) {
39
+ e.preventDefault();
40
+ history.pushState(null, '', a.getAttribute('href'));
41
+ __navigate(window.location.pathname);
42
+ }
43
+ });
44
+ // Prefetch the target route's full render (including $data) on hover, keyboard
45
+ // focus, or touch - the click that follows paints from cache: no await, no
46
+ // request. Other frameworks prefetch data only; rosetack prefetches the render
47
+ // because the inlined bundle already contains every route.
48
+ function __prefetchHandler(e) {
49
+ const a = e.target.closest && e.target.closest('a[href^="/"]');
50
+ if (a && prefetch) prefetch(a.getAttribute('href'), 'hover');
51
+ }
52
+ document.addEventListener('mouseover', __prefetchHandler);
53
+ document.addEventListener('focusin', __prefetchHandler);
54
+ document.addEventListener('touchstart', __prefetchHandler, { passive: true });
55
+ // Viewport + idle prefetch (viewport-triggered): once a link scrolls into view and the
56
+ // browser is idle, its route renders ahead of any interaction. trade-off: both
57
+ // APIs are feature-detected; without them the hover/focus/touch path above
58
+ // still covers every link.
59
+ if (prefetch && 'IntersectionObserver' in window && 'requestIdleCallback' in window) {
60
+ const io = new IntersectionObserver((entries) => {
61
+ for (const e of entries) {
62
+ if (!e.isIntersecting) continue;
63
+ io.unobserve(e.target); // one-shot per element; fresh links re-observe after nav
64
+ requestIdleCallback(() => prefetch(e.target.getAttribute('href'), 'viewport'));
65
+ }
66
+ });
67
+ // observing an already-observed element is a no-op, so re-sweeping is cheap
68
+ const observeLinks = () => {
69
+ for (const a of document.querySelectorAll('a[href^="/"]')) io.observe(a);
70
+ };
71
+ observeLinks();
72
+ // navigation swaps the container's innerHTML: re-observe the fresh links
73
+ const __rawNav = __navigate;
74
+ __navigate = (p) => __rawNav(p).then(observeLinks, () => {});
75
+ }
76
+ // Progressive-enhancement forms: <form method="POST"> backed by a server
77
+ // action. With JS the submit is intercepted and handed to postForm (one
78
+ // request, in-place adopt). Without JS the browser performs the native POST
79
+ // and the server re-renders the page: the same form works with JavaScript
80
+ // disabled, which Server Actions in other frameworks do not.
81
+ document.addEventListener('submit', (e) => {
82
+ const f = e.target;
83
+ if (!f || f.tagName !== 'FORM' || f.hasAttribute('data-on-submit')) return;
84
+ if ((f.getAttribute('method') || '').toLowerCase() !== 'post') return;
85
+ e.preventDefault();
86
+ postForm(new FormData(f));
87
+ });
88
+ // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
89
+ // If the document was rendered for a DIFFERENT route (a static-file server's
90
+ // SPA fallback serves index.html for unknown paths), adopt nothing - let the
91
+ // client router render the requested route from scratch.
92
+ const __st = document.getElementById('__rosetack_state');
93
+ const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
94
+ if (__state.__route === window.location.pathname) {
95
+ start(__app, window.location.pathname, true);
96
+ } else {
97
+ start(__app, window.location.pathname);
98
+ }
99
+ `, { minify: true }).code;
100
+ var CSP_TAIL = `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'`;
101
+ var cspCache = null;
102
+ var EXTERNAL_BOOTSTRAP = `
103
+ import { start, prefetch, postForm } from '/client.js';
104
+ ${BOOTSTRAP}`;
105
+ function inlineScript(client) {
106
+ return `
107
+ ${client}
108
+ ${BOOTSTRAP}`;
109
+ }
110
+ function mintNonce() {
111
+ const bytes = new Uint8Array(16);
112
+ crypto.getRandomValues(bytes);
113
+ let raw = "";
114
+ for (const b of bytes) raw += String.fromCharCode(b);
115
+ return btoa(raw);
116
+ }
117
+ function securityHeaders(client, nonce = "") {
118
+ if (nonce) return { "Content-Security-Policy": `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
119
+ if (!cspCache || cspCache.for !== client) {
120
+ const scriptSrc = client ? `'sha256-${createHash("sha256").update(inlineScript(client), "utf-8").digest("base64")}'` : `'self' 'sha256-${createHash("sha256").update(EXTERNAL_BOOTSTRAP, "utf-8").digest("base64")}'`;
121
+ cspCache = {
122
+ for: client,
123
+ value: `script-src ${scriptSrc}; ${CSP_TAIL}`
124
+ };
125
+ }
126
+ return { "Content-Security-Policy": cspCache.value };
127
+ }
128
+ var 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==">';
129
+ var STYLES = `
130
+ body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
131
+ button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
132
+ a { color: #e91e63; text-decoration: none; font-weight: bold; }
133
+ a:hover { text-decoration: underline; }
134
+ nav a { margin-right: 1rem; }
135
+ .rh { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; border-bottom: 2px solid #e91e63; margin-bottom: 1.5rem; padding-bottom: 0.75rem; }
136
+ .rb { font-size: 1.6rem; }
137
+ .rbrand { display: inline-flex; align-items: center; gap: 0.5em; }
138
+ .rlogo { height: 1em; width: 1em; vertical-align: -0.08em; margin-right: 0.2em; }
139
+ @media (max-width: 640px) {
140
+ .rh { flex-direction: column; align-items: flex-start; gap: 0.75rem; }
141
+ nav a:last-child { margin-right: 0; }
142
+ }
143
+ .rn { display: inline-block; margin-left: 1.5rem; }
144
+ .rf { margin-top: 2rem; color: #888; font-size: 0.85rem; }
145
+ ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
146
+ `;
147
+ var STYLES_MIN = STYLES.replace(
148
+ /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
149
+ (m) => m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, " ").replace(/\s*([:;{},])\s*/g, "$1").trim()
150
+ ).trim();
151
+ function mergeHeadBlocks(blocks) {
152
+ const byKey = /* @__PURE__ */ new Map();
153
+ const order = [];
154
+ const put = (key, html) => {
155
+ if (!byKey.has(key)) {
156
+ byKey.set(key, html);
157
+ order.push(key);
158
+ }
159
+ };
160
+ for (const block of blocks) {
161
+ for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put("title", m[0]);
162
+ for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
163
+ const tag = m[1].toLowerCase();
164
+ const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
165
+ const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
166
+ const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
167
+ put(key, marked);
168
+ }
169
+ }
170
+ return order.map((k) => byKey.get(k)).join("\n ");
171
+ }
172
+ function clientScriptTag(client, nonce = "") {
173
+ const n = nonce ? ` nonce="${nonce}"` : "";
174
+ return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
175
+ <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
176
+ }
177
+ function shellOpen(styles = getStyles(), lang = "en", dir = "") {
178
+ const styleTag = styles ? `
179
+ <style>${styles}</style>` : "";
180
+ return `<!DOCTYPE html>
181
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
182
+ <head>
183
+ <meta charset="UTF-8">
184
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
185
+ <title>RoseTack</title>
186
+ <style>${STYLES_MIN}</style>${styleTag}
187
+ ${FAVICON}
188
+ </head>
189
+ <body>
190
+ <div id="app">`;
191
+ }
192
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
193
+ const clientTag = clientScriptTag(client, nonce);
194
+ const mergedHead = mergeHeadBlocks(head);
195
+ const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
196
+ const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
197
+ ${FAVICON}`;
198
+ const headTags = mergedHead ? `
199
+ ${mergedHead}` : "";
200
+ const styleTag = styles ? `
201
+ <style>${styles}</style>` : "";
202
+ const jsTail = js ? `
203
+ <script type="application/json" id="__rosetack_state">${stateJson}</script>
204
+ ${clientTag}` : "";
205
+ return `<!DOCTYPE html>
206
+ <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
207
+ <head>
208
+ <meta charset="UTF-8">
209
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
210
+ ${titleTag}
211
+ <style>${STYLES_MIN}</style>${styleTag}
212
+ </head>
213
+ <body>
214
+ <div id="app">${ssrHtml}</div>${jsTail}
215
+ </body>
216
+ </html>`;
217
+ }
218
+
219
+ // src/cli/edge.ts
220
+ async function createEdgeHandler(outDir) {
221
+ const mod = await import(pathToFileURL(join2(outDir, "server.js")).href);
222
+ let client = null;
223
+ let styles = "";
224
+ try {
225
+ client = await (await import("fs/promises")).readFile(join2(outDir, "client.js"), "utf-8");
226
+ } catch {
227
+ client = null;
228
+ }
229
+ try {
230
+ styles = await (await import("fs/promises")).readFile(join2(outDir, "styles.css"), "utf-8");
231
+ } catch {
232
+ styles = "";
233
+ }
234
+ let broken = /* @__PURE__ */ new Set();
235
+ try {
236
+ broken = new Set(JSON.parse(await (await import("fs/promises")).readFile(join2(outDir, "broken.json"), "utf-8")));
237
+ } catch {
238
+ broken = /* @__PURE__ */ new Set();
239
+ }
240
+ const pageHeaders = (pathname, nonce = "") => {
241
+ const headers = {};
242
+ if (client) for (const [k, v] of Object.entries(securityHeaders(client, nonce))) headers[k.toLowerCase()] = v;
243
+ const own = mod.headersFor?.(pathname);
244
+ if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
245
+ return headers;
246
+ };
247
+ return async function handle(request) {
248
+ const { pathname } = new URL(request.url);
249
+ const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks ? { request, url: new URL(request.url), method: request.method, pathname, state: {} } : null;
250
+ if (hookCtx) {
251
+ const short = await mod.runRequestHooks(hookCtx);
252
+ if (short) return mod.runResponseHooks(hookCtx, short);
253
+ }
254
+ if (mod.middleware) {
255
+ const mw = await mod.runMiddleware(request);
256
+ if (mw) return hookCtx ? mod.runResponseHooks(hookCtx, mw) : mw;
257
+ }
258
+ if (mod.isApi(pathname)) {
259
+ const apiRes = await mod.handleApi(request.method, pathname, request);
260
+ return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
261
+ }
262
+ const form = request.method === "POST" ? await request.formData() : void 0;
263
+ if (!form && !broken.has(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
264
+ const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
265
+ const streamed = new Response(null, {
266
+ status: 200,
267
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders(pathname, nonce2) }
268
+ });
269
+ const head = hookCtx ? await mod.runResponseHooks(hookCtx, streamed) : streamed;
270
+ const encoder = new TextEncoder();
271
+ const stream = new ReadableStream({
272
+ async start(controller) {
273
+ const doc = mod.docAttrs(pathname);
274
+ await mod.renderPageStream(
275
+ pathname,
276
+ (chunk) => controller.enqueue(encoder.encode(chunk)),
277
+ shellOpen(styles, doc.lang, doc.dir),
278
+ clientScriptTag(client, nonce2)
279
+ );
280
+ controller.close();
281
+ }
282
+ });
283
+ return new Response(stream, { status: head.status, headers: head.headers });
284
+ }
285
+ const page = await mod.renderPage(pathname, form);
286
+ const nonce = mod.cspNonce?.(pathname) ? mintNonce() : "";
287
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce);
288
+ const buffered = new Response(html, {
289
+ status: page.status ?? 200,
290
+ headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders(pathname, nonce) }
291
+ });
292
+ return hookCtx ? mod.runResponseHooks(hookCtx, buffered) : buffered;
293
+ };
294
+ }
295
+ export {
296
+ createEdgeHandler
297
+ };