clarusjs 0.8.1 → 0.9.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.
@@ -1,12 +1,12 @@
1
1
  import { ClarusError } from './errors.js';
2
2
  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
3
  const DATA_IMPORT_RE = /^@import\s+(\{[^}]*\})\s+from\s+(['"])(.+?)\2\s*$/d;
5
4
  const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+(['"])(.+?)\2\s*$/d;
6
5
  const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
7
6
  const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
7
+ 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
8
  export function parse(source, file) {
9
- const out = { inputs: [], imports: [], typeImports: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
9
+ const out = { inputs: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
10
10
  let i = 0;
11
11
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
12
12
  const atLineStart = (at) => /^[ \t]*$/.test(source.slice(source.lastIndexOf('\n', at - 1) + 1, at));
@@ -15,9 +15,11 @@ export function parse(source, file) {
15
15
  const lineStart = i + (source.slice(i, end).length - source.slice(i, end).trimStart().length);
16
16
  const line = source.slice(i, end).trim();
17
17
  let m;
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) } : {}) });
18
+ if (/^@(input|model)\s/.test(line)) {
19
+ return inputDecl(lineStart, line.startsWith('@model'));
20
+ }
21
+ else if (/^@(type|interface)\s/.test(line)) {
22
+ return typeDecl(lineStart);
21
23
  }
22
24
  else if ((m = IMPORT_TYPE_RE.exec(line))) {
23
25
  out.typeImports.push({ clause: m[1], from: m[3], start: i, clauseStart: lineStart + m.indices[1][0] });
@@ -40,6 +42,126 @@ export function parse(source, file) {
40
42
  fail(`unknown or malformed directive "${line.split(/\s/)[0]}"`, i);
41
43
  i = end;
42
44
  }
45
+ function typeEnd(from, what, angles = false) {
46
+ const open = [];
47
+ for (let j = from; j <= source.length; j++) {
48
+ const c = source[j];
49
+ if (c === undefined || (c === '\n' && !open.length)) {
50
+ if (open.length)
51
+ fail(`${what}: unclosed ${open[0]}`, i);
52
+ return j;
53
+ }
54
+ if (c === "'" || c === '"' || c === '`') {
55
+ for (j++; j < source.length && source[j] !== c; j++)
56
+ if (source[j] === '\\')
57
+ j++;
58
+ }
59
+ else if (c === '(' || c === '[' || c === '{' || (angles && c === '<'))
60
+ open.push(c);
61
+ else if (c === ')' || c === ']' || c === '}' || (angles && c === '>' && source[j - 1] !== '='))
62
+ open.pop();
63
+ }
64
+ return source.length;
65
+ }
66
+ function inputDecl(lineStart, model) {
67
+ const directive = model ? '@model' : '@input';
68
+ const malformed = () => fail(`unknown or malformed directive "${directive}"`, i);
69
+ let pos = lineStart + directive.length;
70
+ while (source[pos] === ' ' || source[pos] === '\t')
71
+ pos++;
72
+ const name = /^[A-Za-z_$][\w$]*/.exec(source.slice(pos))?.[0] ?? malformed();
73
+ const nameStart = pos;
74
+ pos += name.length;
75
+ while (source[pos] === ' ' || source[pos] === '\t')
76
+ pos++;
77
+ if (source[pos] !== ':')
78
+ malformed();
79
+ pos++;
80
+ while (source[pos] === ' ' || source[pos] === '\t')
81
+ pos++;
82
+ const typeStart = pos;
83
+ const open = [];
84
+ let j = pos;
85
+ for (; j < source.length; j++) {
86
+ const c = source[j];
87
+ if (c === '\n' && !open.length)
88
+ break;
89
+ if (c === "'" || c === '"' || c === '`') {
90
+ for (j++; j < source.length && source[j] !== c; j++)
91
+ if (source[j] === '\\')
92
+ j++;
93
+ }
94
+ else if ('([{<'.includes(c))
95
+ open.push(c);
96
+ else if (')]}'.includes(c) || (c === '>' && source[j - 1] !== '='))
97
+ open.pop();
98
+ else if (c === '=' && !open.length && source[j + 1] !== '>' && source[j + 1] !== '=')
99
+ break;
100
+ }
101
+ if (open.length)
102
+ fail(`@input ${name}: unclosed ${open[0]}`, i);
103
+ const type = source.slice(typeStart, j).trim();
104
+ if (!type)
105
+ malformed();
106
+ let end = j;
107
+ let fallback;
108
+ if (source[j] === '=') {
109
+ let at = j + 1;
110
+ while (source[at] === ' ' || source[at] === '\t')
111
+ at++;
112
+ end = typeEnd(at, `@input ${name}`);
113
+ const value = source.slice(at, end).trim();
114
+ if (!value)
115
+ malformed();
116
+ fallback = { default: value, defaultStart: at };
117
+ }
118
+ out.inputs.push({ name, type, start: i, nameStart, typeStart, ...fallback, ...(model ? { model: true } : {}) });
119
+ i = end;
120
+ }
121
+ function typeDecl(lineStart) {
122
+ const kind = source.startsWith('@interface', lineStart) ? 'interface' : 'type';
123
+ const malformed = () => fail(`unknown or malformed directive "@${kind}"`, i);
124
+ let pos = lineStart + kind.length + 1;
125
+ while (source[pos] === ' ' || source[pos] === '\t')
126
+ pos++;
127
+ const name = /^[A-Za-z_$][\w$]*/.exec(source.slice(pos))?.[0] ?? malformed();
128
+ const nameStart = pos;
129
+ pos += name.length;
130
+ let params;
131
+ if (source[pos] === '<') {
132
+ let depth = 0;
133
+ let end = pos;
134
+ for (; end < source.length; end++) {
135
+ if (source[end] === '<')
136
+ depth++;
137
+ else if (source[end] === '>' && source[end - 1] !== '=' && --depth === 0)
138
+ break;
139
+ else if (source[end] === '\n')
140
+ malformed();
141
+ }
142
+ params = source.slice(pos, end + 1);
143
+ pos = end + 1;
144
+ }
145
+ while (source[pos] === ' ' || source[pos] === '\t')
146
+ pos++;
147
+ if (kind === 'type') {
148
+ if (source[pos] !== '=')
149
+ malformed();
150
+ pos++;
151
+ while (source[pos] === ' ' || source[pos] === '\t')
152
+ pos++;
153
+ }
154
+ const end = typeEnd(pos, `@${kind} ${name}`, true);
155
+ const type = source.slice(pos, end).trimEnd().replace(/;$/, '').trimEnd();
156
+ if (!type || (kind === 'interface' && !type.includes('{')))
157
+ malformed();
158
+ if (out.types.some((t) => t.name === name))
159
+ fail(`@type ${name} is declared twice`, i);
160
+ if (out.typeImports.some((t) => typeNames(t.clause).includes(name)))
161
+ fail(`@type ${name} is already imported with @import type`, i);
162
+ out.types.push({ kind, name, ...(params ? { params } : {}), type, start: i, nameStart, typeStart: pos });
163
+ i = end;
164
+ }
43
165
  function attrs() {
44
166
  const list = [];
45
167
  for (;;) {
@@ -67,6 +189,11 @@ export function parse(source, file) {
67
189
  fail(`event binding ${name} needs a handler`, start);
68
190
  list.push({ kind: 'event', name: name.slice(1, -1), expr: value.trim(), start });
69
191
  }
192
+ else if (name.startsWith('[(') && name.endsWith(')]')) {
193
+ if (value === true)
194
+ fail(`two-way binding ${name} needs a variable or property path`, start);
195
+ list.push({ kind: 'model', name: name.slice(2, -2), expr: value.trim(), start });
196
+ }
70
197
  else if (name.startsWith('[') && name.endsWith(']')) {
71
198
  if (value === true)
72
199
  fail(`binding ${name} needs an expression`, start);
@@ -405,7 +532,8 @@ export function parse(source, file) {
405
532
  const hole = source.slice(i, end).indexOf('{{');
406
533
  if (hole !== -1)
407
534
  fail('{{ }} holes are not supported in a component <style>: set a CSS custom property from the template instead (style="--x: {{ x }}")', i + hole);
408
- out.styles.push({ css: source.slice(i, end), global: list.some((a) => a.name === 'global'), start: i });
535
+ const mode = list.some((a) => a.name === 'scoped') ? 'scoped' : list.some((a) => a.name === 'global') ? 'global' : 'plain';
536
+ out.styles.push({ css: source.slice(i, end), mode, start: i, tag: start });
409
537
  i = end + '</style>'.length;
410
538
  }
411
539
  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;
@@ -198,6 +198,41 @@ export function splitImports(code, file, source, offset) {
198
198
  }
199
199
  return { imports, body };
200
200
  }
201
+ export function untypedParams(code) {
202
+ const ast = parseScript(code);
203
+ const isFn = (n) => !!n && (n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression');
204
+ const own = new Map();
205
+ for (const stmt of ast.body) {
206
+ if (stmt.type === 'FunctionDeclaration' && stmt.id)
207
+ own.set(stmt.id.name, stmt.params);
208
+ if (stmt.type === 'VariableDeclaration')
209
+ for (const d of stmt.declarations)
210
+ if (d.id.type === 'Identifier' && isFn(d.init))
211
+ own.set(d.id.name, d.init.params);
212
+ }
213
+ const targets = new Set();
214
+ print(ast, code, (node, parent, key) => {
215
+ if (node.type === 'FunctionDeclaration' || (isFn(node) && ((parent?.type === 'VariableDeclarator' && key === 'init') || parent?.type === 'MethodDefinition')))
216
+ targets.add(node);
217
+ const params = node.type === 'CallExpression' && node.callee.type === 'Identifier' ? own.get(node.callee.name) : undefined;
218
+ if (params)
219
+ node.arguments.forEach((arg, i) => { if (isFn(arg) && params[i]?.type !== 'AssignmentPattern')
220
+ targets.add(arg); });
221
+ return undefined;
222
+ });
223
+ const edits = [];
224
+ for (const fn of targets) {
225
+ for (const p of fn.params) {
226
+ if (p.type === 'AssignmentPattern')
227
+ continue;
228
+ const bare = fn.type === 'ArrowFunctionExpression' && !code.slice(fn.start, p.start).includes('(');
229
+ if (bare)
230
+ edits.push({ at: p.start, text: '(' });
231
+ edits.push({ at: p.end, text: (p.type === 'RestElement' ? ': any[]' : ': any') + (bare ? ')' : '') });
232
+ }
233
+ }
234
+ return edits.sort((a, b) => a.at - b.at);
235
+ }
201
236
  const SERVER_GLOBALS = new Set(['process', 'Deno', 'Bun', 'require']);
202
237
  export function analyzeScript(code, file, source, offset) {
203
238
  const signals = new Map();
@@ -223,21 +258,36 @@ export function analyzeScript(code, file, source, offset) {
223
258
  }
224
259
  return signals;
225
260
  }
226
- function clientHook(code, signals, entered = new WeakSet()) {
261
+ export function formName(imports) {
262
+ for (const line of imports) {
263
+ if (!/from\s*['"]clarusjs\/forms['"]/.test(line))
264
+ continue;
265
+ const m = /\{[^}]*\bform\b(?:\s+as\s+([A-Za-z_$][\w$]*))?[^}]*\}/.exec(line);
266
+ if (m)
267
+ return m[1] ?? 'form';
268
+ }
269
+ }
270
+ function clientHook(code, signals, entered = new WeakSet(), forms) {
227
271
  const hook = (node, parent, key) => {
228
272
  const rec = (n) => print(n, code, hook, node, '');
229
273
  const isSignal = (n) => n.type === 'Identifier' && signals.has(n.name);
230
274
  if (!entered.has(node)) {
231
- const shadowed = [...scopeNames(node)].filter((n) => signals.has(n));
232
- if (shadowed.length) {
275
+ const names = scopeNames(node);
276
+ const shadowed = [...names].filter((n) => signals.has(n));
277
+ const formHidden = !!forms && names.has(forms);
278
+ if (shadowed.length || formHidden) {
233
279
  entered.add(node);
234
280
  const inner = new Map([...signals].filter(([n]) => !shadowed.includes(n)));
235
- return print(node, code, clientHook(code, inner, entered), parent, key);
281
+ return print(node, code, clientHook(code, inner, entered, formHidden ? undefined : forms), parent, key);
236
282
  }
237
283
  }
238
284
  if (node.type === 'VariableDeclaration' && node.kind === 'let' && node.declarations.every((d) => signalCall(d.init))) {
239
285
  return 'const' + print({ ...node, kind: 'const', start: node.start + 3 }, code, hook, parent, key);
240
286
  }
287
+ if (forms && node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === forms && node.arguments[0] && isSignal(node.arguments[0])) {
288
+ const [first, ...rest] = node.arguments;
289
+ return `${forms}(${first.name}${rest.map((a) => `, ${rec(a)}`).join('')})`;
290
+ }
241
291
  if (node.type === 'UpdateExpression' && isSignal(node.argument)) {
242
292
  const name = node.argument.name;
243
293
  const op = node.operator[0];
@@ -265,7 +315,7 @@ function clientHook(code, signals, entered = new WeakSet()) {
265
315
  }
266
316
  export function rewriteClient(code, signals, options = {}) {
267
317
  const ast = parseScript(code);
268
- const hook = clientHook(code, signals);
318
+ const hook = clientHook(code, signals, new WeakSet(), options.forms);
269
319
  if (!options.stateFromServer)
270
320
  return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
271
321
  const topLevel = new Set(ast.body.filter((n) => n.type === 'VariableDeclaration').flatMap((n) => n.declarations));
@@ -306,6 +356,32 @@ export function rewriteServer(code) {
306
356
  export function referencesSignal(expr, signals) {
307
357
  return referencesNames(expr, new Set(signals.keys()));
308
358
  }
359
+ export function writesTo(code, names) {
360
+ const found = [];
361
+ const visit = (active, entered) => (node, parent, key) => {
362
+ if (!entered.has(node)) {
363
+ const shadowed = [...scopeNames(node)].filter((n) => active.has(n));
364
+ if (shadowed.length) {
365
+ entered.add(node);
366
+ print(node, code, visit(new Set([...active].filter((n) => !shadowed.includes(n))), entered), parent, key);
367
+ return '';
368
+ }
369
+ }
370
+ const target = node.type === 'AssignmentExpression' ? node.left : node.type === 'UpdateExpression' ? node.argument : null;
371
+ if (target?.type === 'Identifier' && active.has(target.name))
372
+ found.push({ name: target.name, start: target.start });
373
+ if (target && target.type !== 'Identifier' && target.type !== 'MemberExpression') {
374
+ const written = new Set();
375
+ patternNames(target, written);
376
+ for (const name of written)
377
+ if (active.has(name))
378
+ found.push({ name, start: target.start });
379
+ }
380
+ return undefined;
381
+ };
382
+ print(parseScript(code), code, visit(names, new WeakSet()));
383
+ return found;
384
+ }
309
385
  export function referencesNames(expr, names) {
310
386
  let found = false;
311
387
  print(parseExpr(expr), expr, (node, parent, key) => {
@@ -0,0 +1,7 @@
1
+ import { type Ctx, type Signal } from '../runtime/index.ts';
2
+ import type { Form, FormOptions } from './types.ts';
3
+ export type { Form, FormError, FormOptions, Path, StandardSchema } from './types.ts';
4
+ /** The form's engine. `values`: its state (on the server, where the compiler passes a plain value, it only renders). */
5
+ export declare function form<T extends object>(values: Signal<T> | T, options?: FormOptions<T>): Form<T>;
6
+ /** [engine]="f" (compiled): connect the element marked data-cl-form="index" to its form until the island goes. */
7
+ export declare function connect(ctx: Ctx, index: number, get: () => Form<any>): void;