clarusjs 0.19.1 → 0.21.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 (63) hide show
  1. package/README.md +1 -1
  2. package/dist/check/generate.js +124 -25
  3. package/dist/cli/index.js +17 -0
  4. package/dist/cli/migrate-files.d.ts +5 -0
  5. package/dist/cli/migrate-files.js +22 -0
  6. package/dist/cli/migrate.d.ts +8 -0
  7. package/dist/cli/migrate.js +317 -0
  8. package/dist/compiler/emit-client.js +7 -4
  9. package/dist/compiler/emit-server.js +10 -3
  10. package/dist/compiler/factories.d.ts +38 -0
  11. package/dist/compiler/factories.js +273 -0
  12. package/dist/compiler/html-expr.d.ts +4 -0
  13. package/dist/compiler/html-expr.js +5 -1
  14. package/dist/compiler/index.js +8 -9
  15. package/dist/compiler/ir.d.ts +13 -0
  16. package/dist/compiler/ir.js +41 -12
  17. package/dist/compiler/jsdoc.d.ts +15 -0
  18. package/dist/compiler/jsdoc.js +81 -0
  19. package/dist/compiler/lint.js +9 -4
  20. package/dist/compiler/parse.d.ts +35 -9
  21. package/dist/compiler/parse.js +77 -8
  22. package/dist/compiler/script.d.ts +15 -5
  23. package/dist/compiler/script.js +112 -18
  24. package/dist/compiler/shared.d.ts +5 -0
  25. package/dist/compiler/shared.js +5 -3
  26. package/dist/compiler/strip-types.d.ts +20 -0
  27. package/dist/compiler/strip-types.js +148 -0
  28. package/dist/forms/index.js +26 -5
  29. package/dist/runtime/context.d.ts +39 -0
  30. package/dist/runtime/context.js +4 -0
  31. package/dist/runtime/fragments.js +6 -2
  32. package/dist/runtime/index.d.ts +1 -0
  33. package/dist/runtime/index.js +1 -0
  34. package/dist/runtime/navigate.js +2 -1
  35. package/dist/runtime/signals.d.ts +11 -6
  36. package/dist/runtime/signals.js +12 -3
  37. package/dist/vite/base-clash.d.ts +9 -0
  38. package/dist/vite/base-clash.js +54 -0
  39. package/dist/vite/build-app.d.ts +5 -0
  40. package/dist/vite/build-app.js +185 -0
  41. package/dist/vite/dev-server.d.ts +5 -0
  42. package/dist/vite/dev-server.js +67 -0
  43. package/dist/vite/graph.d.ts +45 -0
  44. package/dist/vite/graph.js +125 -0
  45. package/dist/vite/hmr.d.ts +19 -0
  46. package/dist/vite/hmr.js +53 -0
  47. package/dist/vite/links.d.ts +2 -0
  48. package/dist/vite/links.js +2 -0
  49. package/dist/vite/options.d.ts +147 -0
  50. package/dist/vite/options.js +1 -0
  51. package/dist/vite/output.d.ts +25 -0
  52. package/dist/vite/output.js +49 -0
  53. package/dist/vite/plugin.d.ts +4 -150
  54. package/dist/vite/plugin.js +68 -624
  55. package/dist/vite/preview.d.ts +3 -0
  56. package/dist/vite/preview.js +100 -0
  57. package/dist/vite/server-entry.d.ts +18 -0
  58. package/dist/vite/server-entry.js +83 -0
  59. package/dist/vite/shared.d.ts +34 -0
  60. package/dist/vite/shared.js +47 -0
  61. package/dist/vite/styles.d.ts +16 -0
  62. package/dist/vite/styles.js +56 -0
  63. package/package.json +6 -4
@@ -0,0 +1,317 @@
1
+ import { parse as acornParse, parseExpressionAt } from 'acorn';
2
+ import { parse } from '../compiler/parse.js';
3
+ import { compile } from '../compiler/index.js';
4
+ const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
5
+ function bindingNames(p, out = []) {
6
+ if (!p)
7
+ return out;
8
+ if (p.type === 'Identifier')
9
+ out.push(p.name);
10
+ else if (p.type === 'ObjectPattern')
11
+ for (const x of p.properties)
12
+ bindingNames(x.type === 'RestElement' ? x.argument : x.value, out);
13
+ else if (p.type === 'ArrayPattern')
14
+ for (const x of p.elements)
15
+ bindingNames(x, out);
16
+ else if (p.type === 'AssignmentPattern')
17
+ bindingNames(p.left, out);
18
+ else if (p.type === 'RestElement')
19
+ bindingNames(p.argument, out);
20
+ return out;
21
+ }
22
+ function declaredIn(body) {
23
+ return body.flatMap((s) => {
24
+ const d = s.type === 'ExportNamedDeclaration' && s.declaration ? s.declaration : s;
25
+ if (d.type === 'VariableDeclaration')
26
+ return d.declarations.flatMap((x) => bindingNames(x.id));
27
+ if ((d.type === 'FunctionDeclaration' || d.type === 'ClassDeclaration') && d.id)
28
+ return [d.id.name];
29
+ if (d.type === 'ImportDeclaration')
30
+ return d.specifiers.map((x) => x.local.name);
31
+ return [];
32
+ });
33
+ }
34
+ function renameReads(ast, names, shadow, offset, edits) {
35
+ const visit = (node, parent, key, scopes) => {
36
+ if (!node || typeof node.type !== 'string')
37
+ return;
38
+ const hidden = (name) => shadow.has(name) || scopes.some((s) => s.has(name));
39
+ if (node.type === 'Identifier') {
40
+ if (!names.has(node.name) || hidden(node.name))
41
+ return;
42
+ if (parent?.type === 'MemberExpression' && key === 'property' && !parent.computed)
43
+ return;
44
+ if ((parent?.type === 'Property' || parent?.type === 'MethodDefinition' || parent?.type === 'PropertyDefinition') && key === 'key' && !parent.computed)
45
+ return;
46
+ edits.push({ start: offset + node.start, end: offset + node.end, text: `props.${node.name}` });
47
+ return;
48
+ }
49
+ if (node.type === 'Property' && node.shorthand && node.value.type === 'Identifier' && names.has(node.value.name) && !hidden(node.value.name) && parent?.type === 'ObjectExpression') {
50
+ edits.push({ start: offset + node.start, end: offset + node.end, text: `${node.key.name}: props.${node.key.name}` });
51
+ return;
52
+ }
53
+ const pattern = (p, s) => {
54
+ if (!p)
55
+ return;
56
+ if (p.type === 'AssignmentPattern') {
57
+ pattern(p.left, s);
58
+ visit(p.right, p, 'right', s);
59
+ }
60
+ else if (p.type === 'ObjectPattern')
61
+ for (const x of p.properties) {
62
+ if (x.type === 'RestElement')
63
+ pattern(x.argument, s);
64
+ else {
65
+ if (x.computed)
66
+ visit(x.key, x, 'key', s);
67
+ pattern(x.value, s);
68
+ }
69
+ }
70
+ else if (p.type === 'ArrayPattern')
71
+ for (const x of p.elements)
72
+ pattern(x, s);
73
+ else if (p.type === 'RestElement')
74
+ pattern(p.argument, s);
75
+ };
76
+ if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
77
+ const own = new Set([...node.params.flatMap((p) => bindingNames(p)), ...(node.type === 'FunctionExpression' && node.id ? [node.id.name] : [])]);
78
+ if (node.body.type === 'BlockStatement')
79
+ for (const n of declaredIn(node.body.body))
80
+ own.add(n);
81
+ const inner = [...scopes, own];
82
+ for (const p of node.params)
83
+ pattern(p, inner);
84
+ visit(node.body, node, 'body', inner);
85
+ return;
86
+ }
87
+ if (node.type === 'Program' || node.type === 'BlockStatement' || node.type === 'StaticBlock') {
88
+ const inner = [...scopes, new Set(declaredIn(node.body))];
89
+ for (const s of node.body)
90
+ visit(s, node, 'body', inner);
91
+ return;
92
+ }
93
+ if (node.type === 'VariableDeclarator') {
94
+ pattern(node.id, scopes);
95
+ if (node.init)
96
+ visit(node.init, node, 'init', scopes);
97
+ return;
98
+ }
99
+ if (node.type === 'CatchClause') {
100
+ const inner = [...scopes, new Set(bindingNames(node.param))];
101
+ visit(node.body, node, 'body', inner);
102
+ return;
103
+ }
104
+ if (node.type === 'ForStatement' || node.type === 'ForInStatement' || node.type === 'ForOfStatement') {
105
+ const head = node.type === 'ForStatement' ? node.init : node.left;
106
+ const inner = [...scopes, new Set(head?.type === 'VariableDeclaration' ? head.declarations.flatMap((x) => bindingNames(x.id)) : [])];
107
+ for (const [k, v] of Object.entries(node))
108
+ if (v && typeof v === 'object' && k !== 'loc')
109
+ visit(v, node, k, inner);
110
+ return;
111
+ }
112
+ if (node.type === 'ImportDeclaration' || node.type === 'LabeledStatement' || node.type === 'BreakStatement' || node.type === 'ContinueStatement')
113
+ return;
114
+ if ((node.type === 'ClassDeclaration' || node.type === 'ClassExpression')) {
115
+ if (node.superClass)
116
+ visit(node.superClass, node, 'superClass', scopes);
117
+ visit(node.body, node, 'body', scopes);
118
+ return;
119
+ }
120
+ for (const [k, v] of Object.entries(node)) {
121
+ if (k === 'loc' || !v || typeof v !== 'object')
122
+ continue;
123
+ for (const c of Array.isArray(v) ? v : [v])
124
+ if (c && typeof c.type === 'string')
125
+ visit(c, node, k, scopes);
126
+ }
127
+ };
128
+ visit(ast, undefined, '', []);
129
+ }
130
+ function renameInExpression(source, text, at, names, shadow, statements, edits) {
131
+ const start = source.indexOf(text, at);
132
+ if (start === -1 || !text.trim())
133
+ return;
134
+ try {
135
+ const ast = (statements ? acornParse(text, OPTS) : parseExpressionAt(text, 0, OPTS));
136
+ renameReads(ast, names, shadow, start, edits);
137
+ }
138
+ catch { }
139
+ }
140
+ const fillNames = (params) => { try {
141
+ return bindingNames(parseExpressionAt(`(${params}) => 0`, 0, OPTS).params[0]).concat(parseExpressionAt(`(${params}) => 0`, 0, OPTS).params.slice(1).flatMap((p) => bindingNames(p)));
142
+ }
143
+ catch {
144
+ return [];
145
+ } };
146
+ function renameInTemplate(source, nodes, names, shadow, edits) {
147
+ for (const n of nodes) {
148
+ if (n.type === 'expr')
149
+ renameInExpression(source, n.expr, n.start, names, shadow, false, edits);
150
+ else if (n.type === 'element') {
151
+ for (const a of n.attrs) {
152
+ if (a.kind === 'interp') {
153
+ for (const p of a.parts)
154
+ if (typeof p !== 'string')
155
+ renameInExpression(source, p.expr, p.start, names, shadow, false, edits);
156
+ }
157
+ else if (a.kind !== 'static')
158
+ renameInExpression(source, a.expr, source.indexOf('=', a.start + a.name.length) + 1, names, shadow, a.kind === 'event', edits);
159
+ }
160
+ renameInTemplate(source, n.children, names, shadow, edits);
161
+ }
162
+ else if (n.type === 'if') {
163
+ for (const b of n.branches) {
164
+ if (b.cond)
165
+ renameInExpression(source, b.cond, b.condStart, names, shadow, false, edits);
166
+ renameInTemplate(source, b.children, names, shadow, edits);
167
+ }
168
+ }
169
+ else if (n.type === 'for') {
170
+ renameInExpression(source, n.list, n.listStart, names, shadow, false, edits);
171
+ const inner = new Set([...shadow, n.item, ...n.aliases.map((a) => a.name)]);
172
+ if (n.track)
173
+ renameInExpression(source, n.track, n.trackStart, names, inner, false, edits);
174
+ renameInTemplate(source, n.children, names, inner, edits);
175
+ if (n.empty)
176
+ renameInTemplate(source, n.empty, names, shadow, edits);
177
+ }
178
+ else if (n.type === 'await') {
179
+ renameInExpression(source, n.expr, n.exprStart, names, shadow, false, edits);
180
+ renameInTemplate(source, n.pending, names, shadow, edits);
181
+ if (n.then)
182
+ renameInTemplate(source, n.then.children, names, new Set([...shadow, n.then.name]), edits);
183
+ if (n.catch)
184
+ renameInTemplate(source, n.catch.children, names, new Set([...shadow, n.catch.name]), edits);
185
+ }
186
+ else if (n.type === 'fill')
187
+ renameInTemplate(source, n.children, names, new Set([...shadow, ...(n.params ? fillNames(n.params) : [])]), edits);
188
+ }
189
+ }
190
+ const indentDoc = (doc, indent) => doc.split('\n').map((l, i) => (i === 0 ? l.trim() : ` ${l.trim()}`)).join(`\n${indent}`);
191
+ const lineEnd = (source, at) => { const n = source.indexOf('\n', at); return n === -1 ? source.length : n + 1; };
192
+ export function migrate(source, file) {
193
+ const parsed = parse(source, file);
194
+ const notes = [];
195
+ const inputs = parsed.inputs.filter((i) => !i.model);
196
+ const models = parsed.inputs.filter((i) => i.model);
197
+ if (!inputs.length && !models.length && !parsed.events.length && !parsed.types.length && !parsed.typeImports.length)
198
+ return { code: source, notes };
199
+ if (parsed.contexts.length)
200
+ notes.push(`${file}: @context ${parsed.contexts.map((c) => c.name).join(', ')} kept (context() reads through a typed key; see the context guide)`);
201
+ if (parsed.props || parsed.script?.factories?.length)
202
+ return { code: source, notes: [...notes, `${file}: already uses props()/model()/events(); left as it is`] };
203
+ const edits = [];
204
+ let island = true;
205
+ try {
206
+ island = compile(source, { file, target: 'client' }).code.trim() !== 'export {}';
207
+ }
208
+ catch { }
209
+ const commentBefore = (at) => {
210
+ const before = source.slice(0, at).replace(/\s+$/, '');
211
+ if (!before.endsWith('--}}'))
212
+ return undefined;
213
+ const start = before.lastIndexOf('{{--');
214
+ if (start === -1 || !/\S/.test(source.slice(0, start)))
215
+ return undefined;
216
+ const lines = before.slice(start + 4, -4).trim().split('\n').map((l) => l.trim()).filter(Boolean);
217
+ return { start, doc: lines.length === 1 ? `/** ${lines[0]} */` : `/**\n${lines.map((l) => ` * ${l}`).join('\n')}\n */` };
218
+ };
219
+ for (const d of [...parsed.inputs, ...parsed.types])
220
+ if (!d.doc) {
221
+ const c = commentBefore(d.start);
222
+ if (c)
223
+ Object.assign(d, { doc: c.doc, commentStart: c.start });
224
+ }
225
+ const withDoc = (start, doc) => {
226
+ const from = parsed.inputs.concat(parsed.types).find((d) => d.start === start)?.commentStart;
227
+ if (from !== undefined)
228
+ return from;
229
+ const at = doc ? source.lastIndexOf(doc, start) : -1;
230
+ return at === -1 ? start : at;
231
+ };
232
+ const drop = (from, last) => edits.push({ start: from, end: lineEnd(source, last), text: '' });
233
+ for (const i of parsed.inputs)
234
+ drop(withDoc(i.start, i.doc), i.defaultStart !== undefined ? i.defaultStart + i.default.length - 1 : i.typeStart + i.type.length - 1);
235
+ for (const t of parsed.types)
236
+ drop(withDoc(t.start, t.doc), t.typeStart + t.type.length - 1);
237
+ for (const t of parsed.typeImports)
238
+ drop(t.start, t.start);
239
+ for (const e of parsed.events)
240
+ drop(e.start, e.start);
241
+ const dataImports = island ? [] : parsed.dataImports;
242
+ for (const d of dataImports)
243
+ drop(d.start, d.start);
244
+ if (island)
245
+ for (const d of parsed.dataImports)
246
+ notes.push(`${file}: @import ${d.clause} from '${d.from}' kept (an island: as a script import it would ship to the browser)`);
247
+ const scriptTag = parsed.script ? source.lastIndexOf('<script', parsed.script.start) : -1;
248
+ const jsScript = !!parsed.script && !/\blang=/.test(source.slice(scriptTag, parsed.script.start)) && !parsed.types.length && !parsed.typeImports.length;
249
+ const closes = [...inputs, ...models, ...parsed.events].some((d) => d.type.includes('*/'));
250
+ if (jsScript && closes)
251
+ notes.push(`${file}: a type contains */, which would end a JSDoc comment: its <script> becomes TypeScript instead`);
252
+ const js = jsScript && !closes;
253
+ const scriptCode = parsed.script?.code ?? '';
254
+ const propsType = ['Props', 'ComponentProps', 'InputProps'].find((n) => !new RegExp(`\\b${n}\\b`).test(scriptCode)) ?? `Props${scriptCode.length}`;
255
+ const proseOf = (doc) => doc?.replace(/^\/\*\*|\*\/$/g, '').split('\n').map((l) => l.replace(/^\s*\*?\s?/, '').trim()).filter(Boolean).join(' ');
256
+ const decl = [];
257
+ for (const d of dataImports)
258
+ decl.push(`import ${d.clause} from '${d.from}'`);
259
+ for (const t of parsed.typeImports)
260
+ decl.push(`import type ${t.clause} from '${t.from}'`);
261
+ for (const t of parsed.types)
262
+ decl.push(...(t.doc ? [indentDoc(t.doc, ' ')] : []), t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ${t.type}` : `type ${t.name}${t.params ?? ''} = ${t.type}`);
263
+ const defaultsOf = (list) => { const d = list.filter((i) => i.default !== undefined); return d.length ? `() => ({ ${d.map((i) => `${i.name}: ${i.default}`).join(', ')} })` : ''; };
264
+ const modelDefault = (m) => (m.default !== undefined ? `() => ${/^\{/.test(m.default) ? `(${m.default})` : m.default}` : '');
265
+ if (js) {
266
+ if (inputs.length) {
267
+ const lines = inputs.map((i) => { const d = proseOf(i.doc); return ` * @property {${i.type}} ${i.default !== undefined ? `[${i.name}]` : i.name}${d ? ` - ${d}` : ''}`; });
268
+ decl.push(`/**\n * @typedef {object} ${propsType}\n${lines.join('\n')}\n */`, `/** @type {${propsType}} */`, `const props = props(${defaultsOf(inputs)})`);
269
+ }
270
+ for (const m of models) {
271
+ const d = proseOf(m.doc);
272
+ decl.push(d ? `/**\n * ${d}\n * @type {${m.type}}\n */` : `/** @type {${m.type}} */`, `let ${m.name} = model(${modelDefault(m)})`);
273
+ }
274
+ if (parsed.events.length)
275
+ decl.push(`/** @type {{ ${parsed.events.map((e) => `${e.name}: ${e.type}`).join(', ')} }} */`, 'const emit = events()');
276
+ }
277
+ else {
278
+ if (inputs.length) {
279
+ const members = inputs.map((i) => `${i.doc ? ` ${indentDoc(i.doc, ' ')}\n` : ''} ${i.name}${i.default !== undefined ? '?' : ''}: ${i.type}`);
280
+ decl.push(`const props = props<{\n${members.join('\n')}\n }>(${defaultsOf(inputs)})`);
281
+ }
282
+ for (const m of models)
283
+ decl.push(...(m.doc ? [indentDoc(m.doc, ' ')] : []), `let ${m.name} = model<${m.type}>(${modelDefault(m)})`);
284
+ if (parsed.events.length)
285
+ decl.push(`const emit = events<{ ${parsed.events.map((e) => `${e.name}: ${e.type}`).join('; ')} }>()`);
286
+ }
287
+ const block = decl.map((l) => ` ${l}`).join('\n');
288
+ const names = new Set(inputs.map((i) => i.name));
289
+ if (names.size) {
290
+ renameInTemplate(source, parsed.nodes, names, new Set(), edits);
291
+ for (const s of [parsed.script])
292
+ if (s)
293
+ renameReads(acornParse(s.code, OPTS), names, new Set(), s.start, edits);
294
+ if (parsed.serverScript)
295
+ notes.push(`${file}: its <script server> reads inputs by name; left as it is (props.name there too, by hand)`);
296
+ }
297
+ if (parsed.script) {
298
+ const s = parsed.script;
299
+ const tag = source.lastIndexOf('<script', s.start);
300
+ if (!js && !/\blang=/.test(source.slice(tag, s.start))) {
301
+ edits.push({ start: tag + '<script'.length, end: tag + '<script'.length, text: ' lang="ts"' });
302
+ notes.push(`${file}: its <script> is now TypeScript: give its untyped function parameters types (clarusjs check lists them)`);
303
+ }
304
+ const imports = acornParse(s.code, OPTS).body.filter((x) => x.type === 'ImportDeclaration');
305
+ const at = imports.length ? s.start + imports[imports.length - 1].end : s.start;
306
+ edits.push({ start: at, end: at, text: `${imports.length ? '\n' : '\n'}${block}${imports.length ? '' : '\n'}` });
307
+ }
308
+ else {
309
+ const first = Math.min(...[...parsed.inputs.map((i) => withDoc(i.start, i.doc)), ...parsed.types.map((t) => withDoc(t.start, t.doc)), ...parsed.typeImports.map((t) => t.start), ...parsed.events.map((e) => e.start), ...dataImports.map((d) => d.start)]);
310
+ edits.push({ start: first, end: first, text: `<script lang="ts">\n${block}\n</script>\n\n` });
311
+ }
312
+ edits.sort((a, b) => b.start - a.start || (a.end === a.start ? 1 : 0) - (b.end === b.start ? 1 : 0));
313
+ let code = source;
314
+ for (const e of edits)
315
+ code = code.slice(0, e.start) + e.text + code.slice(e.end);
316
+ return { code: code.replace(/\n{3,}/g, '\n\n'), notes };
317
+ }
@@ -1,6 +1,6 @@
1
1
  import { guardCode } from './events.js';
2
2
  import { FOR_IMPLICIT } from './parse.js';
3
- import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
3
+ import { attrValue, attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
4
4
  import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
5
5
  import { contextLines, indentScript, inputsLine, renderName } from './shared.js';
6
6
  export function emitClient(ir, hot) {
@@ -17,6 +17,7 @@ export function emitClient(ir, hot) {
17
17
  (kinds.has('state') || kinds.has('input')) && 'state',
18
18
  kinds.has('derived') && 'derived',
19
19
  kinds.has('shared') && 'shared',
20
+ ir.effect && 'effect',
20
21
  hasHoles && 'holes as __cl_holes',
21
22
  hasHoles && 'text as __cl_text',
22
23
  ir.events.length > 0 && 'on as __cl_on',
@@ -44,7 +45,7 @@ export function emitClient(ir, hot) {
44
45
  rendersHtml && hasFors && 'forHtml as __cl_forHtml',
45
46
  hasRegions && 'regionHtml as __cl_regionHtml',
46
47
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
47
- all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
48
+ all.some((n) => n.kind === 'attr' && n.name !== '...' && !!n.base) && 'baseUrl as __cl_baseUrl',
48
49
  all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
49
50
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
50
51
  ].filter(Boolean);
@@ -74,7 +75,7 @@ export function emitClient(ir, hot) {
74
75
  out += ` __cl_declare(__cl_root, ${JSON.stringify(ir.sendNames)})\n`;
75
76
  if (ir.sends)
76
77
  out += ` const emit = (name, value, info) => __cl_emit(__cl_root, name, value, info)\n`;
77
- out += contextLines(ir, 'undefined');
78
+ out += contextLines(ir, '__cl_props.__cl_cx');
78
79
  if (ir.provides)
79
80
  out += ` __cl_provideOn(__cl_root, __cl_cx)\n`;
80
81
  const inputs = ir.inputs.filter((i) => ir.signals.get(i.name) === 'input' || ir.signals.get(i.name) === 'model');
@@ -85,6 +86,8 @@ export function emitClient(ir, hot) {
85
86
  : ` const ${i.name} = state(${value(i, '__cl_props')})\n`;
86
87
  }
87
88
  out += inputsLine({ ...ir, inputs: ir.inputs.filter((i) => !inputs.includes(i)) });
89
+ if (ir.props)
90
+ out += ` const ${ir.props.name} = { ${ir.props.keys.map((k) => `get ${k}() { return ${rewriteClientExpr(k, ir.signals)} }`).join(', ')} }\n`;
88
91
  if (ir.script)
89
92
  out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true, forms: formName(ir.scriptImports) }));
90
93
  const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
@@ -117,7 +120,7 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
117
120
  if (a.kind === 'attr' && a.reactive && a.name === '...')
118
121
  lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${a.base ? `__cl_baseAttrs(${JSON.stringify(a.base)}, ${attrValueExpr(a.value, rw.expr)})` : attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
119
122
  else if (a.kind === 'attr' && a.reactive)
120
- lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
123
+ lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValue(a, rw.expr)}${tagArg(a)})`);
121
124
  if (a.kind === 'connect')
122
125
  lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
123
126
  if (a.kind === 'use')
@@ -1,6 +1,6 @@
1
1
  import { asWritten, htmlExpr, walk } from './html-expr.js';
2
2
  import { rewriteServer } from './script.js';
3
- import { contextLines, indentScript, inputsLine, renderName } from './shared.js';
3
+ import { contextLines, contextName, indentScript, inputsLine, renderName } from './shared.js';
4
4
  export function emitServer(ir, clientUrl, renderImports = false, loader) {
5
5
  const all = walk(ir.nodes);
6
6
  const html = htmlExpr(ir.nodes, asWritten, { island: ir.stateful ? ir.name : null, top: true });
@@ -12,7 +12,7 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
12
12
  html.includes('__cl_spreadHtml(') && 'spreadHtml as __cl_spreadHtml',
13
13
  html.includes('__cl_passedHtml(') && 'passedHtml as __cl_passedHtml',
14
14
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
15
- all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
15
+ all.some((n) => n.kind === 'attr' && n.name !== '...' && !!n.base) && 'baseUrl as __cl_baseUrl',
16
16
  all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
17
17
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
18
18
  all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
@@ -32,9 +32,14 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
32
32
  out += `import ${d.clause} from '${d.from}'\n`;
33
33
  for (const line of ir.scriptImports)
34
34
  out += `${line}\n`;
35
+ if (ir.effect)
36
+ out += `import { effect } from 'clarusjs/runtime'\n`;
35
37
  for (const line of ir.server?.imports ?? [])
36
38
  out += `${line}\n`;
37
- const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
39
+ const notPublic = (c) => `(() => { throw new Error("[clarusjs] <${ir.name}> is an island and reads context \\"" + ${contextName(c)} + "\\", which isn't public: its value would be written into the page. The key it's read with and the key it's provided with must both be contextKey(name, { public: true })") })()`;
40
+ const sendable = (c) => `${c.key}.public === true && (!__cl_cx || !{}.hasOwnProperty.call(__cl_cx, ${contextName(c)}) || __cl_cx[Symbol.for("clarusjs.publicContext")]?.has(${contextName(c)}) === true)`;
41
+ const cx = ir.contexts.length ? [`__cl_cx: { ${ir.contexts.map((c) => (c.key ? `[${contextName(c)}]: ${sendable(c)} ? ${c.name} : ${notPublic(c)}` : `[${contextName(c)}]: ${c.name}`)).join(', ')} }`] : [];
42
+ const props = `{ ${[...ir.inputs.map((i) => i.name), ...cx, '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
38
43
  out += `\nexport ${ir.server?.awaits ? 'async ' : ''}function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
39
44
  out += unknownSlotCheck(ir);
40
45
  if (!ir.stateful)
@@ -42,6 +47,8 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
42
47
  if (loader)
43
48
  out += ` __cl_props = { ...__cl_loaded(${JSON.stringify(loader)}), ...__cl_props }\n`;
44
49
  out += inputsLine(ir);
50
+ if (ir.props)
51
+ out += ` const ${ir.props.name} = { ${ir.props.keys.join(', ')} }\n`;
45
52
  out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
46
53
  if (html.includes('__cl_attrs'))
47
54
  out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))}${ir.extends ? `, ${JSON.stringify(ir.extends)}` : ''})\n`;
@@ -0,0 +1,38 @@
1
+ export type FactoryInput = {
2
+ name: string;
3
+ type: string;
4
+ nameStart: number;
5
+ typeStart: number;
6
+ default?: string; /** The default as written (TypeScript), for type checking. */
7
+ defaultTs?: string;
8
+ defaultStart?: number;
9
+ model?: true;
10
+ optional?: true;
11
+ doc?: string;
12
+ start: number;
13
+ };
14
+ export type FactoryEvent = {
15
+ name: string;
16
+ type: string;
17
+ nameStart: number;
18
+ typeStart: number;
19
+ start: number;
20
+ };
21
+ export type FactoryContext = Omit<FactoryInput, 'model'> & {
22
+ key?: string;
23
+ };
24
+ export type Factories = {
25
+ inputs: FactoryInput[];
26
+ events: FactoryEvent[];
27
+ contexts: FactoryContext[];
28
+ props?: {
29
+ name: string;
30
+ keys: string[];
31
+ };
32
+ blank: [number, number][]; /** The names their arguments use at runtime (a key, a default's import): not type members. */
33
+ refs: string[];
34
+ };
35
+ /** The factories in `code` (TypeScript, as written; or JavaScript with JSDoc types, with `js: true`). */
36
+ export declare function factories(code: string, js?: string, options?: {
37
+ js?: boolean;
38
+ }): Factories;