clarusjs 0.0.1 → 0.1.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/LICENSE +21 -0
- package/dist/compiler/emit-client.d.ts +2 -0
- package/dist/compiler/emit-client.js +34 -0
- package/dist/compiler/emit-server.d.ts +2 -0
- package/dist/compiler/emit-server.js +28 -0
- package/dist/compiler/errors.d.ts +7 -0
- package/dist/compiler/errors.js +16 -0
- package/dist/compiler/index.d.ts +11 -0
- package/dist/compiler/index.js +14 -0
- package/dist/compiler/ir.d.ts +35 -0
- package/dist/compiler/ir.js +92 -0
- package/dist/compiler/parse.d.ts +52 -0
- package/dist/compiler/parse.js +189 -0
- package/dist/compiler/script.d.ts +18 -0
- package/dist/compiler/script.js +287 -0
- package/dist/compiler/shared.d.ts +6 -0
- package/dist/compiler/shared.js +26 -0
- package/dist/runtime/dom.d.ts +14 -0
- package/dist/runtime/dom.js +70 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.js +3 -0
- package/dist/runtime/loader.d.ts +5 -0
- package/dist/runtime/loader.js +42 -0
- package/dist/runtime/server.d.ts +4 -0
- package/dist/runtime/server.js +26 -0
- package/dist/runtime/signals.d.ts +10 -0
- package/dist/runtime/signals.js +53 -0
- package/dist/server/handler.d.ts +9 -0
- package/dist/server/handler.js +26 -0
- package/dist/vite/node.d.ts +3 -0
- package/dist/vite/node.js +15 -0
- package/dist/vite/plugin.d.ts +4 -0
- package/dist/vite/plugin.js +80 -0
- package/package.json +77 -8
- package/README.md +0 -7
- package/index.js +0 -1
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// <script> analysis and signal rewrites. Reads `count` → `count.get()`, writes `count++` → `count.set(count.get() + 1)`.
|
|
2
|
+
import { parse as acornParse, parseExpressionAt } from 'acorn';
|
|
3
|
+
import { ClarusError } from './errors.js';
|
|
4
|
+
const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
|
|
5
|
+
function isNode(v) {
|
|
6
|
+
return !!v && typeof v.type === 'string' && typeof v.start === 'number';
|
|
7
|
+
}
|
|
8
|
+
// Child slots that hold names, not reads.
|
|
9
|
+
function isBinding(parent, key) {
|
|
10
|
+
if (!parent)
|
|
11
|
+
return false;
|
|
12
|
+
switch (parent.type) {
|
|
13
|
+
case 'MemberExpression': return key === 'property' && !parent.computed;
|
|
14
|
+
case 'Property':
|
|
15
|
+
case 'MethodDefinition':
|
|
16
|
+
case 'PropertyDefinition': return key === 'key' && !parent.computed;
|
|
17
|
+
case 'VariableDeclarator': return key === 'id';
|
|
18
|
+
case 'FunctionDeclaration':
|
|
19
|
+
case 'FunctionExpression':
|
|
20
|
+
case 'ArrowFunctionExpression': return key === 'id' || key === 'params';
|
|
21
|
+
case 'LabeledStatement':
|
|
22
|
+
case 'BreakStatement':
|
|
23
|
+
case 'ContinueStatement': return key === 'label';
|
|
24
|
+
case 'ImportSpecifier':
|
|
25
|
+
case 'ImportDefaultSpecifier':
|
|
26
|
+
case 'ExportSpecifier': return true;
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
// Print `node` from `code`, replacing any subtree for which `hook` returns a string.
|
|
31
|
+
function print(node, code, hook, parent = null, key = '') {
|
|
32
|
+
const replaced = hook(node, parent, key);
|
|
33
|
+
if (replaced !== undefined)
|
|
34
|
+
return replaced;
|
|
35
|
+
const kids = [];
|
|
36
|
+
for (const [k, v] of Object.entries(node)) {
|
|
37
|
+
if (Array.isArray(v))
|
|
38
|
+
for (const c of v) {
|
|
39
|
+
if (isNode(c))
|
|
40
|
+
kids.push({ node: c, key: k });
|
|
41
|
+
}
|
|
42
|
+
else if (isNode(v) && k !== 'loc')
|
|
43
|
+
kids.push({ node: v, key: k });
|
|
44
|
+
}
|
|
45
|
+
kids.sort((a, b) => a.node.start - b.node.start);
|
|
46
|
+
let out = '';
|
|
47
|
+
let pos = node.start;
|
|
48
|
+
for (const kid of kids) {
|
|
49
|
+
if (kid.node.start < pos)
|
|
50
|
+
continue; // shorthand property: key and value share a range
|
|
51
|
+
out += code.slice(pos, kid.node.start) + print(kid.node, code, hook, node, kid.key);
|
|
52
|
+
pos = kid.node.end;
|
|
53
|
+
}
|
|
54
|
+
return out + code.slice(pos, node.end);
|
|
55
|
+
}
|
|
56
|
+
function parseScript(code, file = '<script>', source = code, offset = 0) {
|
|
57
|
+
try {
|
|
58
|
+
return acornParse(code, OPTS);
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
const pos = e.pos ?? 0;
|
|
62
|
+
throw new ClarusError(`script: ${e.message.replace(/ \(\d+:\d+\)$/, '')}`, file, source, offset + pos);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function parseExpr(expr) {
|
|
66
|
+
const ast = parseExpressionAt(expr, 0, OPTS);
|
|
67
|
+
// acorn drops wrapping parens from the node range: `({ a })` gives a node ending before `)`. Allow exactly those.
|
|
68
|
+
const open = (expr.slice(0, ast.start).match(/\(/g) ?? []).length;
|
|
69
|
+
if (!/^[\s(]*$/.test(expr.slice(0, ast.start)) || expr.slice(ast.end).replace(/\s/g, '') !== ')'.repeat(open)) {
|
|
70
|
+
throw Object.assign(new SyntaxError('expected a single expression'), { pos: ast.end });
|
|
71
|
+
}
|
|
72
|
+
return ast;
|
|
73
|
+
}
|
|
74
|
+
function located(fn, what, file, source, offset) {
|
|
75
|
+
try {
|
|
76
|
+
return fn();
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
if (e instanceof ClarusError)
|
|
80
|
+
throw e;
|
|
81
|
+
throw new ClarusError(`${what}: ${e.message.replace(/ \(\d+:\d+\)$/, '')}`, file, source, offset);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Throw a located ClarusError unless `expr` is exactly one JS expression. */
|
|
85
|
+
export function checkExpr(expr, file, source, offset) {
|
|
86
|
+
located(() => parseExpr(expr), 'invalid expression', file, source, offset);
|
|
87
|
+
}
|
|
88
|
+
/** Throw a located ClarusError unless `code` parses as statements (event handlers may hold several). */
|
|
89
|
+
export function checkHandler(code, file, source, offset) {
|
|
90
|
+
const ast = located(() => acornParse(code, OPTS), 'invalid event handler', file, source, offset);
|
|
91
|
+
if (ast.body.some((n) => n.type === 'ImportDeclaration' || n.type.startsWith('Export'))) {
|
|
92
|
+
throw new ClarusError('imports and exports in event handlers are not supported', file, source, offset);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Every name bound by a declaration pattern: `a`, `{ a, b: [c] }`, `...rest`, `x = 1`. */
|
|
96
|
+
function patternNames(p, out = new Set()) {
|
|
97
|
+
if (!p)
|
|
98
|
+
return out;
|
|
99
|
+
switch (p.type) {
|
|
100
|
+
case 'Identifier':
|
|
101
|
+
out.add(p.name);
|
|
102
|
+
break;
|
|
103
|
+
case 'ObjectPattern':
|
|
104
|
+
for (const prop of p.properties)
|
|
105
|
+
patternNames(prop.type === 'RestElement' ? prop.argument : prop.value, out);
|
|
106
|
+
break;
|
|
107
|
+
case 'ArrayPattern':
|
|
108
|
+
for (const el of p.elements)
|
|
109
|
+
patternNames(el, out);
|
|
110
|
+
break;
|
|
111
|
+
case 'AssignmentPattern':
|
|
112
|
+
patternNames(p.left, out);
|
|
113
|
+
break;
|
|
114
|
+
case 'RestElement':
|
|
115
|
+
patternNames(p.argument, out);
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** Names a scope node declares for its own body (params, block-level declarations, loop heads, catch params). */
|
|
121
|
+
function scopeNames(node) {
|
|
122
|
+
const names = new Set();
|
|
123
|
+
const declare = (stmt) => {
|
|
124
|
+
if (stmt.type === 'VariableDeclaration')
|
|
125
|
+
for (const d of stmt.declarations)
|
|
126
|
+
patternNames(d.id, names);
|
|
127
|
+
else if ((stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration') && stmt.id)
|
|
128
|
+
names.add(stmt.id.name);
|
|
129
|
+
};
|
|
130
|
+
switch (node.type) {
|
|
131
|
+
case 'FunctionDeclaration':
|
|
132
|
+
case 'FunctionExpression':
|
|
133
|
+
case 'ArrowFunctionExpression':
|
|
134
|
+
for (const p of node.params)
|
|
135
|
+
patternNames(p, names);
|
|
136
|
+
if (node.type === 'FunctionExpression' && node.id)
|
|
137
|
+
names.add(node.id.name);
|
|
138
|
+
if (node.body.type === 'BlockStatement')
|
|
139
|
+
node.body.body.forEach(declare);
|
|
140
|
+
break;
|
|
141
|
+
case 'BlockStatement':
|
|
142
|
+
node.body.forEach(declare);
|
|
143
|
+
break;
|
|
144
|
+
case 'ForStatement':
|
|
145
|
+
if (node.init)
|
|
146
|
+
declare(node.init);
|
|
147
|
+
break;
|
|
148
|
+
case 'ForInStatement':
|
|
149
|
+
case 'ForOfStatement':
|
|
150
|
+
declare(node.left);
|
|
151
|
+
break;
|
|
152
|
+
case 'CatchClause':
|
|
153
|
+
patternNames(node.param, names);
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
return names;
|
|
157
|
+
}
|
|
158
|
+
/** [start, end] ranges of template literals in `code`, so formatting never touches their contents. */
|
|
159
|
+
export function templateRanges(code) {
|
|
160
|
+
const ranges = [];
|
|
161
|
+
print(parseScript(code), code, (node) => {
|
|
162
|
+
if (node.type === 'TemplateLiteral')
|
|
163
|
+
ranges.push([node.start, node.end]);
|
|
164
|
+
return undefined;
|
|
165
|
+
});
|
|
166
|
+
return ranges;
|
|
167
|
+
}
|
|
168
|
+
/** Parenthesize expressions whose meaning changes when inlined as an argument or arrow body (`a, b`, `{ … }`). */
|
|
169
|
+
export function wrapExpr(expr) {
|
|
170
|
+
const t = parseExpr(expr).type;
|
|
171
|
+
return t === 'SequenceExpression' || t === 'ObjectExpression' ? `(${expr})` : expr;
|
|
172
|
+
}
|
|
173
|
+
/** Names declared at the top level of <script>: variables, functions, classes. */
|
|
174
|
+
export function scriptNames(code) {
|
|
175
|
+
const names = new Set();
|
|
176
|
+
for (const stmt of parseScript(code).body) {
|
|
177
|
+
if (stmt.type === 'VariableDeclaration') {
|
|
178
|
+
for (const d of stmt.declarations)
|
|
179
|
+
patternNames(d.id, names);
|
|
180
|
+
}
|
|
181
|
+
else if ((stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration') && stmt.id) {
|
|
182
|
+
names.add(stmt.id.name);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return names;
|
|
186
|
+
}
|
|
187
|
+
function signalCall(init) {
|
|
188
|
+
if (init?.type !== 'CallExpression' || init.callee.type !== 'Identifier')
|
|
189
|
+
return undefined;
|
|
190
|
+
return init.callee.name === 'state' || init.callee.name === 'derived' ? init.callee.name : undefined;
|
|
191
|
+
}
|
|
192
|
+
export function analyzeScript(code, file, source, offset) {
|
|
193
|
+
const signals = new Map();
|
|
194
|
+
for (const stmt of parseScript(code, file, source, offset).body) {
|
|
195
|
+
if (stmt.type === 'ImportDeclaration' || stmt.type.startsWith('Export')) {
|
|
196
|
+
throw new ClarusError('imports in <script> are not supported yet', file, source, offset + stmt.start);
|
|
197
|
+
}
|
|
198
|
+
if (stmt.type !== 'VariableDeclaration')
|
|
199
|
+
continue;
|
|
200
|
+
for (const d of stmt.declarations) {
|
|
201
|
+
const kind = signalCall(d.init);
|
|
202
|
+
if (kind && d.id.type === 'Identifier')
|
|
203
|
+
signals.set(d.id.name, kind);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return signals;
|
|
207
|
+
}
|
|
208
|
+
// Scope-aware: a parameter or local that shadows a signal name turns the rewrite off inside that scope.
|
|
209
|
+
// ponytail: `var` declared in nested blocks is not hoisted to the function scope here; add if it ever matters
|
|
210
|
+
function clientHook(code, signals, entered = new WeakSet()) {
|
|
211
|
+
const hook = (node, parent, key) => {
|
|
212
|
+
const rec = (n) => print(n, code, hook, node, '');
|
|
213
|
+
const isSignal = (n) => n.type === 'Identifier' && signals.has(n.name);
|
|
214
|
+
if (!entered.has(node)) {
|
|
215
|
+
const shadowed = [...scopeNames(node)].filter((n) => signals.has(n));
|
|
216
|
+
if (shadowed.length) {
|
|
217
|
+
entered.add(node);
|
|
218
|
+
const inner = new Map([...signals].filter(([n]) => !shadowed.includes(n)));
|
|
219
|
+
return print(node, code, clientHook(code, inner, entered), parent, key);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (node.type === 'VariableDeclaration' && node.kind === 'let' && node.declarations.every((d) => signalCall(d.init))) {
|
|
223
|
+
return 'const' + print({ ...node, kind: 'const', start: node.start + 3 }, code, hook, parent, key);
|
|
224
|
+
}
|
|
225
|
+
if (node.type === 'UpdateExpression' && isSignal(node.argument)) {
|
|
226
|
+
const name = node.argument.name;
|
|
227
|
+
const op = node.operator[0];
|
|
228
|
+
if (parent?.type === 'ExpressionStatement')
|
|
229
|
+
return `${name}.set(${name}.get() ${op} 1)`; // value unused
|
|
230
|
+
return node.prefix
|
|
231
|
+
? `(${name}.set(${name}.get() ${op} 1), ${name}.get())`
|
|
232
|
+
: `((__cl_v) => (${name}.set(__cl_v ${op} 1), __cl_v))(${name}.get())`;
|
|
233
|
+
}
|
|
234
|
+
if (node.type === 'AssignmentExpression' && isSignal(node.left)) {
|
|
235
|
+
const name = node.left.name;
|
|
236
|
+
const right = rec(node.right);
|
|
237
|
+
return node.operator === '='
|
|
238
|
+
? `${name}.set(${right})`
|
|
239
|
+
: `${name}.set(${name}.get() ${node.operator.slice(0, -1)} (${right}))`;
|
|
240
|
+
}
|
|
241
|
+
if (node.type === 'Property' && node.shorthand && isSignal(node.value)) {
|
|
242
|
+
return `${node.key.name}: ${node.value.name}.get()`;
|
|
243
|
+
}
|
|
244
|
+
if (isSignal(node) && !isBinding(parent, key))
|
|
245
|
+
return `${node.name}.get()`;
|
|
246
|
+
return undefined;
|
|
247
|
+
};
|
|
248
|
+
return hook;
|
|
249
|
+
}
|
|
250
|
+
export function rewriteClient(code, signals) {
|
|
251
|
+
const ast = parseScript(code);
|
|
252
|
+
return code.slice(0, ast.start) + print(ast, code, clientHook(code, signals)) + code.slice(ast.end);
|
|
253
|
+
}
|
|
254
|
+
export function rewriteClientExpr(expr, signals) {
|
|
255
|
+
const ast = parseExpr(expr);
|
|
256
|
+
return expr.slice(0, ast.start) + print(ast, expr, clientHook(expr, signals)) + expr.slice(ast.end);
|
|
257
|
+
}
|
|
258
|
+
export function rewriteServer(code) {
|
|
259
|
+
const ast = parseScript(code);
|
|
260
|
+
const hook = (node) => {
|
|
261
|
+
if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier')
|
|
262
|
+
return undefined;
|
|
263
|
+
const arg = node.arguments[0];
|
|
264
|
+
const inner = arg ? print(arg, code, hook) : 'undefined';
|
|
265
|
+
if (node.callee.name === 'state')
|
|
266
|
+
return `(${inner})`;
|
|
267
|
+
if (node.callee.name === 'derived')
|
|
268
|
+
return `(${inner})()`;
|
|
269
|
+
return undefined;
|
|
270
|
+
};
|
|
271
|
+
return code.slice(0, ast.start) + print(ast, code, hook) + code.slice(ast.end);
|
|
272
|
+
}
|
|
273
|
+
export function referencesSignal(expr, signals) {
|
|
274
|
+
return referencesNames(expr, new Set(signals.keys()));
|
|
275
|
+
}
|
|
276
|
+
/** Does `expr` read any of `names`? */
|
|
277
|
+
export function referencesNames(expr, names) {
|
|
278
|
+
let found = false;
|
|
279
|
+
print(parseExpr(expr), expr, (node, parent, key) => {
|
|
280
|
+
if (node.type === 'Identifier' && names.has(node.name) && !isBinding(parent, key))
|
|
281
|
+
found = true;
|
|
282
|
+
if (node.type === 'Property' && node.shorthand && names.has(node.value?.name))
|
|
283
|
+
found = true;
|
|
284
|
+
return undefined;
|
|
285
|
+
});
|
|
286
|
+
return found;
|
|
287
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { ComponentIR } from './ir.ts';
|
|
2
|
+
/** `const { start = 0, name } = props`, or '' when the component has no inputs. */
|
|
3
|
+
export declare function inputsLine(ir: ComponentIR): string;
|
|
4
|
+
/** Dedent a script block and indent it by two spaces, one statement line per line. */
|
|
5
|
+
export declare function indentScript(code: string): string;
|
|
6
|
+
export declare const renderName: (name: string) => string;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { templateRanges } from './script.js';
|
|
2
|
+
/** `const { start = 0, name } = props`, or '' when the component has no inputs. */
|
|
3
|
+
export function inputsLine(ir) {
|
|
4
|
+
if (!ir.inputs.length)
|
|
5
|
+
return '';
|
|
6
|
+
const parts = ir.inputs.map((i) => (i.default !== undefined ? `${i.name} = ${i.default}` : i.name));
|
|
7
|
+
return ` const { ${parts.join(', ')} } = __cl_props\n`;
|
|
8
|
+
}
|
|
9
|
+
/** Dedent a script block and indent it by two spaces, one statement line per line. */
|
|
10
|
+
export function indentScript(code) {
|
|
11
|
+
const body = code.replace(/^\s*\n/, '').replace(/\s+$/, '');
|
|
12
|
+
const ranges = templateRanges(body);
|
|
13
|
+
let offset = 0;
|
|
14
|
+
const lines = body.split('\n').map((text) => {
|
|
15
|
+
const start = offset;
|
|
16
|
+
offset += text.length + 1;
|
|
17
|
+
// A line that starts inside a template literal is string content: never re-indent it.
|
|
18
|
+
return { text, literal: ranges.some(([a, b]) => start > a && start < b) };
|
|
19
|
+
});
|
|
20
|
+
const code_ = lines.filter((l) => !l.literal && l.text.trim());
|
|
21
|
+
const indent = Math.min(...code_.map((l) => l.text.match(/^\s*/)[0].length));
|
|
22
|
+
return lines.map((l) => (l.literal ? l.text : ' ' + l.text.slice(indent))).join('\n') + '\n';
|
|
23
|
+
}
|
|
24
|
+
// Generated names carry a __cl_ prefix so they can't collide with names in the author's <script>.
|
|
25
|
+
// `-` maps to `$`, which import names cannot contain after the first character, so the mapping is one-to-one.
|
|
26
|
+
export const renderName = (name) => '__cl_render_' + name.replace(/-/g, '$');
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type Hole = {
|
|
2
|
+
start: Comment;
|
|
3
|
+
end: Comment;
|
|
4
|
+
};
|
|
5
|
+
/** Find `<!--[N-->…<!--]-->` pairs inside `root`, skipping nested islands. Returns holes indexed by N. */
|
|
6
|
+
export declare function holes(root: Element): Hole[];
|
|
7
|
+
/** Keep exactly one text node between the hole's markers, set to `fn()`. */
|
|
8
|
+
export declare function text(hole: Hole, fn: () => unknown): void;
|
|
9
|
+
/**
|
|
10
|
+
* Register a handler for elements marked `data-cl-e="index"` inside this island.
|
|
11
|
+
* 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()`.
|
|
13
|
+
*/
|
|
14
|
+
export declare function on(root: Element, index: number, type: string, fn: (e: Event) => void): void;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Attach helpers: find hole markers in server HTML and keep them updated. Browser only. Never re-renders.
|
|
2
|
+
import { effect } from './signals.js';
|
|
3
|
+
/** Find `<!--[N-->…<!--]-->` pairs inside `root`, skipping nested islands. Returns holes indexed by N. */
|
|
4
|
+
export function holes(root) {
|
|
5
|
+
const found = [];
|
|
6
|
+
const open = [];
|
|
7
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT, {
|
|
8
|
+
acceptNode: (n) => n.nodeType === 8 ? NodeFilter.FILTER_ACCEPT
|
|
9
|
+
: n !== root && n.localName === 'cl-island' ? NodeFilter.FILTER_REJECT
|
|
10
|
+
: NodeFilter.FILTER_SKIP,
|
|
11
|
+
});
|
|
12
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
13
|
+
const data = n.data;
|
|
14
|
+
if (/^\[\d+$/.test(data))
|
|
15
|
+
open.push({ index: Number(data.slice(1)), start: n });
|
|
16
|
+
else if (data === ']' && open.length) {
|
|
17
|
+
const { index, start } = open.pop();
|
|
18
|
+
found[index] = { start, end: n };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return found;
|
|
22
|
+
}
|
|
23
|
+
/** Keep exactly one text node between the hole's markers, set to `fn()`. */
|
|
24
|
+
export function text(hole, fn) {
|
|
25
|
+
effect(() => {
|
|
26
|
+
const value = fn();
|
|
27
|
+
const s = value == null ? '' : String(value);
|
|
28
|
+
const first = hole.start.nextSibling;
|
|
29
|
+
if (first && first !== hole.end && first.nodeType === 3 && first.nextSibling === hole.end) {
|
|
30
|
+
if (first.data !== s)
|
|
31
|
+
first.data = s;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
while (hole.start.nextSibling && hole.start.nextSibling !== hole.end)
|
|
35
|
+
hole.start.nextSibling.remove();
|
|
36
|
+
hole.end.before(document.createTextNode(s));
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
const registry = new WeakMap();
|
|
40
|
+
// These don't bubble, so they are caught on the way down instead.
|
|
41
|
+
const CAPTURE = new Set(['focus', 'blur']);
|
|
42
|
+
/**
|
|
43
|
+
* Register a handler for elements marked `data-cl-e="index"` inside this island.
|
|
44
|
+
* One listener per island per event type; it walks from the target up to the island root, running handlers
|
|
45
|
+
* innermost first and stopping when one calls `stopPropagation()`.
|
|
46
|
+
*/
|
|
47
|
+
export function on(root, index, type, fn) {
|
|
48
|
+
let types = registry.get(root);
|
|
49
|
+
if (!types)
|
|
50
|
+
registry.set(root, (types = new Map()));
|
|
51
|
+
let handlers = types.get(type);
|
|
52
|
+
if (!handlers) {
|
|
53
|
+
const own = (handlers = new Map());
|
|
54
|
+
types.set(type, own);
|
|
55
|
+
root.addEventListener(type, (e) => {
|
|
56
|
+
for (let el = e.target; el && el !== root.parentElement; el = el.parentElement) {
|
|
57
|
+
const i = el.getAttribute?.('data-cl-e');
|
|
58
|
+
if (i === null || i === undefined || el.closest('cl-island') !== root)
|
|
59
|
+
continue;
|
|
60
|
+
for (const h of own.get(Number(i)) ?? [])
|
|
61
|
+
h(e);
|
|
62
|
+
if (e.cancelBubble)
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}, CAPTURE.has(type));
|
|
66
|
+
}
|
|
67
|
+
if (!handlers.has(index))
|
|
68
|
+
handlers.set(index, []);
|
|
69
|
+
handlers.get(index).push(fn);
|
|
70
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Island loader: finds <cl-island> elements, loads each one's chunk, calls attach(). Browser only, ~20 lines.
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
// Islands whose chunk is being fetched. `data-cl-ready` is set only after attach() succeeds.
|
|
11
|
+
const loading = new WeakSet();
|
|
12
|
+
export async function attachAll(root = document, load = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src))) {
|
|
13
|
+
const islands = [...root.querySelectorAll('cl-island:not([data-cl-ready]):not([data-cl-error])')].filter((el) => !loading.has(el));
|
|
14
|
+
const pending = islands.map(async (el) => {
|
|
15
|
+
loading.add(el);
|
|
16
|
+
let mod;
|
|
17
|
+
let props;
|
|
18
|
+
try {
|
|
19
|
+
mod = await load(el.getAttribute('src'));
|
|
20
|
+
props = JSON.parse(el.getAttribute('p') ?? '{}');
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
loading.delete(el); // network or parse failure: the next attachAll() retries
|
|
24
|
+
console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to load`, err);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
mod.attach(el, props);
|
|
29
|
+
el.setAttribute('data-cl-ready', '');
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
el.setAttribute('data-cl-error', ''); // attach may have wired some listeners already: never retry
|
|
33
|
+
console.error(`[clarusjs] island "${el.getAttribute('c')}" failed to attach`, err);
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
loading.delete(el);
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
await Promise.all(pending);
|
|
40
|
+
}
|
|
41
|
+
if (typeof document !== 'undefined')
|
|
42
|
+
attachAll();
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
|
|
2
|
+
export declare function escape(value: unknown): string;
|
|
3
|
+
/** Wrap a stateful component's HTML in its island boundary: name, client chunk URL, serialized props. */
|
|
4
|
+
export declare function island(name: string, src: string, props: Record<string, unknown>, html: string): string;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
|
|
2
|
+
const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
3
|
+
/** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
|
|
4
|
+
export function escape(value) {
|
|
5
|
+
if (value == null)
|
|
6
|
+
return '';
|
|
7
|
+
return String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
|
|
8
|
+
}
|
|
9
|
+
function assertSerializable(value, path) {
|
|
10
|
+
const t = typeof value;
|
|
11
|
+
if (t === 'function' || t === 'symbol' || t === 'bigint') {
|
|
12
|
+
throw new TypeError(`[clarusjs] island prop "${path}" is a ${t}; island props must be JSON-serializable`);
|
|
13
|
+
}
|
|
14
|
+
if (t === 'number' && !Number.isFinite(value)) {
|
|
15
|
+
throw new TypeError(`[clarusjs] island prop "${path}" is ${value}; island props must be JSON-serializable`);
|
|
16
|
+
}
|
|
17
|
+
if (value && t === 'object') {
|
|
18
|
+
for (const [k, v] of Object.entries(value))
|
|
19
|
+
assertSerializable(v, path ? `${path}.${k}` : k);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Wrap a stateful component's HTML in its island boundary: name, client chunk URL, serialized props. */
|
|
23
|
+
export function island(name, src, props, html) {
|
|
24
|
+
assertSerializable(props, '');
|
|
25
|
+
return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(JSON.stringify(props))}">${html}</cl-island>`;
|
|
26
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type Signal<T> = {
|
|
2
|
+
get(): T;
|
|
3
|
+
set(v: T): void;
|
|
4
|
+
};
|
|
5
|
+
export type ReadSignal<T> = {
|
|
6
|
+
get(): T;
|
|
7
|
+
};
|
|
8
|
+
export declare function state<T>(initial: T): Signal<T>;
|
|
9
|
+
export declare function effect(fn: () => void): () => void;
|
|
10
|
+
export declare function derived<T>(fn: () => T): ReadSignal<T>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Fine-grained reactivity used by compiled attach() functions. Browser only.
|
|
2
|
+
let current = null;
|
|
3
|
+
export function state(initial) {
|
|
4
|
+
let value = initial;
|
|
5
|
+
const subs = new Set();
|
|
6
|
+
return {
|
|
7
|
+
get() {
|
|
8
|
+
if (current?.active) {
|
|
9
|
+
subs.add(current);
|
|
10
|
+
current.deps.add(subs);
|
|
11
|
+
}
|
|
12
|
+
return value;
|
|
13
|
+
},
|
|
14
|
+
set(v) {
|
|
15
|
+
if (Object.is(v, value))
|
|
16
|
+
return;
|
|
17
|
+
value = v;
|
|
18
|
+
for (const e of [...subs])
|
|
19
|
+
if (e.active)
|
|
20
|
+
e.run(); // an effect disposed earlier in this loop must not run
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export function effect(fn) {
|
|
25
|
+
const e = {
|
|
26
|
+
deps: new Set(),
|
|
27
|
+
active: true,
|
|
28
|
+
run() {
|
|
29
|
+
if (!e.active)
|
|
30
|
+
return;
|
|
31
|
+
for (const subs of e.deps)
|
|
32
|
+
subs.delete(e);
|
|
33
|
+
e.deps.clear();
|
|
34
|
+
const prev = current;
|
|
35
|
+
current = e;
|
|
36
|
+
try {
|
|
37
|
+
fn();
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
current = prev;
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
e.run();
|
|
45
|
+
return () => { e.active = false; for (const subs of e.deps)
|
|
46
|
+
subs.delete(e); e.deps.clear(); };
|
|
47
|
+
}
|
|
48
|
+
// ponytail: eager derived, may compute twice on diamond graphs; switch to push-pull (alien-signals style) when nested derived lands
|
|
49
|
+
export function derived(fn) {
|
|
50
|
+
const s = state(undefined);
|
|
51
|
+
effect(() => s.set(fn()));
|
|
52
|
+
return { get: s.get };
|
|
53
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
type PageModule = {
|
|
2
|
+
render(props?: object): string;
|
|
3
|
+
};
|
|
4
|
+
/** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
|
|
5
|
+
export declare function routeFromFile(file: string): string;
|
|
6
|
+
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>): {
|
|
7
|
+
fetch(request: Request): Promise<Response>;
|
|
8
|
+
};
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// The fetch handler: Request → Response. Same function for dev, per-request SSR and (later) build-time prerender.
|
|
2
|
+
/** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
|
|
3
|
+
export function routeFromFile(file) {
|
|
4
|
+
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.clarus$/, '').replace(/\/index$/, '');
|
|
5
|
+
return path || '/';
|
|
6
|
+
}
|
|
7
|
+
export function createHandler(pages) {
|
|
8
|
+
const routes = new Map(Object.entries(pages).map(([file, load]) => [routeFromFile(file), load]));
|
|
9
|
+
return {
|
|
10
|
+
async fetch(request) {
|
|
11
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
12
|
+
return new Response('Method Not Allowed', { status: 405 });
|
|
13
|
+
const load = routes.get(new URL(request.url).pathname);
|
|
14
|
+
const head = request.method === 'HEAD';
|
|
15
|
+
if (!load)
|
|
16
|
+
return new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
17
|
+
const html = (await load()).render({});
|
|
18
|
+
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk.
|
|
19
|
+
const hasIslands = html.replace(/<!--[\s\S]*?-->/g, '').includes('<cl-island ');
|
|
20
|
+
const scripts = hasIslands ? '<script type="module" src="/cl-loader.js"></script>' : '';
|
|
21
|
+
const style = hasIslands ? '<style>cl-island{display:contents}</style>' : ''; // islands never affect layout
|
|
22
|
+
const body = `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title>${style}</head><body>${html}${scripts}</body></html>`;
|
|
23
|
+
return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function toRequest(req) {
|
|
2
|
+
const headers = new Headers();
|
|
3
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
4
|
+
if (Array.isArray(value))
|
|
5
|
+
value.forEach((v) => headers.append(key, v));
|
|
6
|
+
else if (value !== undefined)
|
|
7
|
+
headers.set(key, value);
|
|
8
|
+
}
|
|
9
|
+
return new Request(`http://${req.headers.host ?? 'localhost'}${req.url ?? '/'}`, { method: req.method, headers });
|
|
10
|
+
}
|
|
11
|
+
export async function sendResponse(res, response) {
|
|
12
|
+
res.statusCode = response.status;
|
|
13
|
+
response.headers.forEach((value, key) => res.setHeader(key, value));
|
|
14
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
15
|
+
}
|