rosetack 0.1.1 → 0.1.3

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 (56) hide show
  1. package/deploy/cloudflare/functions/[[path]].ts +61 -0
  2. package/deploy/cloudflare/wrangler.toml +14 -0
  3. package/deploy/k8s/rosetack.yaml +107 -0
  4. package/deploy/netlify/functions/rosetack.ts +38 -0
  5. package/deploy/netlify.toml +17 -0
  6. package/devtools/devtools.html +7 -0
  7. package/devtools/devtools.js +1 -0
  8. package/devtools/manifest.json +8 -0
  9. package/devtools/panel.html +28 -0
  10. package/devtools/panel.js +54 -0
  11. package/dist-cli/compiler.mjs +1346 -492
  12. package/dist-cli/edge.mjs +152 -41
  13. package/dist-cli/rosetack.mjs +1974 -606
  14. package/dist-cli/runtime.mjs +205 -40
  15. package/dist-cli/test.mjs +1425 -508
  16. package/package.json +4 -3
  17. package/src/FRAMEWORK_VERSION +1 -1
  18. package/src/cli/edge.ts +76 -61
  19. package/src/cli/index.ts +516 -293
  20. package/src/cli/prompt.ts +130 -0
  21. package/src/cli/shell.ts +113 -65
  22. package/src/cli/test.ts +9 -70
  23. package/src/compiler/errors.ts +74 -0
  24. package/src/compiler/index.ts +1514 -839
  25. package/src/runtime/index.ts +255 -150
  26. package/src/types/rosetack.d.ts +18 -59
  27. package/templates/admin/package.json +14 -0
  28. package/templates/admin/rosetack.config.js +1 -0
  29. package/templates/admin/src/pages/_middleware.rose +33 -0
  30. package/templates/admin/src/pages/api/items.rose +37 -0
  31. package/templates/admin/src/pages/api/login.rose +25 -0
  32. package/templates/admin/src/pages/index.rose +79 -0
  33. package/templates/api/package.json +14 -0
  34. package/templates/api/rosetack.config.js +1 -0
  35. package/templates/api/src/pages/api/health.rose +7 -0
  36. package/templates/api/src/pages/api/items.rose +46 -0
  37. package/templates/api/src/pages/api/login.rose +24 -0
  38. package/templates/api/src/pages/index.rose +25 -0
  39. package/templates/blog/package.json +14 -0
  40. package/templates/blog/rosetack.config.js +1 -0
  41. package/templates/blog/src/pages/404.rose +2 -0
  42. package/templates/blog/src/pages/_layout.rose +42 -0
  43. package/templates/blog/src/pages/_middleware.rose +74 -0
  44. package/templates/blog/src/pages/admin.rose +85 -0
  45. package/templates/blog/src/pages/api/login.rose +46 -0
  46. package/templates/blog/src/pages/api/posts/[id].rose +37 -0
  47. package/templates/blog/src/pages/api/posts.rose +72 -0
  48. package/templates/blog/src/pages/index.rose +31 -0
  49. package/templates/blog/src/pages/post/[id].rose +36 -0
  50. package/templates/site/package.json +14 -0
  51. package/templates/site/rosetack.config.js +1 -0
  52. package/templates/site/src/pages/404.rose +2 -0
  53. package/templates/site/src/pages/_layout.rose +40 -0
  54. package/templates/site/src/pages/about.rose +6 -0
  55. package/templates/site/src/pages/index.rose +13 -0
  56. package/templates/site/src/pages/pricing.rose +8 -0
package/dist-cli/edge.mjs CHANGED
@@ -22,7 +22,25 @@ function getStyles() {
22
22
  }
23
23
  }
24
24
  var BOOTSTRAP = esbuild.transformSync(`
25
- const __app = document.getElementById('app');
25
+ // shell = false: the document's SSR content sits directly in <body> - no
26
+ // #app wrapper, no demo styles, so a real theme's CSS owns the document from
27
+ // the first byte (and a JS-less visitor never sees either). The bundle still
28
+ // runs, and it still needs its container: wrap the content once, here, before
29
+ // any theme script executes (module scripts run before DOMContentLoaded). The
30
+ // wrapper is a plain unstyled div, so the re-parent is visually inert; every
31
+ // later path - adoption, navigation, forms - is then the ordinary one.
32
+ let __app = document.getElementById('app');
33
+ if (!__app) {
34
+ __app = document.createElement('div');
35
+ __app.id = 'app';
36
+ // scripts stay outside the wrapper, exactly where the dressed document
37
+ // keeps them: the state element and the running module must survive a
38
+ // navigation's innerHTML swap (they are the document's, not the route's).
39
+ for (const node of Array.from(document.body.children)) {
40
+ if (node.tagName !== 'SCRIPT') __app.appendChild(node);
41
+ }
42
+ document.body.appendChild(__app);
43
+ }
26
44
  // Native View Transitions around client-side navigation (progressive:
27
45
  // browsers without the API navigate normally, no polyfill, no CSS required).
28
46
  function __navigate(pathname) {
@@ -85,22 +103,52 @@ document.addEventListener('submit', (e) => {
85
103
  e.preventDefault();
86
104
  postForm(new FormData(f));
87
105
  });
106
+ // Dev seam: the live signal graph, readable as JSON. Three callers, one
107
+ // implementation: the dev server's reload bridge snapshots it before a
108
+ // rebuild-triggered reload so the edit lands on the state the developer had,
109
+ // and the devtools extension (devtools/) reads it the same way - the signal
110
+ // graph plus the prefetch counters, which is the whole observable state of a
111
+ // running page. Both are DIRECT references (no wrapper arrow): the names take
112
+ // no arguments, so the call is identical and every document that carries the
113
+ // bundle pays eleven bytes for the pair instead of forty.
114
+ window.__rosetack = { state: serializeState, prefetch: prefetchStats };
88
115
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
89
116
  // If the document was rendered for a DIFFERENT route (a static-file server's
90
117
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
91
118
  // client router render the requested route from scratch.
92
119
  const __st = document.getElementById('__rosetack_state');
93
- const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
94
- if (__state.__route === window.location.pathname) {
120
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
121
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
122
+ // the next document (window.__rosetack_resume). The resumed values win over the
123
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
124
+ // the route renders client-side from the bundle rather than adopting the SSR
125
+ // DOM, because a resumed list can be longer than the document's rows and
126
+ // adoption could not add them. Absent in every non-dev document.
127
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
128
+ if (__resumed) {
129
+ const __route = __state.__route;
130
+ __state = Object.assign(__state, __resumed);
131
+ __state.__route = __route;
132
+ }
133
+ // A NOT-FOUND document (the server stamps __notFound onto its state) boots
134
+ // into the app's own 404 route: the URL matches no route - or a catch-all
135
+ // whose resolver threw notFound(), whose key sits null in the resumed state
136
+ // and whose template would dereference it into a 500. startNotFound paints
137
+ // the not-found route from the resumed state instead (zero requests).
138
+ if (__state.__notFound) {
139
+ startNotFound(__app, window.location.pathname);
140
+ } else if (__resumed) {
141
+ start(__app, window.location.pathname);
142
+ } else if (__state.__route === window.location.pathname) {
95
143
  start(__app, window.location.pathname, true);
96
144
  } else {
97
145
  start(__app, window.location.pathname);
98
146
  }
99
147
  `, { 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'`;
148
+ var CSP_TAIL = `style-src 'unsafe-inline'; img-src 'self' data: https://fastly.picsum.photos; font-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'`;
101
149
  var cspCache = null;
102
150
  var EXTERNAL_BOOTSTRAP = `
103
- import { start, prefetch, postForm } from '/client.js';
151
+ import { start, prefetch, postForm, prefetchStats } from '/client.js';
104
152
  ${BOOTSTRAP}`;
105
153
  function inlineScript(client) {
106
154
  return `
@@ -151,6 +199,7 @@ var STYLES_MIN = STYLES.replace(
151
199
  function mergeHeadBlocks(blocks) {
152
200
  const byKey = /* @__PURE__ */ new Map();
153
201
  const order = [];
202
+ const positional = /* @__PURE__ */ new Map();
154
203
  const put = (key, html) => {
155
204
  if (!byKey.has(key)) {
156
205
  byKey.set(key, html);
@@ -159,11 +208,20 @@ function mergeHeadBlocks(blocks) {
159
208
  };
160
209
  for (const block of blocks) {
161
210
  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)) {
211
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
163
212
  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];
213
+ if (tag === "title") continue;
214
+ const attrs = m[2];
215
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
216
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
217
+ let key;
218
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
219
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
220
+ else {
221
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
222
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
223
+ }
224
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
167
225
  put(key, marked);
168
226
  }
169
227
  }
@@ -174,68 +232,114 @@ function clientScriptTag(client, nonce = "") {
174
232
  return client ? `<script type="module"${n}>${inlineScript(client)}</script>` : `<script type="module"${n} src="/client.js"></script>
175
233
  <script type="module"${n}>${EXTERNAL_BOOTSTRAP}</script>`;
176
234
  }
177
- function shellOpen(styles = getStyles(), lang = "en", dir = "") {
235
+ function shellOpen(styles = getStyles(), lang = "en", dir = "", shell = true) {
178
236
  const styleTag = styles ? `
179
237
  <style>${styles}</style>` : "";
238
+ const demoStyles = shell ? `
239
+ <style>${STYLES_MIN}</style>` : "";
240
+ const appOpen = shell ? `
241
+ <div id="app">` : "";
180
242
  return `<!DOCTYPE html>
181
243
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
182
244
  <head>
183
245
  <meta charset="UTF-8">
184
246
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
185
- <title>RoseTack</title>
186
- <style>${STYLES_MIN}</style>${styleTag}
247
+ <title>RoseTack</title>${demoStyles}${styleTag}
187
248
  ${FAVICON}
188
249
  </head>
189
- <body>
190
- <div id="app">`;
250
+ <body>${appOpen}`;
191
251
  }
192
- function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "") {
252
+ function buildShell(ssrHtml, stateJson, client, head = [], styles = getStyles(), js = true, lang = "en", dir = "", nonce = "", shell = true) {
193
253
  const clientTag = clientScriptTag(client, nonce);
194
254
  const mergedHead = mergeHeadBlocks(head);
255
+ const headStamped = nonce ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs) => /\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`) : mergedHead;
256
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ""}`;
257
+ let bodyAttrs = "";
258
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag, attrs) => {
259
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, "");
260
+ if (tag === "html") htmlAttrs = clean;
261
+ else bodyAttrs = clean;
262
+ return "";
263
+ });
195
264
  const titleTag = /<title>/i.test(mergedHead) ? "" : "<title>RoseTack</title>";
196
265
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? "" : `
197
266
  ${FAVICON}`;
198
- const headTags = mergedHead ? `
199
- ${mergedHead}` : "";
267
+ const headTags = headClean ? `
268
+ ${headClean}` : "";
200
269
  const styleTag = styles ? `
201
270
  <style>${styles}</style>` : "";
271
+ const stateSafe = stateJson.replace(/</g, "\\u003c");
202
272
  const jsTail = js ? `
203
- <script type="application/json" id="__rosetack_state">${stateJson}</script>
273
+ <script type="application/json" id="__rosetack_state">${stateSafe}</script>
204
274
  ${clientTag}` : "";
275
+ const open = js && shell ? '<div id="app">' : "";
276
+ const close = js && shell ? "</div>" : "";
277
+ const shellStyles = js && shell ? `
278
+ <style>${STYLES_MIN}</style>` : "";
205
279
  return `<!DOCTYPE html>
206
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ""}>
280
+ <html${htmlAttrs}>
207
281
  <head>
208
282
  <meta charset="UTF-8">
209
283
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
210
- ${titleTag}
211
- <style>${STYLES_MIN}</style>${styleTag}
284
+ ${titleTag}${shellStyles}${styleTag}
212
285
  </head>
213
- <body>
214
- <div id="app">${ssrHtml}</div>${jsTail}
286
+ <body${bodyAttrs}>
287
+ ${open}${ssrHtml}${close}${jsTail}
215
288
  </body>
216
289
  </html>`;
217
290
  }
218
291
 
219
292
  // src/cli/edge.ts
220
- async function createEdgeHandler(outDir) {
221
- const mod = await import(pathToFileURL(join2(outDir, "server.js")).href);
293
+ function crossSiteWrite(request) {
294
+ const m = request.method;
295
+ if (m !== "POST" && m !== "PUT" && m !== "PATCH" && m !== "DELETE") return null;
296
+ const origin = request.headers.get("origin");
297
+ if (origin) {
298
+ let host;
299
+ try {
300
+ host = new URL(origin).host;
301
+ } catch {
302
+ return new Response("Cross-site request blocked (unparsable Origin header)", { status: 403 });
303
+ }
304
+ return host === new URL(request.url).host ? null : new Response("Cross-site request blocked (Origin does not match Host)", { status: 403 });
305
+ }
306
+ const site = request.headers.get("sec-fetch-site");
307
+ if (site && site !== "same-origin" && site !== "same-site" && site !== "none") {
308
+ return new Response(`Cross-site request blocked (sec-fetch-site: ${site})`, { status: 403 });
309
+ }
310
+ return null;
311
+ }
312
+ async function createEdgeHandler(outDir, preloaded) {
313
+ const mod = preloaded?.server ?? await import(pathToFileURL(join2(outDir, "server.js")).href);
222
314
  let client = null;
223
315
  let styles = "";
224
- try {
225
- client = await (await import("fs/promises")).readFile(join2(outDir, "client.js"), "utf-8");
226
- } catch {
227
- client = null;
316
+ if (preloaded && "client" in preloaded) {
317
+ client = preloaded.client ?? null;
318
+ } else {
319
+ try {
320
+ client = await (await import("fs/promises")).readFile(join2(outDir, "client.js"), "utf-8");
321
+ } catch {
322
+ client = null;
323
+ }
228
324
  }
229
- try {
230
- styles = await (await import("fs/promises")).readFile(join2(outDir, "styles.css"), "utf-8");
231
- } catch {
232
- styles = "";
325
+ if (preloaded && "styles" in preloaded) {
326
+ styles = preloaded.styles ?? "";
327
+ } else {
328
+ try {
329
+ styles = await (await import("fs/promises")).readFile(join2(outDir, "styles.css"), "utf-8");
330
+ } catch {
331
+ styles = "";
332
+ }
233
333
  }
234
334
  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();
335
+ if (preloaded && "broken" in preloaded) {
336
+ broken = new Set(preloaded.broken);
337
+ } else {
338
+ try {
339
+ broken = new Set(JSON.parse(await (await import("fs/promises")).readFile(join2(outDir, "broken.json"), "utf-8")));
340
+ } catch {
341
+ broken = /* @__PURE__ */ new Set();
342
+ }
239
343
  }
240
344
  const pageHeaders = (pathname, nonce = "") => {
241
345
  const headers = {};
@@ -245,7 +349,14 @@ async function createEdgeHandler(outDir) {
245
349
  return headers;
246
350
  };
247
351
  return async function handle(request) {
248
- const { pathname } = new URL(request.url);
352
+ const refused = crossSiteWrite(request);
353
+ if (refused) return refused;
354
+ const { pathname, searchParams } = new URL(request.url);
355
+ const canonical = pathname.replace(/\/+$/, "") || "/";
356
+ if (canonical !== pathname) {
357
+ return new Response(null, { status: 308, headers: { location: canonical + new URL(request.url).search } });
358
+ }
359
+ mod.setQuery?.(Object.fromEntries(searchParams));
249
360
  const hookCtx = mod.hasRequestHooks || mod.hasResponseHooks ? { request, url: new URL(request.url), method: request.method, pathname, state: {} } : null;
250
361
  if (hookCtx) {
251
362
  const short = await mod.runRequestHooks(hookCtx);
@@ -260,7 +371,7 @@ async function createEdgeHandler(outDir) {
260
371
  return hookCtx ? mod.runResponseHooks(hookCtx, apiRes) : apiRes;
261
372
  }
262
373
  const form = request.method === "POST" ? await request.formData() : void 0;
263
- if (!form && !broken.has(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
374
+ if (!form && !broken.has(pathname) && !mod.isBuffered?.(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
264
375
  const nonce2 = mod.cspNonce?.(pathname) ? mintNonce() : "";
265
376
  const streamed = new Response(null, {
266
377
  status: 200,
@@ -274,7 +385,7 @@ async function createEdgeHandler(outDir) {
274
385
  await mod.renderPageStream(
275
386
  pathname,
276
387
  (chunk) => controller.enqueue(encoder.encode(chunk)),
277
- shellOpen(styles, doc.lang, doc.dir),
388
+ shellOpen(styles, doc.lang, doc.dir, !mod.shellOff?.(pathname)),
278
389
  clientScriptTag(client, nonce2)
279
390
  );
280
391
  controller.close();
@@ -284,7 +395,7 @@ async function createEdgeHandler(outDir) {
284
395
  }
285
396
  const page = await mod.renderPage(pathname, form);
286
397
  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);
398
+ const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false, page.lang, page.dir, nonce, page.shell !== false);
288
399
  const buffered = new Response(html, {
289
400
  status: page.status ?? 200,
290
401
  headers: { "content-type": "text/html; charset=utf-8", ...pageHeaders(pathname, nonce) }