clarusjs 0.8.1 → 0.10.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/dist/check/generate.d.ts +20 -4
- package/dist/check/generate.js +157 -21
- package/dist/cli/check.d.ts +13 -0
- package/dist/cli/check.js +65 -18
- package/dist/cli/index.js +9 -3
- package/dist/cli/mapper.d.ts +25 -0
- package/dist/cli/mapper.js +65 -0
- package/dist/cli/project.d.ts +5 -0
- package/dist/cli/project.js +21 -0
- package/dist/compiler/emit-client.js +33 -9
- package/dist/compiler/emit-server.js +3 -2
- package/dist/compiler/errors.d.ts +14 -1
- package/dist/compiler/html-expr.d.ts +21 -0
- package/dist/compiler/html-expr.js +29 -3
- package/dist/compiler/index.d.ts +28 -3
- package/dist/compiler/index.js +36 -24
- package/dist/compiler/ir.d.ts +19 -1
- package/dist/compiler/ir.js +261 -11
- package/dist/compiler/parse.d.ts +52 -1
- package/dist/compiler/parse.js +145 -6
- package/dist/compiler/script.d.ts +22 -1
- package/dist/compiler/script.js +108 -5
- package/dist/fetch/index.d.ts +149 -0
- package/dist/fetch/index.js +312 -0
- package/dist/forms/index.d.ts +26 -0
- package/dist/forms/index.js +374 -0
- package/dist/forms/types.d.ts +111 -0
- package/dist/forms/types.js +1 -0
- package/dist/runtime/attrs.js +10 -2
- package/dist/runtime/dom.d.ts +26 -11
- package/dist/runtime/dom.js +102 -14
- package/dist/runtime/env.d.ts +14 -0
- package/dist/runtime/env.js +14 -0
- package/dist/runtime/html.d.ts +9 -7
- package/dist/runtime/html.js +12 -7
- package/dist/runtime/index.d.ts +3 -2
- package/dist/runtime/index.js +3 -2
- package/dist/runtime/loader.d.ts +1 -1
- package/dist/runtime/loader.js +36 -5
- package/dist/runtime/navigate.d.ts +5 -0
- package/dist/runtime/navigation.d.ts +85 -13
- package/dist/runtime/navigation.js +77 -11
- package/dist/runtime/router.js +10 -1
- package/dist/runtime/serialize.d.ts +1 -1
- package/dist/runtime/serialize.js +1 -1
- package/dist/runtime/server.d.ts +9 -2
- package/dist/runtime/server.js +23 -5
- package/dist/runtime/signals.d.ts +98 -3
- package/dist/runtime/signals.js +112 -6
- package/dist/server/handler.d.ts +14 -1
- package/dist/server/handler.js +2 -2
- package/dist/server/head.d.ts +4 -1
- package/dist/server/manifest.d.ts +14 -1
- package/dist/server/views.d.ts +64 -6
- package/dist/server/views.js +46 -0
- package/dist/vite/build.d.ts +1 -1
- package/dist/vite/manifest.d.ts +12 -0
- package/dist/vite/plugin.d.ts +30 -2
- package/dist/vite/plugin.js +17 -2
- package/dist/vite/sitemap.d.ts +1 -0
- package/package.json +19 -1
package/dist/compiler/parse.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { ClarusError } from './errors.js';
|
|
2
|
+
export const FOR_IMPLICIT = ['$index', '$count', '$first', '$last', '$even', '$odd'];
|
|
2
3
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
3
|
-
const INPUT_RE = /^@input\s+([A-Za-z_$][\w$]*)\s*:\s*([^=\n]+?)\s*(?:=\s*(.+?))?\s*$/d;
|
|
4
4
|
const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
5
5
|
const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
|
|
6
6
|
const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
|
|
7
7
|
const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
|
|
8
|
+
const typeNames = (clause) => clause.startsWith('{') ? clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop().trim()).filter(Boolean) : [clause.trim()];
|
|
8
9
|
export function parse(source, file) {
|
|
9
|
-
const out = { inputs: [], imports: [], typeImports: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
|
|
10
|
+
const out = { inputs: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
|
|
10
11
|
let i = 0;
|
|
11
12
|
const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
|
|
12
13
|
const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
|
|
@@ -15,9 +16,11 @@ export function parse(source, file) {
|
|
|
15
16
|
const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
|
|
16
17
|
const line = source.slice(i, end).trim();
|
|
17
18
|
let m;
|
|
18
|
-
if ((
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
if (/^@(input|model)\s/.test(line)) {
|
|
20
|
+
return inputDecl(lineStart, line.startsWith('@model'));
|
|
21
|
+
}
|
|
22
|
+
else if (/^@(type|interface)\s/.test(line)) {
|
|
23
|
+
return typeDecl(lineStart);
|
|
21
24
|
}
|
|
22
25
|
else if ((m = IMPORT_TYPE_RE.exec(line))) {
|
|
23
26
|
out.typeImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
|
|
@@ -40,6 +43,126 @@ export function parse(source, file) {
|
|
|
40
43
|
fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
|
|
41
44
|
i = end;
|
|
42
45
|
}
|
|
46
|
+
function typeEnd(from, what, angles = false) {
|
|
47
|
+
const open = [];
|
|
48
|
+
for (let j = from; j <= source.length; j++) {
|
|
49
|
+
const c = source[j];
|
|
50
|
+
if (c === undefined || (c === '\n' && !open.length)) {
|
|
51
|
+
if (open.length)
|
|
52
|
+
fail(`${what}: unclosed ${open[0]}`, i);
|
|
53
|
+
return j;
|
|
54
|
+
}
|
|
55
|
+
if (c === "'" || c === '"' || c === '`') {
|
|
56
|
+
for (j++; j < source.length && source[j] !== c; j++)
|
|
57
|
+
if (source[j] === '\\')
|
|
58
|
+
j++;
|
|
59
|
+
}
|
|
60
|
+
else if (c === '(' || c === '[' || c === '{' || (angles && c === '<'))
|
|
61
|
+
open.push(c);
|
|
62
|
+
else if (c === ')' || c === ']' || c === '}' || (angles && c === '>' && source[j - 1] !== '='))
|
|
63
|
+
open.pop();
|
|
64
|
+
}
|
|
65
|
+
return source.length;
|
|
66
|
+
}
|
|
67
|
+
function inputDecl(lineStart, model) {
|
|
68
|
+
const directive = model ? '@model' : '@input';
|
|
69
|
+
const malformed = () => fail(`unknown or malformed directive "${directive}"`, i);
|
|
70
|
+
let pos = lineStart + directive.length;
|
|
71
|
+
while (source[pos] === ' ' || source[pos] === '\t')
|
|
72
|
+
pos++;
|
|
73
|
+
const name = /^[A-Za-z_$][\w$]*/.exec(source.slice(pos))?.[0] ?? malformed();
|
|
74
|
+
const nameStart = pos;
|
|
75
|
+
pos += name.length;
|
|
76
|
+
while (source[pos] === ' ' || source[pos] === '\t')
|
|
77
|
+
pos++;
|
|
78
|
+
if (source[pos] !== ':')
|
|
79
|
+
malformed();
|
|
80
|
+
pos++;
|
|
81
|
+
while (source[pos] === ' ' || source[pos] === '\t')
|
|
82
|
+
pos++;
|
|
83
|
+
const typeStart = pos;
|
|
84
|
+
const open = [];
|
|
85
|
+
let j = pos;
|
|
86
|
+
for (; j < source.length; j++) {
|
|
87
|
+
const c = source[j];
|
|
88
|
+
if (c === '\n' && !open.length)
|
|
89
|
+
break;
|
|
90
|
+
if (c === "'" || c === '"' || c === '`') {
|
|
91
|
+
for (j++; j < source.length && source[j] !== c; j++)
|
|
92
|
+
if (source[j] === '\\')
|
|
93
|
+
j++;
|
|
94
|
+
}
|
|
95
|
+
else if ('([{<'.includes(c))
|
|
96
|
+
open.push(c);
|
|
97
|
+
else if (')]}'.includes(c) || (c === '>' && source[j - 1] !== '='))
|
|
98
|
+
open.pop();
|
|
99
|
+
else if (c === '=' && !open.length && source[j + 1] !== '>' && source[j + 1] !== '=')
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
if (open.length)
|
|
103
|
+
fail(`@input ${name}: unclosed ${open[0]}`, i);
|
|
104
|
+
const type = source.slice(typeStart, j).trim();
|
|
105
|
+
if (!type)
|
|
106
|
+
malformed();
|
|
107
|
+
let end = j;
|
|
108
|
+
let fallback;
|
|
109
|
+
if (source[j] === '=') {
|
|
110
|
+
let at = j + 1;
|
|
111
|
+
while (source[at] === ' ' || source[at] === '\t')
|
|
112
|
+
at++;
|
|
113
|
+
end = typeEnd(at, `@input ${name}`);
|
|
114
|
+
const value = source.slice(at, end).trim();
|
|
115
|
+
if (!value)
|
|
116
|
+
malformed();
|
|
117
|
+
fallback = { default: value, defaultStart: at };
|
|
118
|
+
}
|
|
119
|
+
out.inputs.push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
|
|
120
|
+
i = end;
|
|
121
|
+
}
|
|
122
|
+
function typeDecl(lineStart) {
|
|
123
|
+
const kind = source.startsWith('@interface', lineStart) ? 'interface' : 'type';
|
|
124
|
+
const malformed = () => fail(`unknown or malformed directive "@${kind}"`, i);
|
|
125
|
+
let pos = lineStart + kind.length + 1;
|
|
126
|
+
while (source[pos] === ' ' || source[pos] === '\t')
|
|
127
|
+
pos++;
|
|
128
|
+
const name = /^[A-Za-z_$][\w$]*/.exec(source.slice(pos))?.[0] ?? malformed();
|
|
129
|
+
const nameStart = pos;
|
|
130
|
+
pos += name.length;
|
|
131
|
+
let params;
|
|
132
|
+
if (source[pos] === '<') {
|
|
133
|
+
let depth = 0;
|
|
134
|
+
let end = pos;
|
|
135
|
+
for (; end < source.length; end++) {
|
|
136
|
+
if (source[end] === '<')
|
|
137
|
+
depth++;
|
|
138
|
+
else if (source[end] === '>' && source[end - 1] !== '=' && --depth === 0)
|
|
139
|
+
break;
|
|
140
|
+
else if (source[end] === '\n')
|
|
141
|
+
malformed();
|
|
142
|
+
}
|
|
143
|
+
params = source.slice(pos, end + 1);
|
|
144
|
+
pos = end + 1;
|
|
145
|
+
}
|
|
146
|
+
while (source[pos] === ' ' || source[pos] === '\t')
|
|
147
|
+
pos++;
|
|
148
|
+
if (kind === 'type') {
|
|
149
|
+
if (source[pos] !== '=')
|
|
150
|
+
malformed();
|
|
151
|
+
pos++;
|
|
152
|
+
while (source[pos] === ' ' || source[pos] === '\t')
|
|
153
|
+
pos++;
|
|
154
|
+
}
|
|
155
|
+
const end = typeEnd(pos, `@${kind} ${name}`, true);
|
|
156
|
+
const type = source.slice(pos, end).trimEnd().replace(/;$/, '').trimEnd();
|
|
157
|
+
if (!type || (kind === 'interface' && !type.includes('{')))
|
|
158
|
+
malformed();
|
|
159
|
+
if (out.types.some((t) => t.name === name))
|
|
160
|
+
fail(`@type ${name} is declared twice`, i);
|
|
161
|
+
if (out.typeImports.some((t) => typeNames(t.clause).includes(name)))
|
|
162
|
+
fail(`@type ${name} is already imported with @import type`, i);
|
|
163
|
+
out.types.push({ kind, name, ...(params ? { params } : {}), type, start: i, nameStart, typeStart: pos });
|
|
164
|
+
i = end;
|
|
165
|
+
}
|
|
43
166
|
function attrs() {
|
|
44
167
|
const list = [];
|
|
45
168
|
for (;;) {
|
|
@@ -67,6 +190,11 @@ export function parse(source, file) {
|
|
|
67
190
|
fail(`event binding ${name} needs a handler`, start);
|
|
68
191
|
list.push({ kind: 'event', name: name.slice(1, -1), expr: value.trim(), start });
|
|
69
192
|
}
|
|
193
|
+
else if (name.startsWith('[(') && name.endsWith(')]')) {
|
|
194
|
+
if (value === true)
|
|
195
|
+
fail(`two-way binding ${name} needs a variable or property path`, start);
|
|
196
|
+
list.push({ kind: 'model', name: name.slice(2, -2), expr: value.trim(), start });
|
|
197
|
+
}
|
|
70
198
|
else if (name.startsWith('[') && name.endsWith(']')) {
|
|
71
199
|
if (value === true)
|
|
72
200
|
fail(`binding ${name} needs an expression`, start);
|
|
@@ -232,6 +360,8 @@ export function parse(source, file) {
|
|
|
232
360
|
if (!/^[A-Za-z_$][\w$]*$/.test(m[1].trim()))
|
|
233
361
|
fail('the @for item must be a simple name', headStart);
|
|
234
362
|
const itemStart = at + first.start + m.indices[1][0];
|
|
363
|
+
if (FOR_IMPLICIT.includes(m[1].trim()))
|
|
364
|
+
fail(`"${m[1].trim()}" is an implicit @for variable: name the item something else`, itemStart);
|
|
235
365
|
const listStart = at + first.start + m.indices[2][0];
|
|
236
366
|
let track = null;
|
|
237
367
|
let trackStart = -1;
|
|
@@ -239,6 +369,8 @@ export function parse(source, file) {
|
|
|
239
369
|
const t = /^track\s+([\s\S]+)$/d.exec(clause.text);
|
|
240
370
|
if (!t)
|
|
241
371
|
fail(`unknown @for clause "${clause.text}"`, headStart);
|
|
372
|
+
if (track !== null)
|
|
373
|
+
fail('only one track per @for', at + clause.start);
|
|
242
374
|
track = t[1].trim();
|
|
243
375
|
trackStart = at + clause.start + t.indices[1][0];
|
|
244
376
|
}
|
|
@@ -260,6 +392,12 @@ export function parse(source, file) {
|
|
|
260
392
|
fail('expected { to open the block', i);
|
|
261
393
|
i++;
|
|
262
394
|
empty = children({ tag: '@empty', start, block: true });
|
|
395
|
+
const after = i;
|
|
396
|
+
while (/\s/.test(source[i] ?? ''))
|
|
397
|
+
i++;
|
|
398
|
+
if (/^@empty[\s{]/.test(source.slice(i, i + 7)))
|
|
399
|
+
fail('only one @empty per @for', i);
|
|
400
|
+
i = after;
|
|
263
401
|
}
|
|
264
402
|
else
|
|
265
403
|
i = save;
|
|
@@ -405,7 +543,8 @@ export function parse(source, file) {
|
|
|
405
543
|
const hole = source.slice(i, end).indexOf('{{');
|
|
406
544
|
if (hole !== -1)
|
|
407
545
|
fail('{{ }} holes are not supported in a component <style>: set a CSS custom property from the template instead (style="--x: {{ x }}")', i + hole);
|
|
408
|
-
|
|
546
|
+
const mode = list.some((a) => a.name === 'scoped') ? 'scoped' : list.some((a) => a.name === 'global') ? 'global' : 'plain';
|
|
547
|
+
out.styles.push({ css: source.slice(i, end), mode, start: i, tag: start });
|
|
409
548
|
i = end + '</style>'.length;
|
|
410
549
|
}
|
|
411
550
|
else if (list.some((a) => a.name === 'verbatim')) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type Signals = Map<string, 'state' | 'derived' | 'shared'>;
|
|
1
|
+
export type Signals = Map<string, 'state' | 'derived' | 'shared' | 'input' | 'model'>;
|
|
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). */
|
|
@@ -22,16 +22,37 @@ export declare function splitImports(code: string, file: string, source: string,
|
|
|
22
22
|
}[];
|
|
23
23
|
body: string;
|
|
24
24
|
};
|
|
25
|
+
/**
|
|
26
|
+
* Where type annotations go for type checking: `: any` after the untyped parameters of the script's own functions
|
|
27
|
+
* (declarations, `const f = (x) => …`, class methods) and of callbacks passed straight to them (`record((p) => …)`).
|
|
28
|
+
* A script is JavaScript, so nothing else types those, and a strict project would report each one. Other callbacks
|
|
29
|
+
* keep their contextual type; a parameter with a default takes its type.
|
|
30
|
+
*/
|
|
31
|
+
export declare function untypedParams(code: string): {
|
|
32
|
+
at: number;
|
|
33
|
+
text: string;
|
|
34
|
+
}[];
|
|
25
35
|
export declare function analyzeScript(code: string, file: string, source: string, offset: number): Signals;
|
|
36
|
+
/** Do these import statements bring in form from clarusjs/forms (so `form(x)` is the engine's, not a function of its own)? */
|
|
37
|
+
export declare function formName(imports: string[]): string | undefined;
|
|
26
38
|
/**
|
|
27
39
|
* Rewrite a script (or event handler) for the browser. With `stateFromServer`, each top-level `let x = state(init)`
|
|
28
40
|
* starts from the value the server rendered with (`__cl_state.x`) when there is one, so `init` isn't re-run.
|
|
29
41
|
*/
|
|
30
42
|
export declare function rewriteClient(code: string, signals: Signals, options?: {
|
|
31
43
|
stateFromServer?: boolean;
|
|
44
|
+
forms?: string;
|
|
32
45
|
}): string;
|
|
33
46
|
export declare function rewriteClientExpr(expr: string, signals: Signals): string;
|
|
34
47
|
export declare function rewriteServer(code: string): string;
|
|
35
48
|
export declare function referencesSignal(expr: string, signals: Signals): boolean;
|
|
36
49
|
/** Does `expr` read any of `names`? */
|
|
50
|
+
/**
|
|
51
|
+
* Assignments and ++/-- to any of `names` in a script or event handler, skipping places where a local declaration
|
|
52
|
+
* shadows the name: where each written name starts in `code`.
|
|
53
|
+
*/
|
|
54
|
+
export declare function writesTo(code: string, names: Set<string>): {
|
|
55
|
+
name: string;
|
|
56
|
+
start: number;
|
|
57
|
+
}[];
|
|
37
58
|
export declare function referencesNames(expr: string, names: Set<string>): boolean;
|
package/dist/compiler/script.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parse as acornParse, parseExpressionAt } from 'acorn';
|
|
2
|
+
import { FOR_IMPLICIT } from './parse.js';
|
|
2
3
|
import { ClarusError } from './errors.js';
|
|
3
4
|
const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
|
|
4
5
|
function isNode(v) {
|
|
@@ -198,6 +199,41 @@ export function splitImports(code, file, source, offset) {
|
|
|
198
199
|
}
|
|
199
200
|
return { imports, body };
|
|
200
201
|
}
|
|
202
|
+
export function untypedParams(code) {
|
|
203
|
+
const ast = parseScript(code);
|
|
204
|
+
const isFn = (n) => !!n && (n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression');
|
|
205
|
+
const own = new Map();
|
|
206
|
+
for (const stmt of ast.body) {
|
|
207
|
+
if (stmt.type === 'FunctionDeclaration' && stmt.id)
|
|
208
|
+
own.set(stmt.id.name, stmt.params);
|
|
209
|
+
if (stmt.type === 'VariableDeclaration')
|
|
210
|
+
for (const d of stmt.declarations)
|
|
211
|
+
if (d.id.type === 'Identifier' && isFn(d.init))
|
|
212
|
+
own.set(d.id.name, d.init.params);
|
|
213
|
+
}
|
|
214
|
+
const targets = new Set();
|
|
215
|
+
print(ast, code, (node, parent, key) => {
|
|
216
|
+
if (node.type === 'FunctionDeclaration' || (isFn(node) && ((parent?.type === 'VariableDeclarator' && key === 'init') || parent?.type === 'MethodDefinition')))
|
|
217
|
+
targets.add(node);
|
|
218
|
+
const params = node.type === 'CallExpression' && node.callee.type === 'Identifier' ? own.get(node.callee.name) : undefined;
|
|
219
|
+
if (params)
|
|
220
|
+
node.arguments.forEach((arg, i) => { if (isFn(arg) && params[i]?.type !== 'AssignmentPattern')
|
|
221
|
+
targets.add(arg); });
|
|
222
|
+
return undefined;
|
|
223
|
+
});
|
|
224
|
+
const edits = [];
|
|
225
|
+
for (const fn of targets) {
|
|
226
|
+
for (const p of fn.params) {
|
|
227
|
+
if (p.type === 'AssignmentPattern')
|
|
228
|
+
continue;
|
|
229
|
+
const bare = fn.type === 'ArrowFunctionExpression' && !code.slice(fn.start, p.start).includes('(');
|
|
230
|
+
if (bare)
|
|
231
|
+
edits.push({ at: p.start, text: '(' });
|
|
232
|
+
edits.push({ at: p.end, text: (p.type === 'RestElement' ? ': any[]' : ': any') + (bare ? ')' : '') });
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return edits.sort((a, b) => a.at - b.at);
|
|
236
|
+
}
|
|
201
237
|
const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
|
|
202
238
|
export function analyzeScript(code, file, source, offset) {
|
|
203
239
|
const signals = new Map();
|
|
@@ -209,6 +245,16 @@ export function analyzeScript(code, file, source, offset) {
|
|
|
209
245
|
}
|
|
210
246
|
return undefined;
|
|
211
247
|
});
|
|
248
|
+
for (const stmt of ast.body) {
|
|
249
|
+
const ids = stmt.type === 'VariableDeclaration' ? stmt.declarations.map((d) => d.id) : stmt.type === 'FunctionDeclaration' && stmt.id ? [stmt.id] : [];
|
|
250
|
+
for (const id of ids) {
|
|
251
|
+
if (id.type === 'Identifier' && FOR_IMPLICIT.includes(id.name))
|
|
252
|
+
throw new ClarusError(`"${id.name}" is a @for row name: name it something else`, file, source, offset + id.start);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const tla = topLevelAwait(ast);
|
|
256
|
+
if (tla)
|
|
257
|
+
throw new ClarusError("top-level await isn't supported in a <script> (rendering is synchronous): await inside a function, such as a resource's fetcher or an event handler", file, source, offset + tla.start);
|
|
212
258
|
for (const stmt of ast.body) {
|
|
213
259
|
if (stmt.type.startsWith('Export')) {
|
|
214
260
|
throw new ClarusError('a <script> cannot export anything', file, source, offset + stmt.start);
|
|
@@ -223,21 +269,36 @@ export function analyzeScript(code, file, source, offset) {
|
|
|
223
269
|
}
|
|
224
270
|
return signals;
|
|
225
271
|
}
|
|
226
|
-
function
|
|
272
|
+
export function formName(imports) {
|
|
273
|
+
for (const line of imports) {
|
|
274
|
+
if (!/from\s*['"]clarusjs\/forms['"]/.test(line))
|
|
275
|
+
continue;
|
|
276
|
+
const m = /\{[^}]*\bform\b(?:\s+as\s+([A-Za-z_$][\w$]*))?[^}]*\}/.exec(line);
|
|
277
|
+
if (m)
|
|
278
|
+
return m[1] ?? 'form';
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
function clientHook(code, signals, entered = new WeakSet(), forms) {
|
|
227
282
|
const hook = (node, parent, key) => {
|
|
228
283
|
const rec = (n) => print(n, code, hook, node, '');
|
|
229
284
|
const isSignal = (n) => n.type === 'Identifier' && signals.has(n.name);
|
|
230
285
|
if (!entered.has(node)) {
|
|
231
|
-
const
|
|
232
|
-
|
|
286
|
+
const names = scopeNames(node);
|
|
287
|
+
const shadowed = [...names].filter((n) => signals.has(n));
|
|
288
|
+
const formHidden = !!forms && names.has(forms);
|
|
289
|
+
if (shadowed.length || formHidden) {
|
|
233
290
|
entered.add(node);
|
|
234
291
|
const inner = new Map([...signals].filter(([n]) => !shadowed.includes(n)));
|
|
235
|
-
return print(node, code, clientHook(code, inner, entered), parent, key);
|
|
292
|
+
return print(node, code, clientHook(code, inner, entered, formHidden ? undefined : forms), parent, key);
|
|
236
293
|
}
|
|
237
294
|
}
|
|
238
295
|
if (node.type === 'VariableDeclaration' && node.kind === 'let' && node.declarations.every((d) => signalCall(d.init))) {
|
|
239
296
|
return 'const' + print({ ...node, kind: 'const', start: node.start + 3 }, code, hook, parent, key);
|
|
240
297
|
}
|
|
298
|
+
if (forms && node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === forms && node.arguments[0] && isSignal(node.arguments[0])) {
|
|
299
|
+
const [first, ...rest] = node.arguments;
|
|
300
|
+
return `${forms}(${first.name}${rest.map((a) => `, ${rec(a)}`).join('')})`;
|
|
301
|
+
}
|
|
241
302
|
if (node.type === 'UpdateExpression' && isSignal(node.argument)) {
|
|
242
303
|
const name = node.argument.name;
|
|
243
304
|
const op = node.operator[0];
|
|
@@ -265,7 +326,7 @@ function clientHook(code, signals, entered = new WeakSet()) {
|
|
|
265
326
|
}
|
|
266
327
|
export function rewriteClient(code, signals, options = {}) {
|
|
267
328
|
const ast = parseScript(code);
|
|
268
|
-
const hook = clientHook(code, signals);
|
|
329
|
+
const hook = clientHook(code, signals, new WeakSet(), options.forms);
|
|
269
330
|
if (!options.stateFromServer)
|
|
270
331
|
return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
|
|
271
332
|
const topLevel = new Set(ast.body.filter((n) => n.type === 'VariableDeclaration').flatMap((n) => n.declarations));
|
|
@@ -306,6 +367,32 @@ export function rewriteServer(code) {
|
|
|
306
367
|
export function referencesSignal(expr, signals) {
|
|
307
368
|
return referencesNames(expr, new Set(signals.keys()));
|
|
308
369
|
}
|
|
370
|
+
export function writesTo(code, names) {
|
|
371
|
+
const found = [];
|
|
372
|
+
const visit = (active, entered) => (node, parent, key) => {
|
|
373
|
+
if (!entered.has(node)) {
|
|
374
|
+
const shadowed = [...scopeNames(node)].filter((n) => active.has(n));
|
|
375
|
+
if (shadowed.length) {
|
|
376
|
+
entered.add(node);
|
|
377
|
+
print(node, code, visit(new Set([...active].filter((n) => !shadowed.includes(n))), entered), parent, key);
|
|
378
|
+
return '';
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const target = node.type === 'AssignmentExpression' ? node.left : node.type === 'UpdateExpression' ? node.argument : null;
|
|
382
|
+
if (target?.type === 'Identifier' && active.has(target.name))
|
|
383
|
+
found.push({ name: target.name, start: target.start });
|
|
384
|
+
if (target && target.type !== 'Identifier' && target.type !== 'MemberExpression') {
|
|
385
|
+
const written = new Set();
|
|
386
|
+
patternNames(target, written);
|
|
387
|
+
for (const name of written)
|
|
388
|
+
if (active.has(name))
|
|
389
|
+
found.push({ name, start: target.start });
|
|
390
|
+
}
|
|
391
|
+
return undefined;
|
|
392
|
+
};
|
|
393
|
+
print(parseScript(code), code, visit(names, new WeakSet()));
|
|
394
|
+
return found;
|
|
395
|
+
}
|
|
309
396
|
export function referencesNames(expr, names) {
|
|
310
397
|
let found = false;
|
|
311
398
|
print(parseExpr(expr), expr, (node, parent, key) => {
|
|
@@ -317,3 +404,19 @@ export function referencesNames(expr, names) {
|
|
|
317
404
|
});
|
|
318
405
|
return found;
|
|
319
406
|
}
|
|
407
|
+
function topLevelAwait(node) {
|
|
408
|
+
if (/Function/.test(node.type))
|
|
409
|
+
return undefined;
|
|
410
|
+
if (node.type === 'AwaitExpression' || (node.type === 'ForOfStatement' && node.await))
|
|
411
|
+
return node;
|
|
412
|
+
for (const value of Object.values(node)) {
|
|
413
|
+
for (const child of Array.isArray(value) ? value : [value]) {
|
|
414
|
+
if (child && typeof child === 'object' && typeof child.type === 'string') {
|
|
415
|
+
const found = topLevelAwait(child);
|
|
416
|
+
if (found)
|
|
417
|
+
return found;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return undefined;
|
|
422
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An island's fetched data. Its getters read signals, so a template that shows them updates on its own.
|
|
3
|
+
* @see https://clarusjs.com/reference/fetch#resource
|
|
4
|
+
*/
|
|
5
|
+
export type Resource<T> = {
|
|
6
|
+
/** The last successful answer (kept during a refetch and after an error), or `initial`. */
|
|
7
|
+
readonly value: T | undefined;
|
|
8
|
+
/** A run is in flight. */
|
|
9
|
+
readonly loading: boolean;
|
|
10
|
+
/** The last run's error, cleared when a run starts. */
|
|
11
|
+
readonly error: unknown;
|
|
12
|
+
/** Run now, aborting a run in flight. */
|
|
13
|
+
refetch(): Promise<void>;
|
|
14
|
+
/** Set the shown value (e.g. optimistically, before a POST); the next run overwrites it. Keyed: its cache entry. */
|
|
15
|
+
mutate(value: T): void;
|
|
16
|
+
/** The first answer (`value`), or the first run's error. On the server, `initial`. In handlers, not top level. */
|
|
17
|
+
ready(): Promise<T | undefined>;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* `resource()`'s options: a starting value, retry, refetch, and (with `key`) caching.
|
|
21
|
+
* @see https://clarusjs.com/reference/fetch#resource
|
|
22
|
+
*/
|
|
23
|
+
export type ResourceOptions<T> = {
|
|
24
|
+
/** The starting value (from the page's load()): shown in server HTML and while the browser revalidates. */
|
|
25
|
+
initial?: T;
|
|
26
|
+
/** Attempts after a failed one: a count, or a count and the delay before each (default 500 ms, doubling, ≤ 8 s). */
|
|
27
|
+
retry?: number | {
|
|
28
|
+
count: number;
|
|
29
|
+
delay?(attempt: number): number;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* When to run again: every `interval` ms while the page is visible; on `focus` (the page shown again). `onStart`
|
|
33
|
+
* (default true): run on attach. With `onStart: false` the resource doesn't follow its signals until a first run.
|
|
34
|
+
*/
|
|
35
|
+
refetch?: {
|
|
36
|
+
interval?: number;
|
|
37
|
+
focus?: boolean;
|
|
38
|
+
onStart?: boolean;
|
|
39
|
+
};
|
|
40
|
+
/** Cache answers by this key (`['items', { page }]`), page-wide: seen keys need no request until invalidated. */
|
|
41
|
+
key?: () => unknown[] | undefined | null | false;
|
|
42
|
+
/** With `key`: refetch cached answers older than this (ms). Unset: fresh until invalidated. */
|
|
43
|
+
stale?: number;
|
|
44
|
+
/** With `key`: keep an unshown answer this long (ms, default 5 min). */
|
|
45
|
+
keep?: number;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* A fetcher's answer: a value, a promise of one, or undefined/null/false for "not ready" (a chain still waiting). An
|
|
49
|
+
* async fetcher resolving to undefined is "not ready" too. Signals it reads before its first `await` are tracked.
|
|
50
|
+
*/
|
|
51
|
+
type Fetcher<T> = (ctx: {
|
|
52
|
+
signal: AbortSignal;
|
|
53
|
+
}) => T | Promise<T> | undefined | null | false;
|
|
54
|
+
/**
|
|
55
|
+
* Runs `fetcher` in the browser and gives its answer as `value`, `loading` and `error`, which update an island's
|
|
56
|
+
* template on their own. It runs again when a signal the fetcher reads changes (another resource's `value`, a
|
|
57
|
+
* `state`), so requests chain; a falsy return means "not ready" (no request). The latest run wins; an island that
|
|
58
|
+
* goes away aborts its run. On the server the fetcher never runs.
|
|
59
|
+
*
|
|
60
|
+
* @param fetcher Returns the value or a promise of it (it can be `async`); pass `signal` on to `fetch`. Signals it
|
|
61
|
+
* reads before its first `await` are the ones it follows.
|
|
62
|
+
* @param options `initial` (a starting value), `retry`, `refetch: { interval, focus, onStart }`.
|
|
63
|
+
* @returns A {@link Resource}: `value`, `loading`, `error`, `refetch()`, `mutate()`.
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* const team = resource(({ signal }) => json('/api/team', { signal }))
|
|
67
|
+
* // A chain: waits for the team, and runs again when it changes.
|
|
68
|
+
* const members = resource(({ signal }) => team.value && json(`/api/teams/${team.value.id}/members`, { signal }), {
|
|
69
|
+
* retry: 2,
|
|
70
|
+
* refetch: { interval: 30_000 },
|
|
71
|
+
* })
|
|
72
|
+
* ```
|
|
73
|
+
* @see https://clarusjs.com/reference/fetch#resource
|
|
74
|
+
*/
|
|
75
|
+
export declare function resource<T>(fetcher: Fetcher<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
76
|
+
/**
|
|
77
|
+
* Mark every cached answer whose key starts with `prefix` (element by element) as stale: the resources showing one
|
|
78
|
+
* fetch it again now, the others when next used. With no prefix: everything.
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* await fetch(`/api/items/${id}`, { method: 'PATCH', body })
|
|
82
|
+
* invalidate(['items']) // every cached page of items
|
|
83
|
+
* ```
|
|
84
|
+
* @see https://clarusjs.com/reference/fetch#invalidate
|
|
85
|
+
*/
|
|
86
|
+
export declare function invalidate(prefix?: unknown[]): void;
|
|
87
|
+
/**
|
|
88
|
+
* Set a cached answer (an optimistic edit) and show it in every resource using that key; creates it if missing.
|
|
89
|
+
* @example
|
|
90
|
+
* ```ts
|
|
91
|
+
* setData(['items', { page }], (rows) => rows.map((r) => (r.id === id ? { ...r, name } : r)))
|
|
92
|
+
* ```
|
|
93
|
+
* @see https://clarusjs.com/reference/fetch#setdata
|
|
94
|
+
*/
|
|
95
|
+
export declare function setData<T>(key: unknown[], value: T | ((prev: T | undefined) => T)): void;
|
|
96
|
+
/**
|
|
97
|
+
* Fetch an answer into the cache ahead of time (the next page), unless it's there and fresh. Errors are ignored.
|
|
98
|
+
* @example
|
|
99
|
+
* ```ts
|
|
100
|
+
* prefetch(['items', { page: page + 1 }], ({ signal }) => json(`/api/items?page=${page + 1}`, { signal }))
|
|
101
|
+
* ```
|
|
102
|
+
* @see https://clarusjs.com/reference/fetch#prefetch
|
|
103
|
+
*/
|
|
104
|
+
export declare function prefetch<T>(key: unknown[], fetcher: (ctx: {
|
|
105
|
+
signal: AbortSignal;
|
|
106
|
+
}) => T | Promise<T>): Promise<void>;
|
|
107
|
+
/**
|
|
108
|
+
* Keys asked of one endpoint at the same moment, answered by one request: what `batch()` gives.
|
|
109
|
+
* @see https://clarusjs.com/reference/fetch#batch
|
|
110
|
+
*/
|
|
111
|
+
export type Batch<T> = {
|
|
112
|
+
get(key: string): Promise<T>;
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* One request for the keys asked at the same moment (the same task, or within `wait` ms), from the islands asking
|
|
116
|
+
* then (islands attaching later, such as on idle or when visible, join with a longer `wait`):
|
|
117
|
+
* `load(keys)` answers each key. Concurrent asks for a key share its request; nothing is kept after it settles.
|
|
118
|
+
* `max` splits a large batch. Share it from a module (`export const stats = batch(…)`).
|
|
119
|
+
*
|
|
120
|
+
* @param load Fetches the answers for `keys`: an object with one entry per key.
|
|
121
|
+
* @param options `wait` (ms to collect keys), `max` (keys per request).
|
|
122
|
+
* @returns `{ get(key) }`: a promise of that key's answer.
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* // stores/stats.ts: every card on the page joins the same request
|
|
126
|
+
* export const stats = batch((keys, { signal }) => json(`/api/stats?keys=${keys.join(',')}`, { signal }))
|
|
127
|
+
* // in a card's script
|
|
128
|
+
* const visits = resource(() => stats.get('visits'))
|
|
129
|
+
* ```
|
|
130
|
+
* @see https://clarusjs.com/reference/fetch#batch
|
|
131
|
+
*/
|
|
132
|
+
export declare function batch<T>(load: (keys: string[], ctx: {
|
|
133
|
+
signal: AbortSignal;
|
|
134
|
+
}) => Record<string, T> | Promise<Record<string, T>>, options?: {
|
|
135
|
+
wait?: number;
|
|
136
|
+
max?: number;
|
|
137
|
+
}): Batch<T>;
|
|
138
|
+
/**
|
|
139
|
+
* `fetch(url, init)`, then the response's JSON. A response that isn't 2xx throws an Error naming the URL and status
|
|
140
|
+
* (its `status` property holds the code), so a resource's `retry` and `error` see it.
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* ```ts
|
|
144
|
+
* const me = resource(({ signal }) => json<User>('/api/me', { signal }))
|
|
145
|
+
* ```
|
|
146
|
+
* @see https://clarusjs.com/reference/fetch#json
|
|
147
|
+
*/
|
|
148
|
+
export declare function json<T = any>(url: string | URL, init?: RequestInit): Promise<T>;
|
|
149
|
+
export {};
|