@hidemikimura/vanji 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,391 @@
1
+ // Turns one html`` template into "clone the static HTML + walk to the dynamic nodes + bind".
2
+ import { parseHTML, serialize, isSvgOnly, TemplateError, HO, HC } from './parse-html.js';
3
+ import { walk, isFn, hasCall, hasFnOrTemplate, arrowBody, IDENT } from './ast.js';
4
+ import { emitList } from './list.js';
5
+
6
+ /**
7
+ * @param {{ code: string, id: string, use: (name: string) => string, isHtmlTag: Function, isEach: Function,
8
+ * isWhen: Function, templates: Map<string, object>, handled: Set<object>, fail: Function }} ctx
9
+ */
10
+ export function createTemplateCompiler(ctx) {
11
+ const { code, use, isHtmlTag, isEach, isWhen, templates, handled, reads } = ctx;
12
+ const calls = n => hasCall(n, isHtmlTag, reads);
13
+ const generated = new Map();
14
+
15
+ const isComponentCall = n =>
16
+ n.type === 'CallExpression' && !n.optional && n.callee.type === 'Identifier' && /^[A-Z]/.test(n.callee.name);
17
+
18
+ /**
19
+ * Source of `node` with nested html`` compiled, component calls wrapped (`Card(x)` -> `_$c(Card, x)`)
20
+ * and the item / index of a live each() row read through its getter (`r.n` -> `_$$it().n`).
21
+ */
22
+ const source = node => {
23
+ const reps = [];
24
+ walk(node, n => {
25
+ if (isHtmlTag(n) || isComponentCall(n) || reads.has(n)) {
26
+ reps.push(n);
27
+ return false;
28
+ }
29
+ });
30
+ reps.sort((a, b) => a.start - b.start);
31
+ let out = '', pos = node.start;
32
+ for (const r of reps) {
33
+ out += code.slice(pos, r.start);
34
+ if (isHtmlTag(r)) out += genTemplate(r);
35
+ else if (reads.has(r)) out += reads.get(r);
36
+ else {
37
+ const args = r.arguments.map(a => (a.type === 'SpreadElement' ? `...${source(a.argument)}` : source(a)));
38
+ out += `${use('c')}(${[r.callee.name, ...args].join(', ')})`;
39
+ }
40
+ pos = r.end;
41
+ }
42
+ out += code.slice(pos, node.end);
43
+ return node.type === 'SequenceExpression' ? `(${out})` : out;
44
+ };
45
+
46
+ function genTemplate(tpl) {
47
+ let out = generated.get(tpl);
48
+ if (out === undefined) generated.set(tpl, (out = genTemplateUncached(tpl)));
49
+ return out;
50
+ }
51
+
52
+ /** Parse and validate a template: { tree, roots, exprs, kind, err }. */
53
+ function parseTemplate(tpl) {
54
+ const at = { line: tpl.loc.start.line, column: tpl.loc.start.column };
55
+ const err = (message, hint, node) =>
56
+ ctx.fail(message, hint, node ? { line: node.loc.start.line, column: node.loc.start.column } : at);
57
+ const quasis = tpl.quasi.quasis;
58
+ const exprs = tpl.quasi.expressions;
59
+ let src = '';
60
+ quasis.forEach((q, i) => {
61
+ if (q.value.cooked == null) err('Invalid escape sequence in template');
62
+ src += q.value.cooked;
63
+ if (i < exprs.length) src += HO + i + HC;
64
+ });
65
+ let tree;
66
+ try {
67
+ tree = parseHTML(src);
68
+ } catch (e) {
69
+ if (e instanceof TemplateError) err(e.message, e.hint);
70
+ throw e;
71
+ }
72
+ exprs.forEach(expr =>
73
+ walk(expr, n => {
74
+ if (isFn(n)) return false;
75
+ if (n.type === 'AwaitExpression' || n.type === 'YieldExpression')
76
+ err(
77
+ `"${n.type === 'AwaitExpression' ? 'await' : 'yield'}" cannot be used directly inside a template hole`,
78
+ 'Assign the result to a variable before the template.',
79
+ n
80
+ );
81
+ })
82
+ );
83
+ const roots = tree.children;
84
+ // holes at the root: the template returns an array (nodes and the holes' parts), see genTemplateUncached
85
+ const rootHoles = roots.some(n => n.type === 'hole');
86
+ let kind = roots.length === 1 && !rootHoles ? 0 : 1;
87
+ const rootEls = roots.filter(n => n.type === 'el');
88
+ if (rootEls.length && rootEls.every(n => isSvgOnly(n.tag))) kind |= 2;
89
+ else if (rootEls.some(n => isSvgOnly(n.tag)))
90
+ err('SVG and HTML elements cannot be mixed at the template root', 'Wrap SVG content in <svg>.');
91
+
92
+ const markDynamic = el => {
93
+ let dyn = false;
94
+ for (const a of el.attrs) {
95
+ const special = /^[@.?]/.test(a.name) || a.name === 'ref';
96
+ const hasHole = a.parts && a.parts.some(p => typeof p !== 'string');
97
+ if (special && !(a.parts && a.parts.length === 1 && hasHole))
98
+ err(`"${a.name}" must be bound to exactly one hole`, `Write ${a.name}=\${value} (no quotes mixing text and holes).`);
99
+ a.dynamic = !!hasHole;
100
+ dyn ||= a.dynamic;
101
+ }
102
+ if (el.tag.includes('-')) kind |= 4;
103
+ if (el.tag.toLowerCase() === 'template' && el.children.length) {
104
+ let holes = false;
105
+ walk({ type: 'x', c: el.children }, n => {
106
+ if (n.type === 'hole' || (n.type === 'el' && n.attrs.some(a => a.parts && a.parts.some(p => typeof p !== 'string'))))
107
+ holes = true;
108
+ });
109
+ if (holes) err('Holes are not supported inside a nested <template> element');
110
+ }
111
+ for (const c of el.children) {
112
+ if (c.type === 'hole') dyn = true;
113
+ else if (c.type === 'el') dyn = markDynamic(c) || dyn;
114
+ }
115
+ return (el.dyn = dyn);
116
+ };
117
+ for (const n of roots) if (n.type === 'el') markDynamic(n);
118
+ return { tree, roots, exprs, kind, err, rootHoles };
119
+ }
120
+
121
+ /**
122
+ * Where the dynamic parts are. `decls` reach them right after cloning (firstChild / nextSibling);
123
+ * `path` is an element-only path from the root ("$"), still valid after holes were filled when
124
+ * `safe` (no hole precedes it among its parent's children).
125
+ */
126
+ function layout(t, root) {
127
+ const decls = [], binds = [];
128
+ let uid = 0;
129
+ // <select .value> / .selectedIndex only take effect once the options exist: bind them after the children
130
+ const late = (el, a) => el.tag.toLowerCase() === 'select' && (a.name === '.value' || a.name === '.selectedIndex');
131
+ const visitEl = (el, v, path, safe) => {
132
+ for (const a of el.attrs) if (a.dynamic && !late(el, a)) binds.push({ type: 'attr', el: v, a, path, safe });
133
+ visitKids(el, v, path, safe);
134
+ for (const a of el.attrs) if (a.dynamic && late(el, a)) binds.push({ type: 'attr', el: v, a, path, safe });
135
+ };
136
+ const visitKids = (parent, v, path, safe) => {
137
+ const kids = parent.children;
138
+ if (parent.type === 'el' && kids.length === 1 && kids[0].type === 'hole') {
139
+ binds.push({ type: 'text', parent: v, marker: null, index: kids[0].index, path, safe });
140
+ return;
141
+ }
142
+ let prev = '', prevEl = null, holeBefore = false;
143
+ kids.forEach((c, k) => {
144
+ const access = k === 0 ? `${v}.firstChild` : `${prev}.nextSibling`;
145
+ const elPath = c.type === 'el' ? (prevEl === null ? `${path}.firstElementChild` : `${prevEl}.nextElementSibling`) : null;
146
+ if (c.type === 'hole' || (c.type === 'el' && c.dyn)) {
147
+ const name = `_$$e${uid++}`;
148
+ decls.push(`${name} = ${access}`);
149
+ prev = name;
150
+ if (c.type === 'hole') {
151
+ binds.push({ type: 'text', parent: v, marker: name, index: c.index, path, safe });
152
+ holeBefore = true;
153
+ } else visitEl(c, name, elPath, safe && !holeBefore);
154
+ } else prev = access;
155
+ if (elPath) prevEl = elPath;
156
+ });
157
+ };
158
+ if (t.kind & 1) visitKids(t.tree, root, null, false);
159
+ else if (t.roots[0].type === 'el' && t.roots[0].dyn) visitEl(t.roots[0], root, '$', true);
160
+ return { decls, binds };
161
+ }
162
+
163
+ /** The `_tmpl$N` factory for a parsed template (identical templates share one). */
164
+ function register(t) {
165
+ const html = serialize(t.tree);
166
+ const key = t.kind + html;
167
+ let tmpl = templates.get(key);
168
+ if (!tmpl) templates.set(key, (tmpl = { name: `_tmpl$${templates.size}`, html, kind: t.kind }));
169
+ return tmpl.name;
170
+ }
171
+
172
+ const api = { source, parseTemplate, layout, register, use, isHtmlTag, isEach, isWhen, handled, reads, calls };
173
+
174
+ function genTemplateUncached(tpl) {
175
+ const t = parseTemplate(tpl);
176
+ const { exprs, err } = t;
177
+ const { decls, binds } = layout(t, '_$$r');
178
+ const stmts = [];
179
+ const src = i => source(exprs[i]);
180
+ // reactive body of a hole, or null when the hole is static
181
+ const dynBody = i => {
182
+ const b = arrowBody(exprs[i]);
183
+ if (b) return `(${source(b)})`;
184
+ return calls(exprs[i]) ? `(${src(i)})` : null;
185
+ };
186
+ const noDirective = (i, where) => {
187
+ const e = exprs[i];
188
+ if (isEach(e) || isWhen(e))
189
+ err(`${e.callee.name || e.callee.property.name}() can only be used as content, not in ${where}`, 'Write it between tags: html`<ul>${each(…)}</ul>`.', e);
190
+ };
191
+
192
+ // Holes of a live each() row that read only its item / index (no other call): one effect per template
193
+ // re-evaluates them all and writes the ones that changed, instead of an effect per hole.
194
+ const readsRow = e => {
195
+ let found = false;
196
+ walk(e, n => {
197
+ if (found || isFn(n) || isHtmlTag(n)) return false;
198
+ if (reads.has(n)) found = true;
199
+ });
200
+ return found;
201
+ };
202
+ const rowOnly = i => {
203
+ const e = exprs[i];
204
+ return readsRow(e) && !hasCall(e, isHtmlTag) && !hasFnOrTemplate(e, isHtmlTag) && !isEach(e) && !isWhen(e);
205
+ };
206
+ const group = [], groupVars = [];
207
+ const memo = (value, write) => {
208
+ const k = group.length, pv = `_$$g${k}`;
209
+ groupVars.push(pv);
210
+ group.push(`if (${pv} !== (_$$t = (${value}))) { ${pv} = _$$t; ${write} }`);
211
+ };
212
+
213
+ const parts = new Map(); // root hole index -> its part in the returned array
214
+ for (const b of binds) {
215
+ if (b.type === 'text' && t.rootHoles && b.parent === '_$$r') {
216
+ // a root hole cannot insert into the fragment (it is emptied when inserted somewhere): it becomes
217
+ // a part of the returned array, resolved by whoever renders the array (src/dom.js memo / nodes)
218
+ const e = exprs[b.index];
219
+ let part;
220
+ if (isEach(e)) part = genericEach(e, api, err);
221
+ else if (isWhen(e)) part = whenCall(e, api, err);
222
+ else {
223
+ const body = dynBody(b.index);
224
+ part = body ? `${use('memo')}(() => ${body})` : `${use('nodes')}(${src(b.index)})`;
225
+ }
226
+ parts.set(b.index, part);
227
+ continue;
228
+ }
229
+ if (b.type === 'text') {
230
+ const e = exprs[b.index], at = b.marker ? `, ${b.marker}` : '';
231
+ if (isEach(e)) stmts.push(emitEach(e, b.parent, b.marker, api, err));
232
+ else if (isWhen(e)) stmts.push(`${use('insert')}(${b.parent}, ${whenCall(e, api, err)}${at});`);
233
+ else if (rowOnly(b.index)) {
234
+ if (b.marker === null) memo(src(b.index), `${use('text')}(${b.parent}, _$$t);`);
235
+ else {
236
+ const n = `_$$n${groupVars.length}`;
237
+ groupVars.push(n);
238
+ memo(src(b.index), `${n} = ${use('place')}(${b.parent}, _$$t, ${n}, ${b.marker});`);
239
+ }
240
+ } else {
241
+ const body = dynBody(b.index);
242
+ stmts.push(`${use('insert')}(${b.parent}, ${body ? `() => ${body}` : src(b.index)}${at});`);
243
+ }
244
+ continue;
245
+ }
246
+ const { el: v, a } = b, name = a.name;
247
+ const single = a.parts.length === 1 ? a.parts[0].hole : -1;
248
+ if (single >= 0) noDirective(single, `"${name}"`);
249
+ if (name[0] === '@') {
250
+ const [type, ...mods] = name.slice(1).split('.');
251
+ if (mods.length)
252
+ err(`Unknown modifier ".${mods[0]}" in "${name}"`, 'Event modifiers are not supported: call e.preventDefault() / e.stopPropagation() in the handler.');
253
+ stmts.push(`${v}.addEventListener(${JSON.stringify(type)}, ${src(single)});`);
254
+ } else if (name === 'ref') {
255
+ stmts.push(`(${src(single)})(${v});`);
256
+ } else if (name[0] === '.') {
257
+ // a property gets the value as is (a function stays a function); it is reactive when it calls one
258
+ const p = name.slice(1), target = IDENT.test(p) ? `${v}.${p}` : `${v}[${JSON.stringify(p)}]`;
259
+ if (rowOnly(single)) memo(src(single), `${target} = _$$t;`);
260
+ else if (calls(exprs[single])) stmts.push(`${use('effect')}(() => { ${target} = (${src(single)}); });`);
261
+ else stmts.push(`${target} = ${src(single)};`);
262
+ } else if (name[0] === '?') {
263
+ const n = JSON.stringify(name.slice(1)), body = dynBody(single);
264
+ if (rowOnly(single)) memo(src(single), `${v}.toggleAttribute(${n}, !!_$$t);`);
265
+ else if (body) stmts.push(`${use('effect')}(() => { ${v}.toggleAttribute(${n}, !!${body}); });`);
266
+ else stmts.push(`${use('bool')}(${v}, ${n}, ${src(single)});`);
267
+ } else if (single >= 0) {
268
+ const n = JSON.stringify(name), body = dynBody(single);
269
+ if (rowOnly(single)) memo(src(single), `${use('setAttr')}(${v}, ${n}, _$$t);`);
270
+ else if (body) stmts.push(`${use('effect')}(() => { ${use('setAttr')}(${v}, ${n}, ${body}); });`);
271
+ else stmts.push(`${use('attr')}(${v}, ${n}, ${src(single)});`);
272
+ } else {
273
+ // class="a ${x} b"
274
+ const holes = a.parts.filter(p => typeof p !== 'string').map(p => p.hole);
275
+ if (holes.some(rowOnly) && holes.every(i => rowOnly(i) || !dynBody(i))) {
276
+ const value = a.parts.map(p => (typeof p === 'string' ? JSON.stringify(p) : `${use('str')}(${src(p.hole)})`)).join(' + ');
277
+ memo(value, `${use('setAttr')}(${v}, ${JSON.stringify(name)}, _$$t);`);
278
+ continue;
279
+ }
280
+ let dyn = false;
281
+ const pieces = a.parts.map(p => {
282
+ if (typeof p === 'string') return JSON.stringify(p);
283
+ noDirective(p.hole, `"${name}"`);
284
+ const body = dynBody(p.hole);
285
+ if (body) dyn = true;
286
+ return `${use('str')}(${body || src(p.hole)})`;
287
+ });
288
+ const set = `${use('setAttr')}(${v}, ${JSON.stringify(name)}, ${pieces.join(' + ')});`;
289
+ stmts.push(dyn ? `${use('effect')}(() => { ${set} });` : set);
290
+ }
291
+ }
292
+
293
+ if (group.length)
294
+ stmts.push(`let ${groupVars.join(', ')}; ${use('effect')}(() => { let _$$t; ${group.join(' ')} });`);
295
+ const name = register(t);
296
+ if (t.rootHoles) {
297
+ const items = t.roots.map((n, k) => (n.type === 'hole' ? parts.get(n.index) : `_$$r.childNodes[${k}]`));
298
+ return `(() => { const _$$r = ${name}()${decls.map(d => `, ${d}`).join('')}; ${stmts.join(' ')} return [${items.join(', ')}]; })()`;
299
+ }
300
+ if (!stmts.length) return `${name}()`;
301
+ return `(() => { const _$$r = ${name}()${decls.map(d => `, ${d}`).join('')}; ${stmts.join(' ')} return _$$r; })()`;
302
+ }
303
+
304
+ return { genTemplate, source };
305
+ }
306
+
307
+ /** `${each(items, row, { key })}`: a fast list when the row can be compiled, else the generic each(). */
308
+ function emitEach(e, parent, marker, api, err) {
309
+ checkEach(e, api, err);
310
+ const fast = emitList(e, parent, marker, api, err);
311
+ if (fast) return fast;
312
+ return `${api.use('insert')}(${parent}, ${genericEach(e, api, err)}${marker ? `, ${marker}` : ''});`;
313
+ }
314
+
315
+ function checkEach(e, api, err) {
316
+ api.handled.add(e);
317
+ const [items, row, opts, extra] = e.arguments;
318
+ if (!items || !row) err("each() needs items and a row function: each(items, row => html`…`, { key: 'id' })", undefined, e);
319
+ if (extra || (opts && opts.type !== 'ObjectExpression'))
320
+ err(
321
+ 'each() takes (items, row, { key }): the key moved into the options',
322
+ "Write each(todos(), t => html`<li>…</li>`, { key: 'id' }) or { key: t => t.id }.",
323
+ e
324
+ );
325
+ }
326
+
327
+ /** The generic each() call (a scope per row, rows of any shape). */
328
+ function genericEach(e, api, err) {
329
+ checkEach(e, api, err);
330
+ const { source, use } = api;
331
+ const [items, row, opts] = e.arguments;
332
+ const inline = row.type === 'ArrowFunctionExpression' || row.type === 'FunctionExpression';
333
+ // flags: 1 = an index parameter (row.length misses defaults and rest), 2 = live row (see liveRow)
334
+ const ix = inline && (row.params.length > 1 || row.params.some(p => p.type === 'RestElement'));
335
+ const live = inline && liveRow(row, api.reads);
336
+ const flags = (ix ? 1 : 0) | (live ? 2 : 0);
337
+ let rowSrc = source(row);
338
+ if (live) {
339
+ const names = ['_$$it', '_$$ix'].slice(0, row.params.length);
340
+ const body = row.body.type === 'BlockStatement' ? source(row.body) : `(${source(row.body)})`;
341
+ rowSrc = row.type === 'ArrowFunctionExpression' ? `(${names.join(', ')}) => ${body}` : `function (${names.join(', ')}) ${body}`;
342
+ }
343
+ return `${use('each')}(() => (${source(items)}), ${rowSrc}${opts || flags ? `, ${opts ? source(opts) : 'undefined'}` : ''}${flags ? `, ${flags}` : ''})`;
344
+ }
345
+
346
+ /**
347
+ * A live row keeps its DOM while its key stays: its item / index parameters are read through
348
+ * getters (`r.n` -> `_$$it().n`), so holes that use them update in place. Only for plain identifier
349
+ * parameters that the row never re-declares or assigns; otherwise the row is created again instead.
350
+ */
351
+ function liveRow(row, reads) {
352
+ if (row.async || row.generator || row.params.length > 2 || row.params.some(p => p.type !== 'Identifier')) return false;
353
+ const names = new Map(row.params.map((p, k) => [p.name, k ? '_$$ix()' : '_$$it()']));
354
+ let ok = true;
355
+ const refs = [];
356
+ const visit = (n, parent, key) => {
357
+ if (!ok || !n || typeof n.type !== 'string') return;
358
+ if (n.type === 'Identifier' && names.has(n.name)) {
359
+ const declared =
360
+ ((parent.type === 'VariableDeclarator' || parent.type === 'FunctionDeclaration' || parent.type === 'ClassDeclaration' || parent.type === 'FunctionExpression' || parent.type === 'ClassExpression') && key === 'id') ||
361
+ key === 'params' || parent.type === 'CatchClause' || parent.type === 'AssignmentPattern' || parent.type === 'RestElement' || parent.type === 'ArrayPattern' ||
362
+ (parent.type === 'Property' && key === 'value' && parent.__pattern);
363
+ const assigned = (parent.type === 'AssignmentExpression' && key === 'left') || parent.type === 'UpdateExpression';
364
+ if (declared || assigned) ok = false; // re-declared or assigned: keep the plain value (row is recreated)
365
+ else if ((parent.type === 'MemberExpression' && key === 'property' && !parent.computed) || (parent.type === 'Property' && key === 'key' && !parent.computed) ||
366
+ (parent.type === 'MethodDefinition' && key === 'key') || parent.type === 'LabeledStatement' || parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') {
367
+ // a property name or a label, not a reference
368
+ } else refs.push([n, parent]);
369
+ return;
370
+ }
371
+ if (n.type === 'ObjectPattern') for (const p of n.properties) p.__pattern = true;
372
+ for (const k in n) {
373
+ if (k === '__pattern') continue;
374
+ const v = n[k];
375
+ if (Array.isArray(v)) for (const c of v) visit(c, n, k);
376
+ else if (v && typeof v.type === 'string') visit(v, n, k);
377
+ }
378
+ };
379
+ visit(row.body, row, 'body');
380
+ if (!ok) return false;
381
+ for (const [n, parent] of refs)
382
+ reads.set(n, parent.type === 'Property' && parent.shorthand ? `${n.name}: ${names.get(n.name)}` : names.get(n.name));
383
+ return true;
384
+ }
385
+
386
+ /** `when(cond, yes, no)` with every argument as a function. */
387
+ function whenCall(e, api, err) {
388
+ api.handled.add(e);
389
+ if (!e.arguments.length) err('when() needs a condition: when(cond, yes, no?)', undefined, e);
390
+ return `${api.use('when')}(${e.arguments.map(a => `() => (${api.source(a)})`).join(', ')})`;
391
+ }
@@ -0,0 +1,31 @@
1
+ /** Options of the vanji Vite / Rollup plugin. */
2
+ export interface VanjiPluginOptions {
3
+ /** Files to compile. Default: /\.[cm]?[jt]sx?$/ */
4
+ include?: RegExp;
5
+ /** Files to skip. Default: /node_modules/ */
6
+ exclude?: RegExp;
7
+ /** The import name the compiler looks for. Default: '@hidemikimura/vanji' */
8
+ moduleName?: string;
9
+ /**
10
+ * Keep the runtime's long error messages and dev-only checks.
11
+ * Default: on, except in production builds (Vite: `vite build`; Rollup: NODE_ENV=production).
12
+ */
13
+ dev?: boolean;
14
+ }
15
+
16
+ /**
17
+ * A Vite / Rollup plugin object. Typed loosely (the source map is `any`) so it is accepted by Vite's and
18
+ * Rollup's plugin types without this package depending on either.
19
+ */
20
+ export interface VanjiPlugin {
21
+ name: string;
22
+ configResolved(config: { isProduction?: boolean }): void;
23
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- the source map type differs per bundler
24
+ transform(code: string, id: string): { code: string; map: any } | null;
25
+ }
26
+
27
+ /** `import vanji from '@hidemikimura/vanji/vite'; export default { plugins: [vanji()] }` */
28
+ export default function vanji(options?: VanjiPluginOptions): VanjiPlugin;
29
+
30
+ /** Runtime source with the DEV flag replaced by `false` (what production builds get). */
31
+ export function withoutDev(code: string): string;
@@ -0,0 +1,35 @@
1
+ // Vite / Rollup plugin. Usage: import vanji from '@hidemikimura/vanji/vite'; export default { plugins: [vanji()] }
2
+ import { fileURLToPath } from 'node:url';
3
+ import { compile } from './index.js';
4
+
5
+ // The runtime's DEV flag (src/dev.js). In production builds every runtime file gets the literal `false`
6
+ // in its place (and loses the import), so any bundler drops the dev-only code while parsing.
7
+ const SRC_DIR = fileURLToPath(new URL('../src/', import.meta.url));
8
+
9
+ /** Runtime source with DEV replaced by `false` (also used by scripts/size.js). */
10
+ export const withoutDev = code =>
11
+ code.replace(/^import \{ DEV \} from '\.\/dev\.js';\n/m, '').replace(/\bDEV\b(?! = )/g, 'false');
12
+
13
+ /**
14
+ * @param {{ include?: RegExp, exclude?: RegExp, moduleName?: string, dev?: boolean }} [options]
15
+ * dev: keep long error messages and dev-only checks. Default: on, except in production builds
16
+ * (Vite: config.isProduction; Rollup: NODE_ENV === 'production').
17
+ */
18
+ export default function vanji({ include = /\.[cm]?[jt]sx?$/, exclude = /node_modules/, moduleName = '@hidemikimura/vanji', dev } = {}) {
19
+ let production = dev === undefined ? process.env.NODE_ENV === 'production' : !dev;
20
+ return {
21
+ name: 'vanji',
22
+ configResolved(config) {
23
+ if (dev === undefined) production = !!config.isProduction;
24
+ },
25
+ transform(code, id) {
26
+ const file = id.split('?')[0];
27
+ if (file.startsWith(SRC_DIR) && file.endsWith('.js')) return production ? { code: withoutDev(code), map: null } : null;
28
+ if (!include.test(file) || exclude.test(file)) return null;
29
+ const out = compile(code, { id: file, moduleName });
30
+ if (!out) return null;
31
+ for (const w of out.warnings) this.warn(`[vanji] ${file}:${w.line}:${w.column} ${w.message}`);
32
+ return { code: out.code, map: out.map };
33
+ },
34
+ };
35
+ }
package/llms.txt ADDED
@@ -0,0 +1,143 @@
1
+ # vanji — complete reference for AI assistants
2
+
3
+ vanji is a tiny UI framework: html`` templates + signals, compiled at build time.
4
+ This file is the whole API. If something is not listed here, it does not exist.
5
+ A Claude Code skill with worked examples ships next to it: skills/vanji (copy it to .claude/skills/).
6
+
7
+ ## Setup (build step is required)
8
+
9
+ npm install @hidemikimura/vanji (and Vite: npm install -D vite)
10
+
11
+ // vite.config.js
12
+ import vanji from '@hidemikimura/vanji/vite';
13
+ export default { plugins: [vanji()] };
14
+
15
+ ## Mental model (3 facts)
16
+
17
+ 1. html`...` returns REAL DOM nodes, created once. There is no re-render and no virtual DOM.
18
+ (With a hole at the root, html`${title()}<p>…</p>`, it returns an array: use it in a hole / each / when / mount.)
19
+ 2. A component is a plain function that returns that node. It runs ONCE.
20
+ 3. THE RULE: a template hole whose expression CALLS A FUNCTION is reactive; anything else is set once.
21
+ Read signals by calling them, as you would anywhere else.
22
+
23
+ const count = signal(0);
24
+ html`<p>${count()}</p>` // reactive: updates when count changes
25
+ html`<p class=${count() > 2 ? 'big' : ''}>` // reactive
26
+ html`<p>${total()}</p>` // reactive, also for signals read inside total()
27
+ html`<p>${'static'} ${someVariable}</p>` // set once (no call)
28
+
29
+ ## Public API (12 exports, all from '@hidemikimura/vanji')
30
+
31
+ signal(v) -> s s() read · s.set(v) · s.update(fn) · s.peek() untracked read
32
+ computed(fn) -> c c() read · c.peek() (lazy, cached, read-only)
33
+ effect(fn) -> stop() runs now + after each change; fn may return a cleanup function
34
+ batch(fn) several writes, one update
35
+ untrack(fn) read without subscribing
36
+ onCleanup(fn) when the current component / effect run / list row is torn down
37
+ onMount(fn) once, after the component's DOM is in the document
38
+ root(fn(dispose)) manual ownership scope (rarely needed)
39
+ html`...` -> Node template
40
+ each(items, row, { key }) keyed list, ONLY directly in a hole: ${each(todos(), t => html`<li>…</li>`, { key: 'id' })}
41
+ when(cond, yes, no?) conditional, ONLY directly in a hole: ${when(open(), html`<dialog>…</dialog>`)}
42
+ mount(Component, el) -> unmount() replaces el's content
43
+
44
+ ## Template syntax
45
+
46
+ <p>${value}</p> text / node / array / null / false (nothing)
47
+ <a href=${url}> attribute null or undefined removes it
48
+ <p class="item ${cls}"> attribute with static text + holes
49
+ <button ?disabled=${flag}> boolean attribute
50
+ <input .value=${text()}> DOM property (a function without a call is passed as the value: .onDone=${callback})
51
+ <button @click=${handler}> event listener (plain addEventListener; never reactive)
52
+ <div ref=${el => (node = el)}> element reference, called once at creation
53
+
54
+ ## Components and composition
55
+
56
+ const Greeting = (name) => html`<h1>Hello ${name()}</h1>`; // a component is a function
57
+ const App = () => html`<main>${Greeting(user)}</main>`; // call it inside a hole
58
+ mount(App, document.getElementById('app'));
59
+
60
+ A component call in a hole runs once; its body is not tracked. Pass a signal (user, not user()) when
61
+ the child must update: Greeting(user) reads user() itself. Greeting(user()) also works but creates the
62
+ whole component again whenever user changes.
63
+
64
+ ## Lists
65
+
66
+ const todos = signal([{ id: 1, title: 'a', done: false }]);
67
+ html`<ul>${each(todos(), t => html`
68
+ <li class=${t.done ? 'done' : ''}>
69
+ <input type="checkbox" .checked=${t.done} @change=${() => toggle(t.id)} />
70
+ ${t.title}
71
+ </li>`, { key: 'id' })}</ul>`
72
+ const toggle = id => todos.update(l => l.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
73
+
74
+ - items are plain objects, updated IMMUTABLY: replace an item object to update its row. The row's DOM is
75
+ kept and only the changed parts are written. Mutating an item (t.done = true) changes nothing on screen.
76
+ - key: a property name ('id') or a function (t => t.id). Without a key, the item itself is the key.
77
+ - row receives (item, index); index is a plain number and stays correct when rows move.
78
+ - Selection is cheap however long the list is: `class=${selected() === row.id ? 'on' : ''}` touches only
79
+ the old and the new row when `selected` changes (when key is that property).
80
+ - A row is created once per key and KEPT while its key stays: a replaced item (or a changed index) only
81
+ updates the parts that use it, so DOM made by the row (an editor created in onMount / ref) survives.
82
+ Read the item inside holes / handlers; a value copied at the top of a block body (const t = r.title)
83
+ stays as it was when the row was created.
84
+ - Exceptions that re-create the row when its item is replaced: a row function passed by name
85
+ (each(items(), Row, …)) or one that destructures its item (({ id }) => …). Write r => Row(r) or r => …r.id.
86
+ - Fastest rows: one root element per row; holes that read item fields directly. Rows with a block body,
87
+ several root nodes, nested templates or components work the same (a little more memory per row).
88
+
89
+ ## Conditionals
90
+
91
+ ${when(open(), html`<dialog>…</dialog>`)} // rebuilds only when open() flips true <-> false
92
+ ${when(user(), html`<p>Hi</p>`, html`<p>Sign in</p>`)}
93
+ ${open() ? html`<b>a</b>` : html`<i>b</i>`} // also valid: rebuilds on every change of open()
94
+
95
+ ## Events
96
+
97
+ @event is a plain addEventListener: native order, stopPropagation and currentTarget behave as in the DOM.
98
+ Inside list rows, every @event is handled by ONE capture listener per event type on the list's parent element
99
+ instead of one per row. Row handlers run from the target outwards, get `this` / e.currentTarget = their
100
+ element, see the row's current item, and run BEFORE the parent's own listeners (so a row's
101
+ e.stopPropagation() stops them). Events that do not bubble (focus, mouseenter, …) reach only the handler on
102
+ their target. Handlers on disabled elements are skipped. A listener you add yourself with addEventListener on
103
+ an element inside a row runs after the row handlers.
104
+
105
+ ## Two-way input
106
+
107
+ const text = signal('');
108
+ html`<input .value=${text()} @input=${e => text.set(e.target.value)}>`
109
+
110
+ ## State updates are immutable
111
+
112
+ todos.update(list => [...list, item]); // correct
113
+ todos().push(item); // WRONG: nothing updates
114
+ user.update(u => ({ ...u, name: 'x' })); // correct
115
+
116
+ ## Rules the compiler enforces (errors include a hint)
117
+
118
+ - Close every non-void element, or write <div />. No implied end tags.
119
+ - No dynamic tag names, no attribute spread, no holes inside <textarea>/<style>/<script>/<title>.
120
+ - <tr> must be inside <tbody>/<thead>/<tfoot>; no block elements inside <p>; no nested <a>/<button>/<form>.
121
+ - No `await` directly inside a hole.
122
+ - @event, .prop, ?bool and ref take exactly one unquoted hole. Event modifiers (@click.once) do not exist.
123
+ - each() and when() only directly as the content of a hole; each takes (items, row, { key }).
124
+
125
+ ## Common mistakes
126
+
127
+ todos().push(x) / t.done = true -> todos.update(l => [...l, x]) / replace the item object
128
+ each(todos, t => t.id, Row) -> each(todos(), Row, { key: 'id' }) (items first, key in options)
129
+ const list = each(…) -> write each(…) directly in the hole
130
+ promise.then(data.set) -> promise.then(v => data.set(v)) (set/update/peek must be called on the signal)
131
+ effect(() => b.set(a() * 2)) -> const b = computed(() => a() * 2) (derive, do not sync signals by hand)
132
+ expecting a component to re-run -> it never does; put changing parts in holes that call signals
133
+ async updates -> none: the DOM is already updated when set() returns
134
+ ${row.label} where label is a signal -> ${row.label()} (in a list row, a function that is not called is read once)
135
+
136
+ ## Whitespace
137
+
138
+ A whitespace run containing a newline is removed next to a tag and becomes one space elsewhere.
139
+ <pre> and <textarea> are untouched.
140
+
141
+ ## Not included (do not invent): JSX, virtual DOM, lifecycle hooks other than onMount/onCleanup,
142
+ context/provide-inject, stores, router, SSR/hydration, custom elements, directives, slots helpers,
143
+ two-way binding sugar, event modifiers.
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@hidemikimura/vanji",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "A tiny compile-time UI framework: html`` templates + signals, close to vanilla JS in speed and memory",
5
+ "keywords": [
6
+ "ui",
7
+ "framework",
8
+ "signals",
9
+ "reactive",
10
+ "compiler",
11
+ "vite",
12
+ "html-template",
13
+ "fine-grained"
14
+ ],
15
+ "author": "hidemikimura",
16
+ "license": "MIT",
17
+ "type": "module",
18
+ "sideEffects": false,
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./src/index.d.ts",
25
+ "default": "./src/index.js"
26
+ },
27
+ "./vite": {
28
+ "types": "./compiler/vite.d.ts",
29
+ "default": "./compiler/vite.js"
30
+ },
31
+ "./compiler": {
32
+ "types": "./compiler/index.d.ts",
33
+ "default": "./compiler/index.js"
34
+ },
35
+ "./internal": "./src/internal.js",
36
+ "./llms.txt": "./llms.txt",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "src",
41
+ "compiler",
42
+ "skills",
43
+ "llms.txt",
44
+ "README.md",
45
+ "CHANGELOG.md",
46
+ "LICENSE"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "scripts": {
52
+ "test": "node --test test/*.test.js",
53
+ "size": "node scripts/size.js",
54
+ "prepublishOnly": "npm test"
55
+ },
56
+ "dependencies": {
57
+ "acorn": "^8.12.0",
58
+ "magic-string": "^0.30.10"
59
+ },
60
+ "devDependencies": {
61
+ "esbuild": "^0.21.5",
62
+ "jsdom": "^24.1.0"
63
+ }
64
+ }