clarusjs 0.2.0 → 0.4.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 (47) hide show
  1. package/README.md +5 -15
  2. package/dist/check/generate.d.ts +11 -0
  3. package/dist/check/generate.js +164 -0
  4. package/dist/cli/check.d.ts +17 -0
  5. package/dist/cli/check.js +91 -0
  6. package/dist/cli/explain.d.ts +9 -0
  7. package/dist/cli/explain.js +46 -0
  8. package/dist/cli/index.d.ts +2 -0
  9. package/dist/cli/index.js +38 -0
  10. package/dist/compiler/emit-client.js +90 -17
  11. package/dist/compiler/emit-server.js +32 -24
  12. package/dist/compiler/errors.d.ts +1 -1
  13. package/dist/compiler/errors.js +1 -1
  14. package/dist/compiler/html-expr.d.ts +29 -0
  15. package/dist/compiler/html-expr.js +85 -0
  16. package/dist/compiler/ir.d.ts +40 -1
  17. package/dist/compiler/ir.js +155 -33
  18. package/dist/compiler/parse.d.ts +56 -0
  19. package/dist/compiler/parse.js +244 -11
  20. package/dist/compiler/script.d.ts +21 -2
  21. package/dist/compiler/script.js +67 -6
  22. package/dist/runtime/attrs.d.ts +5 -0
  23. package/dist/runtime/attrs.js +56 -0
  24. package/dist/runtime/dom.d.ts +61 -5
  25. package/dist/runtime/dom.js +257 -17
  26. package/dist/runtime/html.d.ts +10 -0
  27. package/dist/runtime/html.js +30 -0
  28. package/dist/runtime/index.d.ts +4 -2
  29. package/dist/runtime/index.js +4 -2
  30. package/dist/runtime/loader.d.ts +7 -2
  31. package/dist/runtime/loader.js +125 -28
  32. package/dist/runtime/serialize.d.ts +8 -0
  33. package/dist/runtime/serialize.js +93 -0
  34. package/dist/runtime/server.d.ts +9 -4
  35. package/dist/runtime/server.js +13 -24
  36. package/dist/runtime/signals.d.ts +12 -0
  37. package/dist/runtime/signals.js +44 -1
  38. package/dist/server/handler.d.ts +1 -1
  39. package/dist/server/handler.js +2 -2
  40. package/dist/server/manifest.d.ts +4 -0
  41. package/dist/server/manifest.js +17 -0
  42. package/dist/vite/build.d.ts +8 -4
  43. package/dist/vite/build.js +16 -9
  44. package/dist/vite/manifest.d.ts +38 -0
  45. package/dist/vite/manifest.js +69 -0
  46. package/dist/vite/plugin.js +49 -10
  47. package/package.json +10 -2
@@ -1,21 +1,37 @@
1
- // .clarus source → syntax tree. Pure: no file system, no JS parsing (expressions are kept as raw strings).
1
+ // .tscl source → syntax tree. Pure: no file system, no JS parsing (expressions are kept as raw strings).
2
2
  import { ClarusError } from './errors.js';
3
3
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
4
- const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?\s*$/;
4
+ const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?\s*$/d;
5
+ const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
6
+ const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
5
7
  const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
6
8
  export function parse(source, file) {
7
- const out = { inputs: [], imports: [], nodes: [] };
9
+ const out = { inputs: [], imports: [], typeImports: [], dataImports: [], nodes: [] };
8
10
  let i = 0;
9
11
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
10
12
  const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
11
13
  function directive() {
12
14
  const end = source.indexOf('\n', i) === -1 ? source.length : source.indexOf('\n', i);
15
+ const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
13
16
  const line = source.slice(i, end).trim();
14
17
  let m;
15
- if ((m = line.match(INPUT_RE)))
16
- out.inputs.push({ name: m[1], type: m[2].trim(), default: m[3], start: i });
17
- else if ((m = line.match(IMPORT_RE)))
18
- out.imports.push({ name: m[1], from: m[3], start: i });
18
+ if ((m = INPUT_RE.exec(line))) {
19
+ const at = (group) => lineStart + m.indices[group][0];
20
+ out.inputs.push({ name: m[1], type: m[2].trim(), default: m[3], start: i, nameStart: at(1), typeStart: at(2), ...(m[3] ? { defaultStart: at(3) } : {}) });
21
+ }
22
+ else if ((m = IMPORT_TYPE_RE.exec(line))) {
23
+ out.typeImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
24
+ }
25
+ else if ((m = DATA_IMPORT_RE.exec(line))) {
26
+ out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
27
+ }
28
+ else if ((m = line.match(IMPORT_RE))) {
29
+ // A default import of a .tscl file is a component; of anything else, data.
30
+ if (m[3].endsWith('.tscl'))
31
+ out.imports.push({ name: m[1], from: m[3], start: i });
32
+ else
33
+ out.dataImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + line.indexOf(m[1], 7) });
34
+ }
19
35
  else
20
36
  fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
21
37
  i = end;
@@ -53,9 +69,30 @@ export function parse(source, file) {
53
69
  list.push({ kind: 'prop', name: name.slice(1, -1), expr: value.trim(), start });
54
70
  }
55
71
  else {
56
- if (typeof value === 'string' && value.includes('{{'))
57
- fail('interpolation in attributes is not supported yet; use a literal value', start);
58
- list.push({ kind: 'static', name, value, start });
72
+ if (typeof value === 'string' && value.includes('{{')) {
73
+ // Split into literal text and {{ expr }} parts; valueStart is the offset of the value's first character.
74
+ const valueStart = start + name.length + 2;
75
+ const parts = [];
76
+ let at = 0;
77
+ while (at < value.length) {
78
+ const open = value.indexOf('{{', at);
79
+ if (open === -1) {
80
+ parts.push(value.slice(at));
81
+ break;
82
+ }
83
+ if (open > at)
84
+ parts.push(value.slice(at, open));
85
+ const close = value.indexOf('}}', open + 2);
86
+ if (close === -1)
87
+ fail('unclosed {{ in attribute value', valueStart + open);
88
+ parts.push({ expr: value.slice(open + 2, close).trim(), start: valueStart + open });
89
+ at = close + 2;
90
+ }
91
+ list.push({ kind: 'interp', name, parts, start });
92
+ }
93
+ else {
94
+ list.push({ kind: 'static', name, value, start });
95
+ }
59
96
  }
60
97
  }
61
98
  }
@@ -97,6 +134,158 @@ export function parse(source, file) {
97
134
  return -1;
98
135
  }
99
136
  // Parse children until `</parent>` (or end of input at top level).
137
+ // A parenthesised JS condition after `@if` / `@else if`, skipping strings and nested parentheses.
138
+ function condition(keyword) {
139
+ while (/\s/.test(source[i] ?? ''))
140
+ i++;
141
+ if (source[i] !== '(')
142
+ fail(`expected ( after ${keyword}`, i);
143
+ const open = i;
144
+ let depth = 0;
145
+ for (; i < source.length; i++) {
146
+ const c = source[i];
147
+ if (c === '"' || c === "'" || c === '`') {
148
+ for (i++; i < source.length && source[i] !== c; i++)
149
+ if (source[i] === '\\')
150
+ i++;
151
+ }
152
+ else if (c === '(')
153
+ depth++;
154
+ else if (c === ')' && --depth === 0) {
155
+ i++;
156
+ return { cond: source.slice(open + 1, i - 1).trim(), condStart: open + 1 };
157
+ }
158
+ }
159
+ return fail(`unclosed ( after ${keyword}`, open);
160
+ }
161
+ // @if (a) { … } @else if (b) { … } @else { … }
162
+ function ifBlock() {
163
+ const start = i;
164
+ i += 3;
165
+ const branches = [];
166
+ let next = condition('@if');
167
+ while (next) {
168
+ while (/\s/.test(source[i] ?? ''))
169
+ i++;
170
+ if (source[i] !== '{')
171
+ fail('expected { to open the block', i);
172
+ i++;
173
+ branches.push({ ...next, children: children({ tag: '@if', start, block: true }) });
174
+ if (next.cond === null)
175
+ break; // @else is last
176
+ const save = i;
177
+ while (/\s/.test(source[i] ?? ''))
178
+ i++;
179
+ if (!source.startsWith('@else', i)) {
180
+ i = save;
181
+ break;
182
+ }
183
+ i += 5;
184
+ while (/\s/.test(source[i] ?? ''))
185
+ i++;
186
+ if (/^if[\s(]/.test(source.slice(i, i + 3))) {
187
+ i += 2;
188
+ next = condition('@else if');
189
+ }
190
+ else
191
+ next = { cond: null, condStart: i };
192
+ }
193
+ return { type: 'if', branches, start };
194
+ }
195
+ // Split at top-level ';' (outside strings and brackets).
196
+ /** Top-level `;` clauses, trimmed, each with its offset in `text`. */
197
+ function splitClauses(text) {
198
+ const parts = [];
199
+ const push = (from, to) => {
200
+ const raw = text.slice(from, to);
201
+ if (raw.trim())
202
+ parts.push({ text: raw.trim(), start: from + raw.length - raw.trimStart().length });
203
+ };
204
+ let depth = 0;
205
+ let from = 0;
206
+ for (let j = 0; j < text.length; j++) {
207
+ const c = text[j];
208
+ if (c === '"' || c === "'" || c === '`') {
209
+ for (j++; j < text.length && text[j] !== c; j++)
210
+ if (text[j] === '\\')
211
+ j++;
212
+ }
213
+ else if ('([{'.includes(c))
214
+ depth++;
215
+ else if (')]}'.includes(c))
216
+ depth--;
217
+ else if (c === ';' && depth === 0) {
218
+ push(from, j);
219
+ from = j + 1;
220
+ }
221
+ }
222
+ push(from, text.length);
223
+ return parts;
224
+ }
225
+ // @for (item of list; track key) { … } @empty { … }
226
+ function forBlock() {
227
+ const start = i;
228
+ i += 4;
229
+ const { cond: head, condStart: headStart } = condition('@for');
230
+ // Where `head` (trimmed) starts in the source, so every part below gets its exact offset.
231
+ let at = headStart;
232
+ while (/\s/.test(source[at] ?? ''))
233
+ at++;
234
+ const [first = { text: '', start: 0 }, ...rest] = splitClauses(head);
235
+ const m = /^([\s\S]+?)\s+of\s+([\s\S]+)$/d.exec(first.text);
236
+ if (!m)
237
+ fail('expected "item of list" in @for', headStart);
238
+ if (!/^[A-Za-z_$][\w$]*$/.test(m[1].trim()))
239
+ fail('the @for item must be a simple name', headStart);
240
+ const itemStart = at + first.start + m.indices[1][0];
241
+ const listStart = at + first.start + m.indices[2][0];
242
+ let track = null;
243
+ let trackStart = -1;
244
+ for (const clause of rest) {
245
+ const t = /^track\s+([\s\S]+)$/d.exec(clause.text);
246
+ if (!t)
247
+ fail(`unknown @for clause "${clause.text}"`, headStart);
248
+ track = t[1].trim();
249
+ trackStart = at + clause.start + t.indices[1][0];
250
+ }
251
+ while (/\s/.test(source[i] ?? ''))
252
+ i++;
253
+ if (source[i] !== '{')
254
+ fail('expected { to open the block', i);
255
+ i++;
256
+ const body = children({ tag: '@for', start, block: true });
257
+ let empty = null;
258
+ const save = i;
259
+ while (/\s/.test(source[i] ?? ''))
260
+ i++;
261
+ if (/^@empty[\s{]/.test(source.slice(i, i + 7))) {
262
+ i += 6;
263
+ while (/\s/.test(source[i] ?? ''))
264
+ i++;
265
+ if (source[i] !== '{')
266
+ fail('expected { to open the block', i);
267
+ i++;
268
+ empty = children({ tag: '@empty', start, block: true });
269
+ }
270
+ else
271
+ i = save;
272
+ return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, children: body, empty, start };
273
+ }
274
+ // @slot('name') { … }: content for a component's named slot.
275
+ function fillBlock() {
276
+ const start = i;
277
+ i += 5;
278
+ const { cond } = condition('@slot');
279
+ const m = /^(['"])([\w-]+)\1$/.exec(cond);
280
+ if (!m)
281
+ fail(`@slot needs a quoted name, like @slot('aside')`, start);
282
+ while (/\s/.test(source[i] ?? ''))
283
+ i++;
284
+ if (source[i] !== '{')
285
+ fail('expected { to open the block', i);
286
+ i++;
287
+ return { type: 'fill', name: m[2], children: children({ tag: '@slot', start, block: true }), start };
288
+ }
100
289
  function children(parent) {
101
290
  const nodes = [];
102
291
  let text = '';
@@ -122,6 +311,26 @@ export function parse(source, file) {
122
311
  text += source.slice(i, end + 3); // kept verbatim as static text: no tags, no holes inside
123
312
  i = end + 3;
124
313
  }
314
+ else if (/^@if[\s(]/.test(source.slice(i, i + 4))) {
315
+ flush();
316
+ nodes.push(ifBlock());
317
+ textStart = i;
318
+ }
319
+ else if (/^@for[\s(]/.test(source.slice(i, i + 5))) {
320
+ flush();
321
+ nodes.push(forBlock());
322
+ textStart = i;
323
+ }
324
+ else if (/^@slot[\s(]/.test(source.slice(i, i + 6))) {
325
+ flush();
326
+ nodes.push(fillBlock());
327
+ textStart = i;
328
+ }
329
+ else if (parent?.block && source[i] === '}') {
330
+ flush();
331
+ i++;
332
+ return nodes;
333
+ }
125
334
  else if (!parent && source[i] === '@' && atLineStart(i)) {
126
335
  flush();
127
336
  directive();
@@ -169,6 +378,23 @@ export function parse(source, file) {
169
378
  out.script = { code: source.slice(i, end), start: i };
170
379
  i = end + '</script>'.length;
171
380
  }
381
+ else if (list.some((a) => a.name === 'verbatim')) {
382
+ // Everything up to </tag> is text: no holes, tags or directives.
383
+ const attr = list.find((a) => a.name === 'verbatim');
384
+ if (attr.kind !== 'static' || attr.value !== true)
385
+ fail('verbatim takes no value', attr.start);
386
+ if (out.imports.some((imp) => imp.name === tag))
387
+ fail('verbatim only works on HTML elements, not components', attr.start);
388
+ let kids = [];
389
+ if (!selfClosing && !VOID.has(tag)) {
390
+ const close = source.indexOf(`</${tag}>`, i);
391
+ if (close === -1)
392
+ fail(`unclosed <${tag} verbatim>`, start);
393
+ kids = [{ type: 'raw', value: source.slice(i, close), start: i }];
394
+ i = close + `</${tag}>`.length;
395
+ }
396
+ nodes.push({ type: 'element', tag, attrs: list.filter((a) => a !== attr), children: kids, start });
397
+ }
172
398
  else {
173
399
  const kids = selfClosing || VOID.has(tag) ? [] : children({ tag, start });
174
400
  nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
@@ -180,10 +406,17 @@ export function parse(source, file) {
180
406
  }
181
407
  }
182
408
  if (parent)
183
- fail(`unclosed <${parent.tag}>`, parent.start);
409
+ fail(parent.block ? `unclosed ${parent.tag} block` : `unclosed <${parent.tag}>`, parent.start);
184
410
  flush();
185
411
  return nodes;
186
412
  }
187
413
  out.nodes = children();
188
414
  return out;
189
415
  }
416
+ /** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
417
+ export function importNames(clause) {
418
+ if (!clause.startsWith('{'))
419
+ return [clause];
420
+ return clause.slice(1, -1).split(',').map((p) => p.trim()).filter((p) => p && !p.startsWith('type '))
421
+ .map((p) => p.split(/\s+as\s+/).pop().trim());
422
+ }
@@ -1,4 +1,4 @@
1
- export type Signals = Map<string, 'state' | 'derived'>;
1
+ export type Signals = Map<string, 'state' | 'derived' | 'shared'>;
2
2
  /** Throw a located ClarusError unless `expr` is exactly one JS expression. */
3
3
  export declare function checkExpr(expr: string, file: string, source: string, offset: number): void;
4
4
  /** Throw a located ClarusError unless `code` parses as statements (event handlers may hold several). */
@@ -9,8 +9,27 @@ export declare function templateRanges(code: string): [number, number][];
9
9
  export declare function wrapExpr(expr: string): string;
10
10
  /** Names declared at the top level of <script>: variables, functions, classes. */
11
11
  export declare function scriptNames(code: string): Set<string>;
12
+ /**
13
+ * Take the `import` statements out of a <script> so they can go at the top of the compiled modules. Their text is
14
+ * blanked in the body (same length, newlines kept), so positions in the rest of the script don't move.
15
+ * Island scripts are bundled for the browser, so `node:` imports are a build error.
16
+ */
17
+ /** Import statements (text and offset in `code`), and the body with them blanked out. */
18
+ export declare function splitImports(code: string, file: string, source: string, offset: number): {
19
+ imports: {
20
+ text: string;
21
+ start: number;
22
+ }[];
23
+ body: string;
24
+ };
12
25
  export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
13
- export declare function rewriteClient(code: string, signals: Signals): string;
26
+ /**
27
+ * Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
28
+ * starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
29
+ */
30
+ export declare function rewriteClient(code: string, signals: Signals, options?: {
31
+ stateFromServer?: boolean;
32
+ }): string;
14
33
  export declare function rewriteClientExpr(expr: string, signals: Signals): string;
15
34
  export declare function rewriteServer(code: string): string;
16
35
  export declare function referencesSignal(expr: string, signals: Signals): boolean;
@@ -181,19 +181,56 @@ export function scriptNames(code) {
181
181
  else if ((stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration') && stmt.id) {
182
182
  names.add(stmt.id.name);
183
183
  }
184
+ else if (stmt.type === 'ImportDeclaration') {
185
+ for (const spec of stmt.specifiers)
186
+ names.add(spec.local.name);
187
+ }
184
188
  }
185
189
  return names;
186
190
  }
187
191
  function signalCall(init) {
188
192
  if (init?.type !== 'CallExpression' || init.callee.type !== 'Identifier')
189
193
  return undefined;
190
- return init.callee.name === 'state' || init.callee.name === 'derived' ? init.callee.name : undefined;
194
+ const name = init.callee.name;
195
+ return name === 'state' || name === 'derived' || name === 'shared' ? name : undefined;
191
196
  }
197
+ /**
198
+ * Take the `import` statements out of a <script> so they can go at the top of the compiled modules. Their text is
199
+ * blanked in the body (same length, newlines kept), so positions in the rest of the script don't move.
200
+ * Island scripts are bundled for the browser, so `node:` imports are a build error.
201
+ */
202
+ /** Import statements (text and offset in `code`), and the body with them blanked out. */
203
+ export function splitImports(code, file, source, offset) {
204
+ const imports = [];
205
+ let body = code;
206
+ for (const stmt of parseScript(code, file, source, offset).body) {
207
+ if (stmt.type !== 'ImportDeclaration')
208
+ continue;
209
+ const from = String(stmt.source.value);
210
+ if (from.startsWith('node:')) {
211
+ throw new ClarusError(`\`${from}\` can't be imported in an island script: the script is bundled for the browser`, file, source, offset + stmt.start);
212
+ }
213
+ imports.push({ text: code.slice(stmt.start, stmt.end), start: stmt.start });
214
+ body = body.slice(0, stmt.start) + code.slice(stmt.start, stmt.end).replace(/[^\n]/g, ' ') + body.slice(stmt.end);
215
+ }
216
+ return { imports, body };
217
+ }
218
+ // Globals that only exist on a server runtime. An island's script also runs in the browser and its state() values
219
+ // are written into the page, so reading these would leak server data (or simply fail in the browser).
220
+ const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
192
221
  export function analyzeScript(code, file, source, offset) {
193
222
  const signals = new Map();
194
- for (const stmt of parseScript(code, file, source, offset).body) {
195
- if (stmt.type === 'ImportDeclaration' || stmt.type.startsWith('Export')) {
196
- throw new ClarusError('imports in <script> are not supported yet', file, source, offset + stmt.start);
223
+ const ast = parseScript(code, file, source, offset);
224
+ const declared = scriptNames(code);
225
+ print(ast, code, (node, parent, key) => {
226
+ if (node.type === 'Identifier' && SERVER_GLOBALS.has(node.name) && !declared.has(node.name) && !isBinding(parent, key)) {
227
+ throw new ClarusError(`\`${node.name}\` is server-only: an island's script also runs in the browser, and its state and props are sent to the browser in the page`, file, source, offset + node.start);
228
+ }
229
+ return undefined;
230
+ });
231
+ for (const stmt of ast.body) {
232
+ if (stmt.type.startsWith('Export')) {
233
+ throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
197
234
  }
198
235
  if (stmt.type !== 'VariableDeclaration')
199
236
  continue;
@@ -247,9 +284,29 @@ function clientHook(code, signals, entered = new WeakSet()) {
247
284
  };
248
285
  return hook;
249
286
  }
250
- export function rewriteClient(code, signals) {
287
+ /**
288
+ * Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
289
+ * starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
290
+ */
291
+ export function rewriteClient(code, signals, options = {}) {
251
292
  const ast = parseScript(code);
252
- return code.slice(0, ast.start) + print(ast, code, clientHook(code, signals)) + code.slice(ast.end);
293
+ const hook = clientHook(code, signals);
294
+ if (!options.stateFromServer)
295
+ return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
296
+ const topLevel = new Set(ast.body.filter((n) => n.type === 'VariableDeclaration').flatMap((n) => n.declarations));
297
+ const withState = (node, parent, key) => {
298
+ // `let x = state()` becomes `const x = …`; re-print with this hook so the declarators below still see it.
299
+ if (node.type === 'VariableDeclaration' && node.kind === 'let' && node.declarations.every((d) => signalCall(d.init))) {
300
+ return 'const' + print({ ...node, kind: 'const', start: node.start + 3 }, code, withState, parent, key);
301
+ }
302
+ if (topLevel.has(node) && node.id.type === 'Identifier' && signals.get(node.id.name) === 'state' && node.init?.arguments?.length) {
303
+ const name = node.id.name;
304
+ const init = print(node.init.arguments[0], code, hook);
305
+ return `${name} = state(__cl_state && ${JSON.stringify(name)} in __cl_state ? __cl_state.${name} : ${init})`;
306
+ }
307
+ return hook(node, parent, key);
308
+ };
309
+ return code.slice(0, ast.start) + print(ast, code, withState) + code.slice(ast.end);
253
310
  }
254
311
  export function rewriteClientExpr(expr, signals) {
255
312
  const ast = parseExpr(expr);
@@ -266,6 +323,10 @@ export function rewriteServer(code) {
266
323
  return `(${inner})`;
267
324
  if (node.callee.name === 'derived')
268
325
  return `(${inner})()`;
326
+ // A store's current value lives across requests on the server; render from its initial value instead, and from
327
+ // a copy, so a render that mutates it can't change what the next request sees.
328
+ if (node.callee.name === 'shared')
329
+ return `structuredClone((${inner}).initial)`;
269
330
  return undefined;
270
331
  };
271
332
  return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
@@ -0,0 +1,5 @@
1
+ export declare const UNSAFE_URL = "about:invalid#unsafe";
2
+ /**
3
+ * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
4
+ */
5
+ export declare function attrValue(name: string, value: unknown, tag?: string): string | true | null;
@@ -0,0 +1,56 @@
1
+ // Attribute values, shared by server rendering and browser updates so both apply the same rules.
2
+ // Attributes whose value is a URL.
3
+ const URL_ATTRS = new Set([
4
+ 'href', 'src', 'action', 'formaction', 'poster', 'cite', 'background', 'xlink:href',
5
+ 'data', 'codebase', 'ping', 'manifest', 'longdesc',
6
+ ]);
7
+ // SVG animation values can set an href, but only on animation elements; elsewhere these are ordinary data.
8
+ const ANIMATION_ATTRS = new Set(['to', 'from', 'values', 'by']);
9
+ const ANIMATION_ELEMENTS = new Set(['animate', 'set', 'animatemotion', 'animatetransform']);
10
+ // Attributes that load an image, where a raster data: URL is fine.
11
+ const IMAGE_ATTRS = new Set(['src', 'srcset', 'poster']);
12
+ const SAFE_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
13
+ const RASTER_DATA = /^data:image\/(png|gif|jpe?g|webp|avif|bmp);/i;
14
+ export const UNSAFE_URL = 'about:invalid#unsafe';
15
+ /**
16
+ * Allowlist: a relative URL, a safe scheme, or (for image attributes) a raster data: image.
17
+ * Browsers ignore control characters and whitespace around and inside the scheme, so the check does too.
18
+ */
19
+ function safeUrl(url, image) {
20
+ const compact = url.replace(/[\u0000- ]/g, '');
21
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(compact)?.[1]?.toLowerCase();
22
+ if (!scheme)
23
+ return true; // relative: /x, ../x, #x, ?x
24
+ if (SAFE_SCHEMES.has(scheme))
25
+ return true;
26
+ return image && RASTER_DATA.test(compact);
27
+ }
28
+ /**
29
+ * What an attribute should become: `null` removes it, `true` makes it a bare boolean attribute, a string is its value.
30
+ */
31
+ export function attrValue(name, value, tag) {
32
+ if (value === false || value == null)
33
+ return null;
34
+ if (value === true)
35
+ return true;
36
+ const s = String(value);
37
+ const n = name.toLowerCase();
38
+ // List-valued URL attributes: every entry must be safe, not just the first.
39
+ if (n === 'srcset') {
40
+ // "url 1x, url 2x"
41
+ const ok = s.split(',').every((candidate) => safeUrl(candidate.trim().split(/\s+/)[0] ?? '', true));
42
+ return ok ? s : UNSAFE_URL;
43
+ }
44
+ if (ANIMATION_ATTRS.has(n)) {
45
+ // The compiler passes the tag for these; without one, check them to stay on the safe side.
46
+ if (tag !== undefined && !ANIMATION_ELEMENTS.has(tag.toLowerCase()))
47
+ return s;
48
+ const entries = n === 'values' ? s.split(';') : [s];
49
+ return entries.every((entry) => safeUrl(entry.trim(), false)) ? s : UNSAFE_URL;
50
+ }
51
+ if (n === 'ping')
52
+ return s.split(/\s+/).filter(Boolean).every((url) => safeUrl(url, false)) ? s : UNSAFE_URL;
53
+ if (URL_ATTRS.has(n) && !safeUrl(s, IMAGE_ATTRS.has(n)))
54
+ return UNSAFE_URL;
55
+ return s;
56
+ }
@@ -1,14 +1,70 @@
1
+ import { type Signal } from './signals.ts';
1
2
  export type Hole = {
2
3
  start: Comment;
3
4
  end: Comment;
4
5
  };
5
- /** Find `<!--[N-->…<!--]-->` pairs inside `root`, skipping nested islands. Returns holes indexed by N. */
6
- export declare function holes(root: Element): Hole[];
6
+ export type Block = {
7
+ start: Comment;
8
+ end: Comment;
9
+ k: number;
10
+ };
11
+ type Range = {
12
+ start: Comment;
13
+ end: Comment;
14
+ };
15
+ export type For = Range & {
16
+ rows: Range[];
17
+ empty: Range | null;
18
+ };
19
+ /**
20
+ * Where wiring looks for its markers: a whole island, or one @for row inside it. A row template repeats its marker
21
+ * numbers once per row, so code wiring a row only looks between that row's markers.
22
+ */
23
+ export type Ctx = Element | {
24
+ root: Element;
25
+ start: Comment;
26
+ end: Comment;
27
+ };
28
+ /** Hole markers in `ctx`, by index. */
29
+ export declare function holes(ctx: Ctx): Hole[];
30
+ /** @if block markers in `ctx`, by index. */
31
+ export declare function blocks(ctx: Ctx): Block[];
32
+ /**
33
+ * An @if block. `which()` picks the branch (-1 for none). The server-rendered branch is wired in place; a change
34
+ * removes the old branch (disposing its effects and handlers), inserts the new branch's HTML and wires it.
35
+ */
36
+ export declare function block(ctx: Ctx, index: number, which: () => number, branches: {
37
+ html: () => string;
38
+ wire: () => void;
39
+ }[]): void;
40
+ /**
41
+ * A child component inside an island whose props or content read state. `html()` renders it with the current
42
+ * values; when anything it read changes, the old HTML is disposed and replaced, and `wire()` wires the island's own
43
+ * holes and events in the child's slot content again. A stateful child is remounted with its new props.
44
+ */
45
+ export declare function region(ctx: Ctx, index: number, html: () => string, wire: () => void): void;
46
+ /**
47
+ * A @for list. Rows the server rendered are adopted in place. When the list changes, rows are matched by key:
48
+ * kept rows keep their DOM nodes (moved only when out of order) and get the new item and index through their
49
+ * signals; new rows are rendered and wired; removed rows are disposed and removed. `@empty` content is shown while
50
+ * the list is empty.
51
+ */
52
+ export declare function forBlock(ctx: Ctx, index: number, list: () => unknown, keyOf: (item: any, i: number) => unknown, row: {
53
+ html: (item: any, i: number) => string;
54
+ wire: (ctx: Ctx, item: Signal<any>, index: Signal<number>) => void;
55
+ }, empty: {
56
+ html: () => string;
57
+ wire: (ctx: Ctx) => void;
58
+ } | null): void;
7
59
  /** Keep exactly one text node between the hole's markers, set to `fn()`. */
8
60
  export declare function text(hole: Hole, fn: () => unknown): void;
9
61
  /**
10
- * Register a handler for elements marked `data-cl-e="index"` inside this island.
62
+ * Register a handler for elements marked `data-cl-e="index"` inside `ctx`.
11
63
  * One listener per island per event type; it walks from the target up to the island root, running handlers
12
- * innermost first and stopping when one calls `stopPropagation()`.
64
+ * innermost first and stopping when one calls `stopPropagation()`. A handler registered for a @for row only fires
65
+ * for elements in that row.
13
66
  */
14
- export declare function on(root: Element, index: number, type: string, fn: (e: Event) => void): void;
67
+ export declare function on(ctx: Ctx, index: number, type: string, fn: (e: Event) => void): void;
68
+ /** Keep attribute `name` of the element marked `data-cl-a="index"` in `ctx` in sync with `fn()`. */
69
+ export declare function attr(ctx: Ctx, index: number, name: string, fn: () => unknown, tag?: string): void;
70
+ export {};