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
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The canonical .rose authoring contract, printed by `rosetack prompt`.
3
+ *
4
+ * Why a command and not a doc page: the audience is as often an AI agent as
5
+ * a human, and the agent needs the contract at the moment it writes code,
6
+ * not a URL to go read. One command, stdout, no network - the same shape as
7
+ * every other tool an agent already shells out to.
8
+ *
9
+ * The content is the compiler's actual rules, in the order a page meets
10
+ * them: file layout, the script block, the template, head and styles,
11
+ * events and actions, the exports, the npm boundary, and the error
12
+ * contract. Anything the compiler REFUSES is listed as a rule here, so a
13
+ * correct page compiles on the first try.
14
+ */
15
+ export const AI_PROMPT = `# rosetack authoring contract (printed by \`rosetack prompt\`)
16
+
17
+ rosetack is a zero-hydration web framework: a .rose file compiles to a server
18
+ render plus a client resume bundle, one request per page, no hydration. Write
19
+ the smallest thing that works - the compiler decides what ships.
20
+
21
+ ## File layout (all paths relative to the project root)
22
+
23
+ - src/pages/index.rose -> route /
24
+ - src/pages/about.rose -> route /about
25
+ - src/pages/blog/[id].rose -> route /blog/:id (the param is readable as state \`id()\`)
26
+ - src/pages/[lang]/about.rose -> localized route (see i18n below)
27
+ - src/pages/_layout.rose -> root layout wrapping every route (app-global exports live here)
28
+ - src/pages/_middleware.rose -> server-only request middleware (handle(request), getContext())
29
+ - src/pages/404.rose, 500.rose -> error pages
30
+ - src/pages/api/posts.rose -> JSON API route (export async function GET/POST/...)
31
+ - src/components/Card.rose -> reusable component, imported by relative path
32
+ - src/locales/en.json -> i18n dictionaries (one file per language)
33
+
34
+ ## A page
35
+
36
+ \`\`\`rose
37
+ <script>
38
+ let count = $state(0); // reactive state: read it as count()
39
+ let posts = $data(async () => db.query()); // server data: awaited on the server,
40
+ // resumed on the client - never re-fetched
41
+ const total = count() + 1; // a top-level read AFTER the declaration is fine
42
+ async function like() { // a server action (progressive enhancement)
43
+ return $merge({ likes: 1 });
44
+ }
45
+ </script>
46
+
47
+ <h1>Posts</h1>
48
+ <p>Total: {total}</p>
49
+ <button on:click={() => $setState('count', count() + 1)}>+1</button>
50
+ <form method="POST"><input type="hidden" name="__action" value="like"><button type="submit">Like</button></form>
51
+ \`\`\`
52
+
53
+ Rules the compiler enforces (breaking one fails the build):
54
+
55
+ - The script block is TypeScript. Types, interfaces, \`import type\`, \`as\` casts and
56
+ type arguments ($state<Post[]>([])) are all erased from the shipped bundles.
57
+ - $state / $data declarations are top-level statements. The declared name IS the
58
+ getter: write count() in the template and the script, never bare count.
59
+ - A route param (pages/blog/[id].rose) is read as state too: declare it
60
+ (\`let id = $state('1')\`) and read id() - the server overwrites the default
61
+ with the URL's value, and export const params = { id: [...] } bakes those
62
+ values at build time.
63
+ - $data() is banned in components (src/components/**) - a component renders
64
+ synchronously inside its parent. Fetch in the page or the middleware and pass
65
+ the value down as a prop.
66
+ - Template interpolation {expr} is HTML-escaped. {@html expr} is the explicit
67
+ trusted-HTML escape hatch - use it only for content you control.
68
+ - Blocks: {#if cond}...{/if}, {#each items as item}...{/each},
69
+ {#boundary}...{/boundary}. There is NO {:else} - nest a second {#if}.
70
+ - A <slot> with attributes is a named slot and must declare its name:
71
+ <slot name="row" item={post} />. A named slot must be a DIRECT child of the
72
+ component tag - never inside another element or an {#if}/{#each} block.
73
+ - Every component tag needs its matching close tag (or self-closes with />).
74
+ - In <head>: <title>, <meta>, <link>, <style>, <script>, <noscript> all pass
75
+ through. A <style> inside <head> is document CSS; a <style> in the body is
76
+ the component's scoped stylesheet.
77
+ - Node-only modules (node:fs, better-sqlite3, pg, redis, ...) are REFUSED in
78
+ pages and components: their script ships to the browser. Import them in
79
+ src/pages/_middleware.rose or a pages/api/*.rose handler instead, and pass
80
+ the rows to the page through getContext().
81
+
82
+ ## Events and server actions
83
+
84
+ - on:click={handler} wires a client event. The handler is a named function from
85
+ the script or an inline arrow: on:click={() => $setState('n', n() + 1)}.
86
+ - A server action is an exported async function. Call it from a native form
87
+ (method="POST", no JS needed - progressive enhancement) or from any event
88
+ (on:click={like} - one POST, in-place adopt). Its return value is an
89
+ incremental patch: $append(row) / $prepend(row) / $merge({...}).
90
+ - A form selects its action by the __action FIELD: name the function
91
+ \`action\` (the default) or add <input type="hidden" name="__action"
92
+ value="like">. The server reads the field, not the URL.
93
+ - Business failures: throw new ActionError('message', 422, 'field'). It lands
94
+ in ordinary state - $actionError() reads it back, a {#boundary} contains it.
95
+ - beforeAction(name, form) is the per-page guard that vetoes an action.
96
+
97
+ ## Route exports (in the script block, validated at build time)
98
+
99
+ - export const csr = false | true force/assert zero-JS (absent = the compiler decides)
100
+ - export const buffer = true keep this route off the streaming path
101
+ - export const headers = { ... } flat string map, merged over the strict CSP default
102
+ - export const csp = { nonce: true } per-response nonce instead of the hash (route becomes dynamic)
103
+ - export const prefetch = 'off' | 'hover' | 'viewport' | 'all' app-global, root layout only
104
+ - export const bundle = 'inline' | 'split' app-global; 'split' = mode B for large apps
105
+ - export const vitals = true opt into the web-vitals hook
106
+ - export const revalidate = N stale-while-revalidate ISR window, seconds
107
+ - export const params = { id: ['1'] } prerender these param values at build time
108
+ - export const prerender = true (api routes) bake the GET body for static deploys
109
+
110
+ ## i18n
111
+
112
+ src/locales/<lang>.json is a dictionary; a [lang] route segment selects one;
113
+ $t('key', { name }) translates reactively; unknown locales answer 404.
114
+
115
+ ## When a build fails
116
+
117
+ Every compiler failure is structured: { code, file, line, message, hint }.
118
+ Run \`rosetack build --json\` to read it as JSON, fix the named file at the named
119
+ line, and build again. Codes: E-IMPORT (unresolvable .rose import), E-PLUGIN
120
+ (transform threw), E-NODE-ONLY (server-only import in a page/component),
121
+ E-EXPORT (invalid export const value), E-TEMPLATE (unclosed tag / slot
122
+ placement), E-ROUTE (no pages found), E-INTERNAL (installation problem).
123
+
124
+ ## The one invariant worth protecting
125
+
126
+ A route ships ONE request with ZERO hydration: the whole client bundle is
127
+ inlined in the document. Keep it that way - browser-only code (document.,
128
+ window., timers) belongs in onMount, and anything the predicate cannot see
129
+ (inline on* attributes, javascript: URLs, eval) is reported by the build.
130
+ `;
package/src/cli/shell.ts CHANGED
@@ -1,11 +1,4 @@
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 achieves that - they all
7
- * ship a separate JS bundle, doubling the round-trips before first paint.
8
- */
1
+
9
2
 
10
3
  import * as fs from 'fs';
11
4
  import * as path from 'path';
@@ -16,8 +9,6 @@ const OUT_DIR = path.join(process.cwd(), 'dist');
16
9
 
17
10
  let clientCache: { mtimeMs: number; source: string } | null = null;
18
11
 
19
- // The bundle mode the last build decided ('inline' | 'split'). In split mode
20
- // getClientSource() answers null - "nothing to inline" - so every shell caller …
21
12
  let splitMode = false;
22
13
  export function setBundleMode(mode: string): void {
23
14
  splitMode = mode === 'split';
@@ -25,7 +16,7 @@ export function setBundleMode(mode: string): void {
25
16
 
26
17
  /** Read dist/client.js with an mtime-based cache (dev server rebuilds it). */
27
18
  export function getClientSource(): string | null {
28
- if (splitMode) return null; // mode B: the document references /client.js
19
+ if (splitMode) return null;
29
20
  const file = path.join(OUT_DIR, 'client.js');
30
21
  try {
31
22
  const st = fs.statSync(file);
@@ -40,11 +31,7 @@ export function getClientSource(): string | null {
40
31
 
41
32
  let styleCache: { mtimeMs: number; source: string } | null = null;
42
33
 
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
- */
34
+ // Read dist/styles.css (every component's scoped <style>, merged at build time) with an mtime-based cache.
48
35
  export function getStyles(): string {
49
36
  const file = path.join(OUT_DIR, 'styles.css');
50
37
  try {
@@ -58,10 +45,26 @@ export function getStyles(): string {
58
45
  }
59
46
  }
60
47
 
61
- // Bootstrap appended after the inlined bundle: client-side navigation. Distinct names avoid
62
- // any collision with minified bundle identifiers.
63
48
  const BOOTSTRAP = esbuild.transformSync(`
64
- const __app = document.getElementById('app');
49
+ // shell = false: the document's SSR content sits directly in <body> - no
50
+ // #app wrapper, no demo styles, so a real theme's CSS owns the document from
51
+ // the first byte (and a JS-less visitor never sees either). The bundle still
52
+ // runs, and it still needs its container: wrap the content once, here, before
53
+ // any theme script executes (module scripts run before DOMContentLoaded). The
54
+ // wrapper is a plain unstyled div, so the re-parent is visually inert; every
55
+ // later path - adoption, navigation, forms - is then the ordinary one.
56
+ let __app = document.getElementById('app');
57
+ if (!__app) {
58
+ __app = document.createElement('div');
59
+ __app.id = 'app';
60
+ // scripts stay outside the wrapper, exactly where the dressed document
61
+ // keeps them: the state element and the running module must survive a
62
+ // navigation's innerHTML swap (they are the document's, not the route's).
63
+ for (const node of Array.from(document.body.children)) {
64
+ if (node.tagName !== 'SCRIPT') __app.appendChild(node);
65
+ }
66
+ document.body.appendChild(__app);
67
+ }
65
68
  // Native View Transitions around client-side navigation (progressive:
66
69
  // browsers without the API navigate normally, no polyfill, no CSS required).
67
70
  function __navigate(pathname) {
@@ -124,28 +127,52 @@ document.addEventListener('submit', (e) => {
124
127
  e.preventDefault();
125
128
  postForm(new FormData(f));
126
129
  });
130
+ // Dev seam: the live signal graph, readable as JSON. Three callers, one
131
+ // implementation: the dev server's reload bridge snapshots it before a
132
+ // rebuild-triggered reload so the edit lands on the state the developer had,
133
+ // and the devtools extension (devtools/) reads it the same way - the signal
134
+ // graph plus the prefetch counters, which is the whole observable state of a
135
+ // running page. Both are DIRECT references (no wrapper arrow): the names take
136
+ // no arguments, so the call is identical and every document that carries the
137
+ // bundle pays eleven bytes for the pair instead of forty.
138
+ window.__rosetack = { state: serializeState, prefetch: prefetchStats };
127
139
  // initial=true: DOM is SSR output, resume state + wire markers (zero hydration).
128
140
  // If the document was rendered for a DIFFERENT route (a static-file server's
129
141
  // SPA fallback serves index.html for unknown paths), adopt nothing - let the
130
142
  // client router render the requested route from scratch.
131
143
  const __st = document.getElementById('__rosetack_state');
132
- const __state = __st ? JSON.parse(__st.textContent || '{}') : {};
133
- if (__state.__route === window.location.pathname) {
144
+ let __state = __st ? JSON.parse(__st.textContent || '{}') : {};
145
+ // The dev server's reload bridge hands the pre-reload signal graph back inside
146
+ // the next document (window.__rosetack_resume). The resumed values win over the
147
+ // fresh render's, but the ROUTE stays the one the server just rendered - and
148
+ // the route renders client-side from the bundle rather than adopting the SSR
149
+ // DOM, because a resumed list can be longer than the document's rows and
150
+ // adoption could not add them. Absent in every non-dev document.
151
+ const __resumed = window.__rosetack_resume ? JSON.parse(window.__rosetack_resume) : null;
152
+ if (__resumed) {
153
+ const __route = __state.__route;
154
+ __state = Object.assign(__state, __resumed);
155
+ __state.__route = __route;
156
+ }
157
+ // A NOT-FOUND document (the server stamps __notFound onto its state) boots
158
+ // into the app's own 404 route: the URL matches no route - or a catch-all
159
+ // whose resolver threw notFound(), whose key sits null in the resumed state
160
+ // and whose template would dereference it into a 500. startNotFound paints
161
+ // the not-found route from the resumed state instead (zero requests).
162
+ if (__state.__notFound) {
163
+ startNotFound(__app, window.location.pathname);
164
+ } else if (__resumed) {
165
+ start(__app, window.location.pathname);
166
+ } else if (__state.__route === window.location.pathname) {
134
167
  start(__app, window.location.pathname, true);
135
168
  } else {
136
169
  start(__app, window.location.pathname);
137
170
  }
138
171
  `, { minify: true }).code;
139
172
 
140
- // The document inlines its entire runtime, so rosetack can ship a STRICT content security
141
- // policy without 'unsafe-inline' in script-src …
142
- const 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'`;
173
+ const 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'`;
143
174
  let cspCache: { for: string | null; value: string } | null = null;
144
- // The exact bytes between the external bootstrap's script tags - the single source of truth
145
- // shared by the tag and the CSP hash …
146
- const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm } from '/client.js';\n${BOOTSTRAP}`;
147
- // The exact bytes between the module script's tags - the single source of truth shared by
148
- // the tag and the CSP hash, so the policy can never drift from what actually ships.
175
+ const EXTERNAL_BOOTSTRAP = `\nimport { start, prefetch, postForm, prefetchStats } from '/client.js';\n${BOOTSTRAP}`;
149
176
  function inlineScript(client: string): string {
150
177
  return `\n${client}\n${BOOTSTRAP}`;
151
178
  }
@@ -184,8 +211,6 @@ export function mintNonce(): string {
184
211
  export function securityHeaders(client: string | null, nonce = ''): Record<string, string> {
185
212
  if (nonce) return { 'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic'; ${CSP_TAIL}` };
186
213
  if (!cspCache || cspCache.for !== client) {
187
- // client === null: split mode (or the edge without a built client.js). 'self' covers
188
- // the external modules and chunks, the hash covers the inline bootstrap …
189
214
  const scriptSrc = client
190
215
  ? `'sha256-${createHash('sha256').update(inlineScript(client), 'utf-8').digest('base64')}'`
191
216
  : `'self' 'sha256-${createHash('sha256').update(EXTERNAL_BOOTSTRAP, 'utf-8').digest('base64')}'`;
@@ -197,12 +222,8 @@ export function securityHeaders(client: string | null, nonce = ''): Record<strin
197
222
  return { 'Content-Security-Policy': cspCache.value };
198
223
  }
199
224
 
200
- // An inline SVG favicon (the rose). Without it every browser requests /favicon.ico on every
201
- // page load - one wasted request per visit.
202
225
  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==">';
203
226
 
204
- // Shared by the buffered shell and the streaming shell-open so both produce
205
- // byte-identical static markup.
206
227
  const STYLES = `
207
228
  body { font-family: system-ui, sans-serif; margin: 0; padding: 2rem; }
208
229
  button { padding: 0.5rem 1rem; font-size: 1rem; margin-right: 0.5rem; }
@@ -222,8 +243,6 @@ const STYLES = `
222
243
  ::view-transition-old(root), ::view-transition-new(root) { animation-duration: .18s; }
223
244
  `;
224
245
 
225
- // The stylesheet ships inside every document, so its source formatting is a tax on every
226
- // route: collapse whitespace outside strings once, here.
227
246
  const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g, (m) =>
228
247
  m[0] === '"' || m[0] === "'" ? m : m.replace(/\s+/g, ' ').replace(/\s*([:;{},])\s*/g, '$1').trim()
229
248
  ).trim();
@@ -232,12 +251,25 @@ const STYLES_MIN = STYLES.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^"']+/g,
232
251
  * Merge the route chain's <head> blocks (document order: page first, then its
233
252
  * layouts) into one clean <head> fragment. First occurrence wins per key, so a
234
253
  * page overrides its layouts - matching the client's reverse-order applyHead.
254
+ *
255
+ * Bug report 2026.9.22 11:46: the keyed whitelist used to be title plus
256
+ * meta/link/base and NOTHING else, so a `<style>` block, a
257
+ * `<script type="application/ld+json">` data block and a `<noscript>`
258
+ * fallback were dropped here in silence - the compiler collected them, the
259
+ * merge threw them away, and a CMS theme system had no way to ship its
260
+ * per-request CSS. Every head element now passes through: the keyed
261
+ * singletons keep their name/property/rel/charset identity, and everything
262
+ * else is keyed by id when it has one and by tag+position when it does not,
263
+ * so two layouts' <style> blocks coexist and a page still overrides its
264
+ * layout's. Passthrough elements carry HEAD_ATTR too (the attribute the
265
+ * runtime manages) so a client-side navigation replaces or drops them like
266
+ * any other managed element instead of leaking the previous route's CSS
267
+ * into every route visited after it.
235
268
  */
236
269
  function mergeHeadBlocks(blocks: string[]): string {
237
270
  const byKey = new Map<string, string>();
238
271
  const order: string[] = [];
239
- // first occurrence wins: blocks arrive page-first (a page renders inside its
240
- // layouts' <slot/>), so the page's title/meta override the layouts'
272
+ const positional = new Map<string, number>();
241
273
  const put = (key: string, html: string) => {
242
274
  if (!byKey.has(key)) {
243
275
  byKey.set(key, html);
@@ -245,15 +277,21 @@ function mergeHeadBlocks(blocks: string[]): string {
245
277
  }
246
278
  };
247
279
  for (const block of blocks) {
248
- // title carries content, so it needs its own pattern
249
280
  for (const m of block.matchAll(/<title[^>]*>[\s\S]*?<\/title>/gi)) put('title', m[0]);
250
- for (const m of block.matchAll(/<(meta|link|base)((?:\s+[\w-]+(?:="[^"]*")?)*)\s*\/?>/gi)) {
281
+ for (const m of block.matchAll(/<(\w+)((?:\s+[\w:-]+(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(?:\/>|>([\s\S]*?)<\/\1\s*>|>)/gi)) {
251
282
  const tag = m[1].toLowerCase();
252
- const keyMatch = m[2].match(/\s(?:name|property|rel|charset)="([^"]*)"/i);
253
- const key = keyMatch ? `${tag}:${keyMatch[1]}` : tag;
254
- // keyed tags carry their key (must match HEAD_ATTR in the runtime) so the client
255
- // adopts these SSR-injected elements in place on the first navigation instead of …
256
- const marked = keyMatch ? m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`) : m[0];
283
+ if (tag === 'title') continue;
284
+ const attrs = m[2];
285
+ const keyMatch = attrs.match(/\s(?:name|property|rel|charset)=(?:"([^"]*)"|'([^']*)')/i);
286
+ const idMatch = attrs.match(/\sid=(?:"([^"]*)"|'([^']*)')/i);
287
+ let key: string;
288
+ if (keyMatch) key = `${tag}:${keyMatch[1] ?? keyMatch[2]}`;
289
+ else if (idMatch) key = `${tag}:${idMatch[1] ?? idMatch[2]}`;
290
+ else {
291
+ key = `${tag}:#${positional.get(tag) ?? 0}`;
292
+ positional.set(tag, (positional.get(tag) ?? 0) + 1);
293
+ }
294
+ const marked = m[0].replace(/^<\w+/, (t) => `${t} data-rosetack-head="${key}"`);
257
295
  put(key, marked);
258
296
  }
259
297
  }
@@ -285,53 +323,63 @@ export function clientScriptTag(client: string | null, nonce = ''): string {
285
323
  * docAttrs). The streaming path flushes this string BEFORE the render, so
286
324
  * the browser gets the language metadata in the first byte.
287
325
  */
288
- export function shellOpen(styles: string = getStyles(), lang = 'en', dir = ''): string {
326
+ export function shellOpen(styles: string = getStyles(), lang = 'en', dir = '', shell = true): string {
289
327
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
328
+ const demoStyles = shell ? `\n <style>${STYLES_MIN}</style>` : '';
329
+ const appOpen = shell ? `\n <div id="app">` : '';
290
330
  return `<!DOCTYPE html>
291
331
  <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
292
332
  <head>
293
333
  <meta charset="UTF-8">
294
334
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
295
- <title>RoseTack</title>
296
- <style>${STYLES_MIN}</style>${styleTag}
335
+ <title>RoseTack</title>${demoStyles}${styleTag}
297
336
  ${FAVICON}
298
337
  </head>
299
- <body>
300
- <div id="app">`;
338
+ <body>${appOpen}`;
301
339
  }
302
340
 
303
341
  /** Build the document from an explicit client source (edge runtimes have no fs). */
304
- export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true, lang = 'en', dir = '', nonce = ''): string {
342
+ export function buildShell(ssrHtml: string, stateJson: string, client: string | null, head: string[] = [], styles: string = getStyles(), js = true, lang = 'en', dir = '', nonce = '', shell = true): string {
305
343
  const clientTag = clientScriptTag(client, nonce);
306
344
 
307
345
  const mergedHead = mergeHeadBlocks(head);
308
- // a route-provided <title> replaces the default one
346
+ const headStamped = nonce
347
+ ? mergedHead.replace(/<script\b([^>]*)>/gi, (m, attrs: string) => (/\bnonce=/.test(attrs) ? m : `<script${attrs} nonce="${nonce}">`))
348
+ : mergedHead;
349
+ let htmlAttrs = ` lang="${lang}"${dir ? ` dir="${dir}"` : ''}`;
350
+ let bodyAttrs = '';
351
+ const headClean = headStamped.replace(/<(html|body)\b([^>]*)>/gi, (_m, tag: string, attrs: string) => {
352
+ const clean = attrs.replace(/\s*data-rosetack-head="[^"]*"/, '');
353
+ if (tag === 'html') htmlAttrs = clean;
354
+ else bodyAttrs = clean;
355
+ return '';
356
+ });
309
357
  const titleTag = /<title>/i.test(mergedHead) ? '' : '<title>RoseTack</title>';
310
- // a route-provided icon replaces the inline favicon
311
358
  const iconTag = /rel=["']?icon/i.test(mergedHead) ? '' : `\n ${FAVICON}`;
312
- const headTags = mergedHead ? `\n ${mergedHead}` : '';
359
+ const headTags = headClean ? `\n ${headClean}` : '';
313
360
  const styleTag = styles ? `\n <style>${styles}</style>` : '';
314
- // js=false (a route exporting csr = false): the document ends at the container - no state
315
- // script, no inlined bundle, zero JavaScript.
361
+ const stateSafe = stateJson.replace(/</g, '\\u003c');
316
362
  const jsTail = js
317
- ? `\n <script type="application/json" id="__rosetack_state">${stateJson}</script>\n ${clientTag}`
363
+ ? `\n <script type="application/json" id="__rosetack_state">${stateSafe}</script>\n ${clientTag}`
318
364
  : '';
365
+ const open = js && shell ? '<div id="app">' : '';
366
+ const close = js && shell ? '</div>' : '';
367
+ const shellStyles = js && shell ? `\n <style>${STYLES_MIN}</style>` : '';
319
368
 
320
369
  return `<!DOCTYPE html>
321
- <html lang="${lang}"${dir ? ` dir="${dir}"` : ''}>
370
+ <html${htmlAttrs}>
322
371
  <head>
323
372
  <meta charset="UTF-8">
324
373
  <meta name="viewport" content="width=device-width, initial-scale=1.0">${headTags}${iconTag}
325
- ${titleTag}
326
- <style>${STYLES_MIN}</style>${styleTag}
374
+ ${titleTag}${shellStyles}${styleTag}
327
375
  </head>
328
- <body>
329
- <div id="app">${ssrHtml}</div>${jsTail}
376
+ <body${bodyAttrs}>
377
+ ${open}${ssrHtml}${close}${jsTail}
330
378
  </body>
331
379
  </html>`;
332
380
  }
333
381
 
334
382
  /** Node entry: reads dist/client.js from disk (mtime-cached). */
335
- export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true, lang = 'en', dir = '', nonce = ''): string {
336
- return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce);
383
+ export function getHtmlShell(ssrHtml: string, stateJson: string, head: string[] = [], js = true, lang = 'en', dir = '', nonce = '', shell = true): string {
384
+ return buildShell(ssrHtml, stateJson, getClientSource(), head, getStyles(), js, lang, dir, nonce, shell);
337
385
  }
package/src/cli/test.ts CHANGED
@@ -1,37 +1,4 @@
1
- /**
2
- * rosetack/test - the public testing surface.
3
- *
4
- * The framework's own suites proved the pipeline; this module lets a PROJECT
5
- * prove its own. Two halves, one entry point:
6
- *
7
- * const c = await test('src/components/Counter.rose', { props: { start: 5 } });
8
- * const r = await c.get(); // the server half: rendered HTML + state
9
- * r.html.includes('5');
10
- * const after = await c.post({ name: 'Ada' }); // a server action / form POST
11
- *
12
- * const dom = new JSDOM('<!DOCTYPE html><html><body><div id="app"></div></body></html>');
13
- * const p = await test('src/pages/sign.rose', { dom }).then((a) => a.mount());
14
- * await p.click('button'); // a real event -> fine-grained patch
15
- * p.text('p');
16
- * p.requestCount(); // the zero-request story, asserted
17
- *
18
- * The design rule: NO second implementation of anything. The
19
- * harness compiles a throwaway project with the SAME compiler the app uses,
20
- * then drives the SAME server bundle and client bundle the app ships. There
21
- * is nothing here that can pass while the real app fails, because there is
22
- * nothing here that is not the real app.
23
- *
24
- * A `.rose` component is not independently renderable in rosetack's
25
- * architecture - it compiles INTO the app's bundles - so a component test
26
- * builds the project it lives in with one synthesized page that renders it
27
- * with the given props. That page is the only thing added; every other route
28
- * of the app still exists, so navigation and api routes are testable too.
29
- *
30
- * Vitest/jest compatible: every entry point is an async function returning
31
- * plain data. No test-runner dependency, no globals beyond the DOM ones a
32
- * browser has (and those are grafted from the window `mount()` runs in, so
33
- * jsdom, happy-dom and vitest's jsdom environment all work unchanged).
34
- */
1
+
35
2
 
36
3
  import * as fs from 'fs';
37
4
  import * as os from 'os';
@@ -55,6 +22,8 @@ export interface TestResult {
55
22
  state: Record<string, unknown>;
56
23
  head: string[];
57
24
  csr?: boolean;
25
+ /** the route exported `shell = false`: the document keeps the bundle but drops the #app wrapper + STYLES_MIN */
26
+ shell?: boolean;
58
27
  lang: string;
59
28
  dir: string;
60
29
  /** the complete document, byte-identical to what the servers send */
@@ -99,12 +68,7 @@ export interface TestOptions {
99
68
  dir?: string;
100
69
  /** keep the built dir and print its path, for inspecting the artifacts */
101
70
  keep?: boolean;
102
- /**
103
- * A DOM for `mount()`: a jsdom `new JSDOM()` instance or its `.window`
104
- * (happy-dom's Window works too - anything with `.window`). Omit it under
105
- * a jsdom test environment (vitest's `environment: 'jsdom'`), where the
106
- * globals are already there.
107
- */
71
+
108
72
  dom?: unknown;
109
73
  }
110
74
 
@@ -123,8 +87,6 @@ export interface TestApp {
123
87
  mount(req?: TestRequest): Promise<TestHandle>;
124
88
  }
125
89
 
126
- // The globals a browser has and a Node test process does not. `mount()` grafts them from
127
- // the document it parses, exactly like the repo's own client suite does …
128
90
  const GRAFTED = ['document', 'Node', 'NodeFilter', 'FormData', 'DOMParser', 'location', 'fetch', 'Event', 'CustomEvent', 'MutationObserver', 'requestAnimationFrame'] as const;
129
91
 
130
92
  /** Absolute path of the project root that owns `file` (the dir holding src/pages). */
@@ -183,8 +145,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
183
145
  const rel = path.relative(root, target).replace(/\\/g, '/');
184
146
  const isComponent = rel.startsWith('src/components/');
185
147
 
186
- // The fixture project: the app's own sources (so every route, component, config and
187
- // public asset resolves exactly as it does for the app) plus, for a component target …
188
148
  const dir = opts.dir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'rosetack-test-'));
189
149
  for (const item of ['src', 'public']) {
190
150
  const from = path.join(root, item);
@@ -209,8 +169,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
209
169
  const outDir = path.join(dir, 'dist');
210
170
  await buildProject(dir, outDir);
211
171
 
212
- // The two bundles the app ships - the same ones the servers run. Imported once per test()
213
- // call: the server module holds module state …
214
172
  const serverUrl = pathToFileURL(path.join(outDir, 'server.js')).href;
215
173
  const clientUrl = pathToFileURL(path.join(outDir, 'client.js')).href;
216
174
  const mod = await import(serverUrl);
@@ -222,8 +180,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
222
180
 
223
181
  if (opts.keep) console.log(`rosetack/test: built ${target} -> ${outDir}`);
224
182
  if (!opts.dir && !opts.keep) {
225
- // a temp fixture is not the developer's to clean up by hand. On exit, not now: the
226
- // locale packs and chunks below are read from disk while the mounted half runs …
227
183
  process.once('exit', () => {
228
184
  try {
229
185
  fs.rmSync(dir, { recursive: true, force: true });
@@ -238,9 +194,10 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
238
194
  state: page.state ? JSON.parse(page.state) : {},
239
195
  head: page.head ?? [],
240
196
  csr: page.csr,
197
+ shell: page.shell,
241
198
  lang: page.lang ?? 'en',
242
199
  dir: page.dir ?? '',
243
- document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? 'en', page.dir ?? ''),
200
+ document: buildShell(page.html, page.state, clientSource, page.head ?? [], styles, page.csr !== false, page.lang ?? 'en', page.dir ?? '', '', page.shell !== false),
244
201
  redirect,
245
202
  });
246
203
 
@@ -248,15 +205,10 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
248
205
  const toRequest = (pathname: string, req: TestRequest = {}, body?: FormData) => {
249
206
  const headers = new Headers(req.headers ?? {});
250
207
  for (const [k, v] of Object.entries(req.cookies ?? {})) headers.append('cookie', `${k}=${v}`);
251
- return new Request(`http://localhost${pathname}`, { method: body ? 'POST' : 'GET', headers, body });
208
+ return new Request(`http://localhost${pathname}`, { method: req.method ?? 'GET', headers, body: body ?? undefined });
252
209
  };
253
210
 
254
- /**
255
- * One request through the real server pipeline: middleware first (it can
256
- * short-circuit - a redirect, an auth wall), then the render. This is the
257
- * order the servers use, so a middleware's effect is visible here or it is
258
- * not visible at all.
259
- */
211
+ // One request through the real server pipeline: middleware first (it can short-circuit - a redirect, an auth wall), then the render.
260
212
  const request = async (pathname: string, req: TestRequest, body?: FormData): Promise<TestResult> => {
261
213
  if (mod.middleware) {
262
214
  const mw = await mod.runMiddleware(toRequest(pathname, req, body), body);
@@ -266,15 +218,10 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
266
218
  return result(page);
267
219
  };
268
220
 
269
- // The client half's request counter and fetch proxy: the bundle POSTs to
270
- // location.pathname like a browser, and the answer is the same document the Node server
271
- // would send …
272
221
  let requests = 0;
273
222
  let currentRoute = route;
274
223
 
275
224
  const mount = async (req: TestRequest = {}): Promise<TestHandle> => {
276
- // The window the bundle will live in: the caller's DOM, or the ambient one under a
277
- // jsdom test environment.
278
225
  const win = ((opts.dom as any)?.window ?? opts.dom ?? globalThis) as any;
279
226
  if (!win?.document || !win?.DOMParser) {
280
227
  throw new Error('rosetack/test: mount() needs a DOM. Pass one - test("src/components/Counter.rose", { dom: new JSDOM() }) - or run under a jsdom environment.');
@@ -283,8 +230,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
283
230
 
284
231
  const doc = win.document;
285
232
  const app = doc.getElementById('app') ?? doc.body;
286
- // reuse the state element across mounts of the same document: a second one would lose
287
- // getElementById's first-match race and the client would resume the FIRST mount's state
288
233
  let stateEl = doc.getElementById('__rosetack_state');
289
234
  if (!stateEl) {
290
235
  stateEl = doc.createElement('script');
@@ -302,8 +247,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
302
247
  (globalThis as any).location = { pathname: currentRoute, href: `http://localhost${currentRoute}` };
303
248
  (globalThis as any).fetch = async (url: string | URL, init: any) => {
304
249
  const pathname = String(url).startsWith('http') ? new URL(String(url)).pathname : String(url);
305
- // an i18n route's runtime language pack: the same request the browser
306
- // makes, served from the file this build wrote
307
250
  if (pathname.startsWith('/locales/') && pathname.endsWith('.json')) {
308
251
  const file = path.join(outDir, pathname.slice(1));
309
252
  if (!fs.existsSync(file)) return { ok: false, json: async () => ({}) };
@@ -360,8 +303,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
360
303
  },
361
304
  requestCount: () => requests,
362
305
  };
363
- // The graft is intentional and documented: a second mount() re-grafts
364
- // over the first. `restore` puts the process back the way it was.
365
306
  (handle as any).restore = () => { for (const [k, v] of saved) (globalThis as any)[k] = v; };
366
307
  return handle;
367
308
  };
@@ -377,8 +318,6 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
377
318
  return request(pathname, req, body);
378
319
  },
379
320
  api: async (method: string, pathname: string, req: TestRequest = {}) => {
380
- // the middleware runs first here too - the servers do, and an api
381
- // route's auth usually lives in it
382
321
  if (mod.middleware) {
383
322
  const mw = await mod.runMiddleware(toRequest(pathname, req));
384
323
  if (mw) return { status: mw.status, body: await mw.text(), headers: { location: mw.headers.get('location') ?? '' } };
@@ -388,7 +327,7 @@ export async function test(file: string, opts: TestOptions = {}): Promise<TestAp
388
327
  let body: unknown = text;
389
328
  try {
390
329
  body = JSON.parse(text);
391
- } catch { /* not JSON: hand back the raw text */ }
330
+ } catch { }
392
331
  const headers: Record<string, string> = {};
393
332
  res.headers.forEach((v: string, k: string) => { headers[k] = v; });
394
333
  return { status: res.status, body, headers };