clarusjs 0.2.0 → 0.3.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.
- package/README.md +0 -10
- package/dist/compiler/emit-client.js +88 -17
- package/dist/compiler/emit-server.js +30 -24
- package/dist/compiler/html-expr.d.ts +29 -0
- package/dist/compiler/html-expr.js +85 -0
- package/dist/compiler/ir.d.ts +38 -0
- package/dist/compiler/ir.js +144 -32
- package/dist/compiler/parse.d.ts +34 -0
- package/dist/compiler/parse.js +199 -4
- package/dist/compiler/script.d.ts +17 -2
- package/dist/compiler/script.js +66 -6
- package/dist/runtime/attrs.d.ts +5 -0
- package/dist/runtime/attrs.js +56 -0
- package/dist/runtime/dom.d.ts +61 -5
- package/dist/runtime/dom.js +257 -17
- package/dist/runtime/html.d.ts +10 -0
- package/dist/runtime/html.js +30 -0
- package/dist/runtime/index.d.ts +4 -2
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/loader.d.ts +7 -2
- package/dist/runtime/loader.js +125 -28
- package/dist/runtime/serialize.d.ts +8 -0
- package/dist/runtime/serialize.js +93 -0
- package/dist/runtime/server.d.ts +9 -4
- package/dist/runtime/server.js +13 -24
- package/dist/runtime/signals.d.ts +12 -0
- package/dist/runtime/signals.js +44 -1
- package/dist/vite/plugin.js +30 -3
- package/package.json +1 -1
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -13,6 +13,14 @@ export type Attr = {
|
|
|
13
13
|
name: string;
|
|
14
14
|
expr: string;
|
|
15
15
|
start: number;
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'interp';
|
|
18
|
+
name: string;
|
|
19
|
+
parts: (string | {
|
|
20
|
+
expr: string;
|
|
21
|
+
start: number;
|
|
22
|
+
})[];
|
|
23
|
+
start: number;
|
|
16
24
|
};
|
|
17
25
|
export type TemplateNode = {
|
|
18
26
|
type: 'element';
|
|
@@ -28,6 +36,32 @@ export type TemplateNode = {
|
|
|
28
36
|
type: 'expr';
|
|
29
37
|
expr: string;
|
|
30
38
|
start: number;
|
|
39
|
+
} | {
|
|
40
|
+
type: 'raw';
|
|
41
|
+
value: string;
|
|
42
|
+
start: number;
|
|
43
|
+
} | {
|
|
44
|
+
type: 'if';
|
|
45
|
+
branches: {
|
|
46
|
+
cond: string | null;
|
|
47
|
+
condStart: number;
|
|
48
|
+
children: TemplateNode[];
|
|
49
|
+
}[];
|
|
50
|
+
start: number;
|
|
51
|
+
} | {
|
|
52
|
+
type: 'fill';
|
|
53
|
+
name: string;
|
|
54
|
+
children: TemplateNode[];
|
|
55
|
+
start: number;
|
|
56
|
+
} | {
|
|
57
|
+
type: 'for';
|
|
58
|
+
item: string;
|
|
59
|
+
list: string;
|
|
60
|
+
track: string | null;
|
|
61
|
+
headStart: number;
|
|
62
|
+
children: TemplateNode[];
|
|
63
|
+
empty: TemplateNode[] | null;
|
|
64
|
+
start: number;
|
|
31
65
|
};
|
|
32
66
|
export type InputDecl = {
|
|
33
67
|
name: string;
|
package/dist/compiler/parse.js
CHANGED
|
@@ -53,9 +53,30 @@ export function parse(source, file) {
|
|
|
53
53
|
list.push({ kind: 'prop', name: name.slice(1, -1), expr: value.trim(), start });
|
|
54
54
|
}
|
|
55
55
|
else {
|
|
56
|
-
if (typeof value === 'string' && value.includes('{{'))
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
if (typeof value === 'string' && value.includes('{{')) {
|
|
57
|
+
// Split into literal text and {{ expr }} parts; valueStart is the offset of the value's first character.
|
|
58
|
+
const valueStart = start + name.length + 2;
|
|
59
|
+
const parts = [];
|
|
60
|
+
let at = 0;
|
|
61
|
+
while (at < value.length) {
|
|
62
|
+
const open = value.indexOf('{{', at);
|
|
63
|
+
if (open === -1) {
|
|
64
|
+
parts.push(value.slice(at));
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
if (open > at)
|
|
68
|
+
parts.push(value.slice(at, open));
|
|
69
|
+
const close = value.indexOf('}}', open + 2);
|
|
70
|
+
if (close === -1)
|
|
71
|
+
fail('unclosed {{ in attribute value', valueStart + open);
|
|
72
|
+
parts.push({ expr: value.slice(open + 2, close).trim(), start: valueStart + open });
|
|
73
|
+
at = close + 2;
|
|
74
|
+
}
|
|
75
|
+
list.push({ kind: 'interp', name, parts, start });
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
list.push({ kind: 'static', name, value, start });
|
|
79
|
+
}
|
|
59
80
|
}
|
|
60
81
|
}
|
|
61
82
|
}
|
|
@@ -97,6 +118,143 @@ export function parse(source, file) {
|
|
|
97
118
|
return -1;
|
|
98
119
|
}
|
|
99
120
|
// Parse children until `</parent>` (or end of input at top level).
|
|
121
|
+
// A parenthesised JS condition after `@if` / `@else if`, skipping strings and nested parentheses.
|
|
122
|
+
function condition(keyword) {
|
|
123
|
+
while (/\s/.test(source[i] ?? ''))
|
|
124
|
+
i++;
|
|
125
|
+
if (source[i] !== '(')
|
|
126
|
+
fail(`expected ( after ${keyword}`, i);
|
|
127
|
+
const open = i;
|
|
128
|
+
let depth = 0;
|
|
129
|
+
for (; i < source.length; i++) {
|
|
130
|
+
const c = source[i];
|
|
131
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
132
|
+
for (i++; i < source.length && source[i] !== c; i++)
|
|
133
|
+
if (source[i] === '\\')
|
|
134
|
+
i++;
|
|
135
|
+
}
|
|
136
|
+
else if (c === '(')
|
|
137
|
+
depth++;
|
|
138
|
+
else if (c === ')' && --depth === 0) {
|
|
139
|
+
i++;
|
|
140
|
+
return { cond: source.slice(open + 1, i - 1).trim(), condStart: open + 1 };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return fail(`unclosed ( after ${keyword}`, open);
|
|
144
|
+
}
|
|
145
|
+
// @if (a) { … } @else if (b) { … } @else { … }
|
|
146
|
+
function ifBlock() {
|
|
147
|
+
const start = i;
|
|
148
|
+
i += 3;
|
|
149
|
+
const branches = [];
|
|
150
|
+
let next = condition('@if');
|
|
151
|
+
while (next) {
|
|
152
|
+
while (/\s/.test(source[i] ?? ''))
|
|
153
|
+
i++;
|
|
154
|
+
if (source[i] !== '{')
|
|
155
|
+
fail('expected { to open the block', i);
|
|
156
|
+
i++;
|
|
157
|
+
branches.push({ ...next, children: children({ tag: '@if', start, block: true }) });
|
|
158
|
+
if (next.cond === null)
|
|
159
|
+
break; // @else is last
|
|
160
|
+
const save = i;
|
|
161
|
+
while (/\s/.test(source[i] ?? ''))
|
|
162
|
+
i++;
|
|
163
|
+
if (!source.startsWith('@else', i)) {
|
|
164
|
+
i = save;
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
i += 5;
|
|
168
|
+
while (/\s/.test(source[i] ?? ''))
|
|
169
|
+
i++;
|
|
170
|
+
if (/^if[\s(]/.test(source.slice(i, i + 3))) {
|
|
171
|
+
i += 2;
|
|
172
|
+
next = condition('@else if');
|
|
173
|
+
}
|
|
174
|
+
else
|
|
175
|
+
next = { cond: null, condStart: i };
|
|
176
|
+
}
|
|
177
|
+
return { type: 'if', branches, start };
|
|
178
|
+
}
|
|
179
|
+
// Split at top-level ';' (outside strings and brackets).
|
|
180
|
+
function splitClauses(text) {
|
|
181
|
+
const parts = [];
|
|
182
|
+
let depth = 0;
|
|
183
|
+
let from = 0;
|
|
184
|
+
for (let j = 0; j < text.length; j++) {
|
|
185
|
+
const c = text[j];
|
|
186
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
187
|
+
for (j++; j < text.length && text[j] !== c; j++)
|
|
188
|
+
if (text[j] === '\\')
|
|
189
|
+
j++;
|
|
190
|
+
}
|
|
191
|
+
else if ('([{'.includes(c))
|
|
192
|
+
depth++;
|
|
193
|
+
else if (')]}'.includes(c))
|
|
194
|
+
depth--;
|
|
195
|
+
else if (c === ';' && depth === 0) {
|
|
196
|
+
parts.push(text.slice(from, j));
|
|
197
|
+
from = j + 1;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return [...parts, text.slice(from)].map((p) => p.trim()).filter(Boolean);
|
|
201
|
+
}
|
|
202
|
+
// @for (item of list; track key) { … } @empty { … }
|
|
203
|
+
function forBlock() {
|
|
204
|
+
const start = i;
|
|
205
|
+
i += 4;
|
|
206
|
+
const { cond: head, condStart: headStart } = condition('@for');
|
|
207
|
+
const [first = '', ...rest] = splitClauses(head);
|
|
208
|
+
const m = /^([\s\S]+?)\s+of\s+([\s\S]+)$/.exec(first);
|
|
209
|
+
if (!m)
|
|
210
|
+
fail('expected "item of list" in @for', headStart);
|
|
211
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(m[1].trim()))
|
|
212
|
+
fail('the @for item must be a simple name', headStart);
|
|
213
|
+
let track = null;
|
|
214
|
+
for (const clause of rest) {
|
|
215
|
+
const t = /^track\s+([\s\S]+)$/.exec(clause);
|
|
216
|
+
if (!t)
|
|
217
|
+
fail(`unknown @for clause "${clause}"`, headStart);
|
|
218
|
+
track = t[1].trim();
|
|
219
|
+
}
|
|
220
|
+
while (/\s/.test(source[i] ?? ''))
|
|
221
|
+
i++;
|
|
222
|
+
if (source[i] !== '{')
|
|
223
|
+
fail('expected { to open the block', i);
|
|
224
|
+
i++;
|
|
225
|
+
const body = children({ tag: '@for', start, block: true });
|
|
226
|
+
let empty = null;
|
|
227
|
+
const save = i;
|
|
228
|
+
while (/\s/.test(source[i] ?? ''))
|
|
229
|
+
i++;
|
|
230
|
+
if (/^@empty[\s{]/.test(source.slice(i, i + 7))) {
|
|
231
|
+
i += 6;
|
|
232
|
+
while (/\s/.test(source[i] ?? ''))
|
|
233
|
+
i++;
|
|
234
|
+
if (source[i] !== '{')
|
|
235
|
+
fail('expected { to open the block', i);
|
|
236
|
+
i++;
|
|
237
|
+
empty = children({ tag: '@empty', start, block: true });
|
|
238
|
+
}
|
|
239
|
+
else
|
|
240
|
+
i = save;
|
|
241
|
+
return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, children: body, empty, start };
|
|
242
|
+
}
|
|
243
|
+
// @slot('name') { … }: content for a component's named slot.
|
|
244
|
+
function fillBlock() {
|
|
245
|
+
const start = i;
|
|
246
|
+
i += 5;
|
|
247
|
+
const { cond } = condition('@slot');
|
|
248
|
+
const m = /^(['"])([\w-]+)\1$/.exec(cond);
|
|
249
|
+
if (!m)
|
|
250
|
+
fail(`@slot needs a quoted name, like @slot('aside')`, start);
|
|
251
|
+
while (/\s/.test(source[i] ?? ''))
|
|
252
|
+
i++;
|
|
253
|
+
if (source[i] !== '{')
|
|
254
|
+
fail('expected { to open the block', i);
|
|
255
|
+
i++;
|
|
256
|
+
return { type: 'fill', name: m[2], children: children({ tag: '@slot', start, block: true }), start };
|
|
257
|
+
}
|
|
100
258
|
function children(parent) {
|
|
101
259
|
const nodes = [];
|
|
102
260
|
let text = '';
|
|
@@ -122,6 +280,26 @@ export function parse(source, file) {
|
|
|
122
280
|
text += source.slice(i, end + 3); // kept verbatim as static text: no tags, no holes inside
|
|
123
281
|
i = end + 3;
|
|
124
282
|
}
|
|
283
|
+
else if (/^@if[\s(]/.test(source.slice(i, i + 4))) {
|
|
284
|
+
flush();
|
|
285
|
+
nodes.push(ifBlock());
|
|
286
|
+
textStart = i;
|
|
287
|
+
}
|
|
288
|
+
else if (/^@for[\s(]/.test(source.slice(i, i + 5))) {
|
|
289
|
+
flush();
|
|
290
|
+
nodes.push(forBlock());
|
|
291
|
+
textStart = i;
|
|
292
|
+
}
|
|
293
|
+
else if (/^@slot[\s(]/.test(source.slice(i, i + 6))) {
|
|
294
|
+
flush();
|
|
295
|
+
nodes.push(fillBlock());
|
|
296
|
+
textStart = i;
|
|
297
|
+
}
|
|
298
|
+
else if (parent?.block && source[i] === '}') {
|
|
299
|
+
flush();
|
|
300
|
+
i++;
|
|
301
|
+
return nodes;
|
|
302
|
+
}
|
|
125
303
|
else if (!parent && source[i] === '@' && atLineStart(i)) {
|
|
126
304
|
flush();
|
|
127
305
|
directive();
|
|
@@ -169,6 +347,23 @@ export function parse(source, file) {
|
|
|
169
347
|
out.script = { code: source.slice(i, end), start: i };
|
|
170
348
|
i = end + '</script>'.length;
|
|
171
349
|
}
|
|
350
|
+
else if (list.some((a) => a.name === 'verbatim')) {
|
|
351
|
+
// Everything up to </tag> is text: no holes, tags or directives.
|
|
352
|
+
const attr = list.find((a) => a.name === 'verbatim');
|
|
353
|
+
if (attr.kind !== 'static' || attr.value !== true)
|
|
354
|
+
fail('verbatim takes no value', attr.start);
|
|
355
|
+
if (out.imports.some((imp) => imp.name === tag))
|
|
356
|
+
fail('verbatim only works on HTML elements, not components', attr.start);
|
|
357
|
+
let kids = [];
|
|
358
|
+
if (!selfClosing && !VOID.has(tag)) {
|
|
359
|
+
const close = source.indexOf(`</${tag}>`, i);
|
|
360
|
+
if (close === -1)
|
|
361
|
+
fail(`unclosed <${tag} verbatim>`, start);
|
|
362
|
+
kids = [{ type: 'raw', value: source.slice(i, close), start: i }];
|
|
363
|
+
i = close + `</${tag}>`.length;
|
|
364
|
+
}
|
|
365
|
+
nodes.push({ type: 'element', tag, attrs: list.filter((a) => a !== attr), children: kids, start });
|
|
366
|
+
}
|
|
172
367
|
else {
|
|
173
368
|
const kids = selfClosing || VOID.has(tag) ? [] : children({ tag, start });
|
|
174
369
|
nodes.push({ type: 'element', tag, attrs: list, children: kids, start });
|
|
@@ -180,7 +375,7 @@ export function parse(source, file) {
|
|
|
180
375
|
}
|
|
181
376
|
}
|
|
182
377
|
if (parent)
|
|
183
|
-
fail(`unclosed <${parent.tag}>`, parent.start);
|
|
378
|
+
fail(parent.block ? `unclosed ${parent.tag} block` : `unclosed <${parent.tag}>`, parent.start);
|
|
184
379
|
flush();
|
|
185
380
|
return nodes;
|
|
186
381
|
}
|
|
@@ -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,23 @@ 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
|
+
export declare function splitImports(code: string, file: string, source: string, offset: number): {
|
|
18
|
+
imports: string[];
|
|
19
|
+
body: string;
|
|
20
|
+
};
|
|
12
21
|
export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
|
|
13
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
|
|
24
|
+
* starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
|
|
25
|
+
*/
|
|
26
|
+
export declare function rewriteClient(code: string, signals: Signals, options?: {
|
|
27
|
+
stateFromServer?: boolean;
|
|
28
|
+
}): string;
|
|
14
29
|
export declare function rewriteClientExpr(expr: string, signals: Signals): string;
|
|
15
30
|
export declare function rewriteServer(code: string): string;
|
|
16
31
|
export declare function referencesSignal(expr: string, signals: Signals): boolean;
|
package/dist/compiler/script.js
CHANGED
|
@@ -181,19 +181,55 @@ 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
|
-
|
|
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
|
+
export function splitImports(code, file, source, offset) {
|
|
203
|
+
const imports = [];
|
|
204
|
+
let body = code;
|
|
205
|
+
for (const stmt of parseScript(code, file, source, offset).body) {
|
|
206
|
+
if (stmt.type !== 'ImportDeclaration')
|
|
207
|
+
continue;
|
|
208
|
+
const from = String(stmt.source.value);
|
|
209
|
+
if (from.startsWith('node:')) {
|
|
210
|
+
throw new ClarusError(`\`${from}\` can't be imported in an island script: the script is bundled for the browser`, file, source, offset + stmt.start);
|
|
211
|
+
}
|
|
212
|
+
imports.push(code.slice(stmt.start, stmt.end));
|
|
213
|
+
body = body.slice(0, stmt.start) + code.slice(stmt.start, stmt.end).replace(/[^\n]/g, ' ') + body.slice(stmt.end);
|
|
214
|
+
}
|
|
215
|
+
return { imports, body };
|
|
216
|
+
}
|
|
217
|
+
// Globals that only exist on a server runtime. An island's script also runs in the browser and its state() values
|
|
218
|
+
// are written into the page, so reading these would leak server data (or simply fail in the browser).
|
|
219
|
+
const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
|
|
192
220
|
export function analyzeScript(code, file, source, offset) {
|
|
193
221
|
const signals = new Map();
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
222
|
+
const ast = parseScript(code, file, source, offset);
|
|
223
|
+
const declared = scriptNames(code);
|
|
224
|
+
print(ast, code, (node, parent, key) => {
|
|
225
|
+
if (node.type === 'Identifier' && SERVER_GLOBALS.has(node.name) && !declared.has(node.name) && !isBinding(parent, key)) {
|
|
226
|
+
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);
|
|
227
|
+
}
|
|
228
|
+
return undefined;
|
|
229
|
+
});
|
|
230
|
+
for (const stmt of ast.body) {
|
|
231
|
+
if (stmt.type.startsWith('Export')) {
|
|
232
|
+
throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
|
|
197
233
|
}
|
|
198
234
|
if (stmt.type !== 'VariableDeclaration')
|
|
199
235
|
continue;
|
|
@@ -247,9 +283,29 @@ function clientHook(code, signals, entered = new WeakSet()) {
|
|
|
247
283
|
};
|
|
248
284
|
return hook;
|
|
249
285
|
}
|
|
250
|
-
|
|
286
|
+
/**
|
|
287
|
+
* Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
|
|
288
|
+
* starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
|
|
289
|
+
*/
|
|
290
|
+
export function rewriteClient(code, signals, options = {}) {
|
|
251
291
|
const ast = parseScript(code);
|
|
252
|
-
|
|
292
|
+
const hook = clientHook(code, signals);
|
|
293
|
+
if (!options.stateFromServer)
|
|
294
|
+
return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
|
|
295
|
+
const topLevel = new Set(ast.body.filter((n) => n.type === 'VariableDeclaration').flatMap((n) => n.declarations));
|
|
296
|
+
const withState = (node, parent, key) => {
|
|
297
|
+
// `let x = state()` becomes `const x = …`; re-print with this hook so the declarators below still see it.
|
|
298
|
+
if (node.type === 'VariableDeclaration' && node.kind === 'let' && node.declarations.every((d) => signalCall(d.init))) {
|
|
299
|
+
return 'const' + print({ ...node, kind: 'const', start: node.start + 3 }, code, withState, parent, key);
|
|
300
|
+
}
|
|
301
|
+
if (topLevel.has(node) && node.id.type === 'Identifier' && signals.get(node.id.name) === 'state' && node.init?.arguments?.length) {
|
|
302
|
+
const name = node.id.name;
|
|
303
|
+
const init = print(node.init.arguments[0], code, hook);
|
|
304
|
+
return `${name} = state(__cl_state && ${JSON.stringify(name)} in __cl_state ? __cl_state.${name} : ${init})`;
|
|
305
|
+
}
|
|
306
|
+
return hook(node, parent, key);
|
|
307
|
+
};
|
|
308
|
+
return code.slice(0, ast.start) + print(ast, code, withState) + code.slice(ast.end);
|
|
253
309
|
}
|
|
254
310
|
export function rewriteClientExpr(expr, signals) {
|
|
255
311
|
const ast = parseExpr(expr);
|
|
@@ -266,6 +322,10 @@ export function rewriteServer(code) {
|
|
|
266
322
|
return `(${inner})`;
|
|
267
323
|
if (node.callee.name === 'derived')
|
|
268
324
|
return `(${inner})()`;
|
|
325
|
+
// A store's current value lives across requests on the server; render from its initial value instead, and from
|
|
326
|
+
// a copy, so a render that mutates it can't change what the next request sees.
|
|
327
|
+
if (node.callee.name === 'shared')
|
|
328
|
+
return `structuredClone((${inner}).initial)`;
|
|
269
329
|
return undefined;
|
|
270
330
|
};
|
|
271
331
|
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
|
+
}
|
package/dist/runtime/dom.d.ts
CHANGED
|
@@ -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
|
-
|
|
6
|
-
|
|
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
|
|
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(
|
|
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 {};
|