>} one entry per token,
+ * in document order, each carrying the full scope stack.
+ */
+export async function tokenize(source) {
+ grammarPromise ??= loadGrammar();
+ const grammar = await grammarPromise;
+
+ const out = [];
+ let stack = textmate.INITIAL;
+
+ source.split(/\r?\n/).forEach((text, line) => {
+ const result = grammar.tokenizeLine(text, stack);
+ for (const t of result.tokens) {
+ out.push({ line, text: text.slice(t.startIndex, t.endIndex), scopes: t.scopes });
+ }
+ stack = result.ruleStack;
+ });
+
+ return out;
+}
+
+/** Every token whose scope stack contains `scope`. */
+export const withScope = (tokens, scope) => tokens.filter((t) => t.scopes.includes(scope));
+
+/** The scope stack at the first occurrence of `needle`. */
+export function scopesAt(tokens, needle) {
+ const t = tokens.find((x) => x.text.includes(needle));
+ return t ? t.scopes : [];
+}
+
+/** Every built-in component and layout — the corpus for SC-003. */
+export async function corpus() {
+ const { readdir } = await import('node:fs/promises');
+ const out = [];
+ for (const dir of ['components', 'layouts']) {
+ const abs = path.join(PKG_ROOT, dir);
+ for (const f of await readdir(abs)) {
+ if (!f.endsWith('.axo')) continue;
+ out.push({ name: `${dir}/${f}`, source: await readFile(path.join(abs, f), 'utf8') });
+ }
+ }
+ return out;
+}
diff --git a/extension/test/api.test.mjs b/extension/test/api.test.mjs
new file mode 100644
index 0000000..414be03
--- /dev/null
+++ b/extension/test/api.test.mjs
@@ -0,0 +1,134 @@
+/**
+ * The ambient API table — US-4, FR-010, FR-011 and SC-006.
+ *
+ * The load-bearing test here is the biconditional against `docs/writing-components.md`: the
+ * docs and the table must cover each other exactly. It is what keeps the editor honest when
+ * the format changes, since Principle 1 puts the docs in the same change as the behaviour.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { AMBIENT, entriesFor, entryFor, directives } from '../dist/language/api.mjs';
+import { PKG_ROOT } from './_tmgrammar.mjs';
+
+/**
+ * Rows that document SYNTAX rather than a name.
+ *
+ * `{expr}` `.map()` `&&` is the JSX escape hatch — there is no identifier to complete and
+ * nothing to hover, so it is deliberately absent from the table. Every other row must map to
+ * an entry. Keeping this list explicit means a new syntax row is a decision, not a silent
+ * omission.
+ */
+const SYNTAX_ONLY = ['{expr}'];
+
+/** Extract the documented names from the two API tables. */
+async function documentedNames() {
+ const md = await readFile(path.join(PKG_ROOT, 'docs', 'writing-components.md'), 'utf8');
+ const section = md.slice(md.indexOf('## The API'), md.indexOf('## Compound components'));
+
+ const names = [];
+ for (const line of section.split('\n')) {
+ const m = /^\|\s*`([^`]+)`/.exec(line);
+ if (!m) continue;
+ names.push(normalise(m[1]));
+ }
+ return names.filter((n) => !SYNTAX_ONLY.includes(n));
+}
+
+/** `expect(cond, msg)` → `expect`; `` → ``; etc. */
+function normalise(doc) {
+ if (doc.startsWith('';
+ if (doc.startsWith('';
+ if (doc.startsWith('Axo.slots')) return 'Axo.slots';
+ if (doc.startsWith('export const')) return 'export const';
+ const call = /^([A-Za-z][A-Za-z0-9_.]*)\s*\(/.exec(doc);
+ if (call) return call[1];
+ const directive = /^([a-z]+:[a-z]+)=/.exec(doc);
+ if (directive) return directive[1];
+ return doc;
+}
+
+/* ------------------------------------------------------------------ SC-006 */
+
+test('SC-006 every documented name is in the table', async () => {
+ const documented = await documentedNames();
+ assert.ok(documented.length > 0, 'the docs parse produced nothing — the test proves nothing');
+
+ const known = new Set(AMBIENT.map((e) => e.name));
+ for (const name of documented) {
+ assert.ok(known.has(name), `${name} is documented but the editor will never offer it`);
+ }
+});
+
+test('SC-006 every table entry is documented', async () => {
+ const documented = new Set(await documentedNames());
+ for (const entry of AMBIENT) {
+ assert.ok(
+ documented.has(entry.name),
+ `${entry.name} is offered by the editor but documented nowhere`
+ );
+ }
+});
+
+test('SC-006 the ambient helpers are all present — they are why this story exists', () => {
+ const known = new Set(AMBIENT.map((e) => e.name));
+ for (const helper of ['expect', 'pick', 'cx', 'toChildArray', 'cloneElement']) {
+ assert.ok(known.has(helper), `${helper} has no import to follow and is not offered either`);
+ }
+});
+
+/* ------------------------------------------------------------------ FR-010 */
+
+test('FR-010 the frontmatter offers the helpers and not the markup elements', () => {
+ const names = entriesFor('frontmatter').map((e) => e.name);
+
+ assert.ok(names.includes('expect'));
+ assert.ok(names.includes('Axo.props'));
+ assert.ok(!names.includes(''), 'a template element was offered above the fence');
+});
+
+test('FR-010 the template offers the elements and directives, not the helpers', () => {
+ const names = entriesFor('template').map((e) => e.name);
+
+ assert.ok(names.includes(''));
+ assert.ok(names.includes('class:list'));
+ assert.ok(!names.includes('expect'), 'a frontmatter helper was offered in markup');
+});
+
+test('FR-010 an expression is script, so it offers what the frontmatter offers', () => {
+ const inExpr = entriesFor('expression').map((e) => e.name).sort();
+ const inScript = entriesFor('frontmatter').map((e) => e.name).sort();
+ assert.deepEqual(inExpr, inScript, '{cx(a, b)} is as valid as calling cx above the fence');
+});
+
+test('FR-010 nothing is offered outside a region', () => {
+ assert.deepEqual(entriesFor(null), []);
+});
+
+/* ------------------------------------------------------------------ FR-011 */
+
+test('FR-011 every entry carries a signature and a one-line summary', () => {
+ for (const e of AMBIENT) {
+ assert.ok(e.signature.trim().length > 0, `${e.name} has no signature`);
+ assert.ok(e.summary.trim().length > 0, `${e.name} has no summary`);
+ assert.ok(!e.summary.includes('\n'), `${e.name}'s summary is not one line`);
+ }
+});
+
+test('FR-011 a name resolves to its entry, and an unknown one to nothing', () => {
+ assert.equal(entryFor('pick').signature, 'pick(children, Type)');
+ assert.equal(entryFor('nope'), undefined);
+});
+
+/* --------------------------------------------------- US-4 acceptance: attrs */
+
+test('the directives are exactly class:list and html:raw', () => {
+ assert.deepEqual(directives().map((e) => e.name).sort(), ['class:list', 'html:raw']);
+});
+
+test('no name appears twice', () => {
+ const names = AMBIENT.map((e) => e.name);
+ assert.equal(new Set(names).size, names.length, 'a duplicate would be offered twice');
+});
diff --git a/extension/test/diagnostics.test.mjs b/extension/test/diagnostics.test.mjs
new file mode 100644
index 0000000..b867543
--- /dev/null
+++ b/extension/test/diagnostics.test.mjs
@@ -0,0 +1,126 @@
+/**
+ * Diagnostics — US-5, FR-012, FR-013 and SC-007.
+ *
+ * The parity tests are the point. SC-007 promises the editor never reports a problem the build
+ * does not have, so every fixture that produces a diagnostic here is also fed to the real
+ * pipeline, and the build must reject it too.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { diagnosticsFor } from '../dist/language/diagnostics.mjs';
+import { buildRejects } from './_framework.mjs';
+
+/* ------------------------------------------------------------------ FR-012 */
+
+test('FR-012 a client:* directive is an error', () => {
+ const src = 'x
';
+ const [d] = diagnosticsFor(src);
+
+ assert.ok(d, 'no diagnostic for a client directive');
+ assert.equal(d.severity, 'error');
+ assert.match(d.message, /static HTML/);
+});
+
+test('FR-012 the squiggle sits on the directive, not the line', () => {
+ const src = 'x
';
+ const [d] = diagnosticsFor(src);
+
+ assert.equal(src.slice(d.offset, d.offset + d.length), 'client:load');
+});
+
+test('FR-012 every directive the compiler rejects is flagged', async () => {
+ for (const kind of ['load', 'idle', 'visible', 'only', 'media']) {
+ const src = `x
`;
+ assert.equal(diagnosticsFor(src).length, 1, `client:${kind} was not flagged`);
+ assert.ok(await buildRejects(src), `client:${kind} is flagged but the build accepts it`);
+ }
+});
+
+test('a clean component produces nothing', () => {
+ const src = '---\nconst { a } = Axo.props;\n---\n
\n';
+ assert.deepEqual(diagnosticsFor(src), []);
+});
+
+/* ------------------------------------------------------------------ FR-013 */
+
+test('FR-013 an unclosed brace is reported AT the brace', () => {
+ const src = '{ oops
';
+ const [d] = diagnosticsFor(src);
+
+ assert.ok(d, 'no diagnostic for an unbalanced brace');
+ assert.equal(d.offset, src.indexOf('{'));
+ assert.equal(src[d.offset], '{');
+ assert.match(d.message, /never closed/);
+});
+
+test('FR-013 the position is a line and character the editor can use', () => {
+ const src = '';
+ const [d] = diagnosticsFor(src);
+
+ assert.equal(d.line, 1);
+ assert.equal(src.split('\n')[d.line][d.character], '{');
+});
+
+test('FR-013 a balanced document with hard cases reports nothing', () => {
+ const src = '{ f({ a: 1 }) }
';
+ assert.deepEqual(diagnosticsFor(src), []);
+});
+
+test('FR-013 a brace inside a quoted attribute is not an imbalance', () => {
+ assert.deepEqual(diagnosticsFor('x
'), []);
+});
+
+/* ------------------------------------------------------------------ SC-007 */
+
+test('SC-007 the editor reports nothing the build accepts', async () => {
+ const broken = [
+ 'x
',
+ 'x
',
+ '{ oops
',
+ '---\nconst a = 1;\n---\n{ a
',
+ ];
+
+ for (const src of broken) {
+ assert.ok(diagnosticsFor(src).length > 0, `no diagnostic for: ${src}`);
+ assert.ok(await buildRejects(src), `the editor flags a document the build accepts: ${src}`);
+ }
+});
+
+test('SC-007 clean documents are clean to both', async () => {
+ const fine = [
+ 'hello
',
+ '---\nconst { a } = Axo.props;\n---\n{a}
',
+ '
',
+ ];
+
+ for (const src of fine) {
+ assert.deepEqual(diagnosticsFor(src), [], `the editor flags clean source: ${src}`);
+ assert.ok(!await buildRejects(src), `the build rejects source the editor calls clean: ${src}`);
+ }
+});
+
+test('SC-007 the brace position matches the one the compiler would carry', async () => {
+ const src = '{ oops
';
+ const [d] = diagnosticsFor(src);
+
+ // The compiler's scanner throws from the same offset — same scanner, one implementation.
+ assert.equal(d.offset, src.indexOf('{'));
+ assert.ok(await buildRejects(src));
+});
+
+/* -------------------------------------------------------- reports clear */
+
+test('US-5 fixing the problem clears the report', () => {
+ assert.equal(diagnosticsFor('{ oops
').length, 1);
+ assert.deepEqual(diagnosticsFor('{ oops }
'), []);
+});
+
+test('problems arrive in document order', () => {
+ const src = '';
+ const found = diagnosticsFor(src);
+
+ for (let i = 1; i < found.length; i++) {
+ assert.ok(found[i].offset > found[i - 1].offset, 'diagnostics are out of order');
+ }
+});
diff --git a/extension/test/drift.test.mjs b/extension/test/drift.test.mjs
new file mode 100644
index 0000000..2ceabb8
--- /dev/null
+++ b/extension/test/drift.test.mjs
@@ -0,0 +1,80 @@
+/**
+ * The drift guard — FR-019.
+ *
+ * The extension bundles the framework's scanner rather than reimplementing it, so that the
+ * editor and the build can never disagree about where a region ends. Bundling makes that true
+ * at build time; this test makes it stay true.
+ *
+ * It compares BEHAVIOUR, not bytes. esbuild rewrites the module on the way in — different
+ * whitespace, renamed locals, inlined helpers — so a byte comparison would fail on every build
+ * while proving nothing. What matters is that both answer identically for the same input, and
+ * the corpus is the input that matters most.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { regionsOf } from '../dist/language/regions.mjs';
+import { fromDist } from './_framework.mjs';
+import { corpus } from './_tmgrammar.mjs';
+
+const framework = await fromDist('scan.js');
+
+/* --------------------------------------------------------- same answers */
+
+test('FR-019 the bundled scanner agrees with the framework across the corpus', async () => {
+ const files = await corpus();
+ assert.ok(files.length > 0, 'corpus is empty — the test proves nothing');
+
+ for (const { name, source } of files) {
+ assert.deepEqual(
+ regionsOf(source),
+ framework.scanRegions(source),
+ `${name}: the editor and the build disagree about this file's regions`
+ );
+ }
+});
+
+test('FR-019 they agree on the cases the scanner exists for', () => {
+ const hard = [
+ 't
',
+ '{ f("}") }
',
+ '{ f({ a: 1 }) }
',
+ '---\nconst a = 1;\n---\n{a}
',
+ 'no fence at all
',
+ '---\nconst a = 1;\n---\none
\n---\ntwo
',
+ 'literal
',
+ ];
+
+ for (const source of hard) {
+ assert.deepEqual(regionsOf(source), framework.scanRegions(source), `disagreement on: ${source}`);
+ }
+});
+
+test('FR-019 they agree that a malformed document is malformed', () => {
+ const src = '{ oops
';
+
+ assert.throws(() => regionsOf(src));
+ assert.throws(() => framework.scanRegions(src));
+});
+
+/* ------------------------------------------------- the bundle is standalone */
+
+test('FR-017 the bundled module carries the scanner rather than importing it', async () => {
+ const { readFile } = await import('node:fs/promises');
+ const path = await import('node:path');
+ const { EXT_ROOT } = await import('./_tmgrammar.mjs');
+
+ const bundled = await readFile(
+ path.default.join(EXT_ROOT, 'dist', 'language', 'regions.mjs'),
+ 'utf8'
+ );
+
+ assert.ok(
+ !/from\s+['"]@ambystech\/axo/.test(bundled),
+ 'the bundle still imports the framework — the VSIX would need it installed at runtime'
+ );
+ assert.ok(
+ bundled.includes('unbalanced { } in template'),
+ 'the scanner does not appear to be inlined'
+ );
+});
diff --git a/extension/test/grammar.test.mjs b/extension/test/grammar.test.mjs
new file mode 100644
index 0000000..a8b1719
--- /dev/null
+++ b/extension/test/grammar.test.mjs
@@ -0,0 +1,164 @@
+/**
+ * The grammar — US-1 acceptance criteria and FR-002 through FR-007.
+ *
+ * These assert the scopes a reader's theme colours. Where a rule is a deliberate approximation
+ * (expression extent), the test says so and the exact version lives in tokens.test.mjs.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { tokenize, withScope, scopesAt, corpus } from './_tmgrammar.mjs';
+
+/* ------------------------------------------------------ FR-002: two regions */
+
+test('FR-002 the frontmatter is a script region and the template is not', async () => {
+ const tokens = await tokenize('---\nconst a = 1;\n---\nhello
\n');
+
+ assert.ok(
+ withScope(tokens, 'meta.embedded.block.typescript').length > 0,
+ 'the frontmatter did not enter a script region'
+ );
+ assert.ok(
+ scopesAt(tokens, 'hello').every((s) => !s.startsWith('meta.embedded.block')),
+ 'template text leaked into the script region'
+ );
+});
+
+test('FR-002 both fences are punctuation, not content', async () => {
+ const tokens = await tokenize('---\nconst a = 1;\n---\nx
\n');
+
+ assert.equal(withScope(tokens, 'punctuation.definition.frontmatter.begin.axo').length, 1);
+ assert.equal(withScope(tokens, 'punctuation.definition.frontmatter.end.axo').length, 1);
+});
+
+/* --------------------------------------------------- FR-003: no fence at all */
+
+test('FR-003 a file with no fence is template throughout', async () => {
+ const tokens = await tokenize('just markup
\n');
+
+ assert.equal(withScope(tokens, 'meta.frontmatter.axo').length, 0);
+ assert.ok(withScope(tokens, 'entity.name.tag.axo').length > 0, 'tags were not recognised');
+});
+
+/* ------------------------------------------ FR-004: only the leading fence */
+
+test('FR-004 a --- after the template has begun is content, not a fence', async () => {
+ const src = '---\nconst a = 1;\n---\none
\n---\ntwo
\n';
+ const tokens = await tokenize(src);
+
+ // exactly one open and one close: the later --- opened nothing
+ assert.equal(withScope(tokens, 'punctuation.definition.frontmatter.begin.axo').length, 1);
+ assert.equal(withScope(tokens, 'punctuation.definition.frontmatter.end.axo').length, 1);
+
+ // and the tag after it is still template
+ assert.ok(
+ scopesAt(tokens, 'two').every((s) => !s.startsWith('meta.embedded.block')),
+ 'content after the stray --- was treated as frontmatter'
+ );
+});
+
+test('FR-004 a fence that is not at the start of the document is not a fence', async () => {
+ const tokens = await tokenize('x
\n---\nconst a = 1;\n---\n');
+ assert.equal(withScope(tokens, 'meta.frontmatter.axo').length, 0);
+});
+
+/* --------------------------------------------------------- FR-006: directives */
+
+test('FR-006 class:list and html:raw are scoped apart from ordinary attributes', async () => {
+ const tokens = await tokenize('y
\n');
+
+ const directives = withScope(tokens, 'entity.other.attribute-name.directive.axo').map(
+ (t) => t.text
+ );
+ assert.deepEqual(directives.sort(), ['class:list', 'html:raw']);
+
+ assert.ok(
+ !scopesAt(tokens, 'id').includes('entity.other.attribute-name.directive.axo'),
+ 'an ordinary attribute was scoped as a directive'
+ );
+});
+
+/* -------------------------------------------------------------- FR-007: slot */
+
+test('FR-007 is a language-defined element', async () => {
+ const tokens = await tokenize('
\n');
+
+ const slots = withScope(tokens, 'entity.name.tag.slot.axo');
+ assert.equal(slots.length, 1);
+ assert.equal(slots[0].text, 'slot');
+});
+
+test('FR-007 is too', async () => {
+ const tokens = await tokenize('
\n');
+ assert.equal(withScope(tokens, 'entity.name.tag.slot.axo').length, 1);
+});
+
+test('FR-007 a component tag is NOT a slot', async () => {
+ const tokens = await tokenize('x\n');
+
+ assert.equal(withScope(tokens, 'entity.name.tag.slot.axo').length, 0);
+ assert.ok(withScope(tokens, 'entity.name.tag.axo').some((t) => t.text === 'Tag'));
+});
+
+/* ------------------------------------------------------------- expressions */
+
+test('an expression opens an embedded region', async () => {
+ const tokens = await tokenize('{name}
\n');
+ assert.ok(withScope(tokens, 'meta.embedded.expression.axo').length > 0);
+});
+
+test('a brace inside a quoted attribute value stays a string', async () => {
+ const tokens = await tokenize('x
\n');
+ const brace = tokens.find((t) => t.text.includes('{'));
+ assert.ok(
+ brace.scopes.some((s) => s.startsWith('string.quoted')),
+ 'a literal brace in an attribute value was treated as an expression'
+ );
+});
+
+/* -------------------------------------------------- SC-002 / SC-003: corpus */
+
+test('SC-003 every built-in component and layout tokenizes with no region left open', async () => {
+ const files = await corpus();
+ assert.ok(files.length > 0, 'corpus is empty — the test proves nothing');
+
+ for (const { name, source } of files) {
+ const tokens = await tokenize(source);
+ assert.ok(tokens.length > 0, `${name} produced no tokens`);
+
+ // A file that ends inside a string or comment means a rule never closed. The last token
+ // of a well-formed file sits in the template, not in an unterminated construct.
+ const last = tokens.at(-1);
+ assert.ok(
+ !last.scopes.some((s) => s.startsWith('string.quoted') || s.startsWith('comment')),
+ `${name} ends inside an unterminated ${last.scopes.at(-1)}`
+ );
+ }
+});
+
+test('SC-002 the documented constructs each carry a distinct scope', async () => {
+ const src = [
+ '---',
+ 'const { title } = Axo.props;',
+ 'export const sectionClass = "s";',
+ '---',
+ '',
+ ' ',
+ ' ',
+ ' {title}',
+ '
',
+ ].join('\n');
+
+ const tokens = await tokenize(src);
+ const present = (scope) => withScope(tokens, scope).length > 0;
+
+ for (const scope of [
+ 'meta.embedded.block.typescript',
+ 'entity.other.attribute-name.directive.axo',
+ 'entity.name.tag.slot.axo',
+ 'entity.name.tag.axo',
+ 'meta.embedded.expression.axo',
+ ]) {
+ assert.ok(present(scope), `${scope} never appeared`);
+ }
+});
diff --git a/extension/test/language-config.test.mjs b/extension/test/language-config.test.mjs
new file mode 100644
index 0000000..b9fe1ba
--- /dev/null
+++ b/extension/test/language-config.test.mjs
@@ -0,0 +1,111 @@
+/**
+ * Editing behaviour — US-3, FR-008 and FR-009.
+ *
+ * WHAT THESE TESTS CAN AND CANNOT PROVE
+ *
+ * Comment toggling and auto-closing are the EDITOR's behaviour, driven by declarative
+ * configuration. There is no keystroke to simulate under `node --test` (that is R6 in plan.md),
+ * so what is asserted here is the contract the editor reads: the declared pairs, and the
+ * embedded-language wiring that makes comment toggling region-aware.
+ *
+ * The region-aware part is worth spelling out. A language configuration carries ONE comment
+ * style, so `` is declared for the template. The frontmatter gets `//` instead because
+ * the grammar maps `meta.embedded.block.typescript` to the `typescript` language, and the
+ * editor picks the comment style of the embedded language under the cursor. That mapping is
+ * what satisfies FR-008, so it is what these tests guard.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { EXT_ROOT, tokenize, scopesAt } from './_tmgrammar.mjs';
+
+const config = JSON.parse(
+ await readFile(path.join(EXT_ROOT, 'language-configuration.json'), 'utf8')
+);
+const manifest = JSON.parse(await readFile(path.join(EXT_ROOT, 'package.json'), 'utf8'));
+
+/* ----------------------------------------------------------------- FR-008 */
+
+test('FR-008 the manifest points the language at the configuration', () => {
+ const [lang] = manifest.contributes.languages;
+ assert.equal(lang.configuration, './language-configuration.json');
+});
+
+test('FR-008 the template comment style is markup', () => {
+ assert.deepEqual(config.comments.blockComment, ['']);
+ assert.ok(!config.comments.lineComment, 'a line comment here would be wrong for markup');
+});
+
+test('FR-008 the frontmatter is mapped to an embedded language, which is what makes comment toggling region-aware', () => {
+ const [grammar] = manifest.contributes.grammars;
+ assert.equal(grammar.embeddedLanguages['meta.embedded.block.typescript'], 'typescript');
+});
+
+test('FR-008 the scope that mapping keys off is the one the grammar actually emits', async () => {
+ const tokens = await tokenize('---\nconst a = 1;\n---\nx
\n');
+ assert.ok(
+ scopesAt(tokens, 'const a = 1;').includes('meta.embedded.block.typescript'),
+ 'the frontmatter scope changed — comment toggling would silently fall back to markup'
+ );
+});
+
+/* ----------------------------------------------------------------- FR-009 */
+
+test('FR-009 every bracket kind the language uses is declared', () => {
+ const pairs = config.brackets.map(([open]) => open).sort();
+ assert.deepEqual(pairs, ['(', '<', '[', '{']);
+});
+
+test('FR-009 quotes do not auto-close inside strings or comments', () => {
+ for (const q of ["'", '"', '`']) {
+ const pair = config.autoClosingPairs.find((p) => p.open === q);
+ assert.ok(pair, `${q} is not an auto-closing pair`);
+ assert.deepEqual(pair.notIn.sort(), ['comment', 'string']);
+ }
+});
+
+test('FR-009 the template literal backtick closes — it is the character the scanner exists for', () => {
+ assert.ok(config.autoClosingPairs.some((p) => p.open === '`' && p.close === '`'));
+ assert.ok(config.surroundingPairs.some(([open]) => open === '`'));
+});
+
+test('FR-009 an HTML comment auto-closes', () => {
+ const pair = config.autoClosingPairs.find((p) => p.open === '');
+});
+
+test('FR-009 selecting text and typing a bracket surrounds it', () => {
+ const surrounds = config.surroundingPairs.map(([open]) => open);
+ for (const expected of ['{', '[', '(', '"', "'", '`', '<']) {
+ assert.ok(surrounds.includes(expected), `${expected} does not surround a selection`);
+ }
+});
+
+/* ------------------------------------------------------------- indentation */
+
+test('a self-closing tag does not increase indent', () => {
+ const re = new RegExp(config.indentationRules.increaseIndentPattern);
+ assert.ok(!re.test(''), ' wrongly increases indent');
+ assert.ok(!re.test(''), 'a self-closed component wrongly increases indent');
+});
+
+test('an open tag increases indent, and its close decreases it', () => {
+ const inc = new RegExp(config.indentationRules.increaseIndentPattern);
+ const dec = new RegExp(config.indentationRules.decreaseIndentPattern);
+
+ assert.ok(inc.test(''), 'an open tag did not increase indent');
+ assert.ok(dec.test('
'), 'a close tag did not decrease indent');
+});
+
+test('a tag opened and closed on one line does not increase indent', () => {
+ const re = new RegExp(config.indentationRules.increaseIndentPattern);
+ assert.ok(!re.test('{name}'));
+});
+
+test('an unclosed brace increases indent — multi-line expressions are common in .axo', () => {
+ const re = new RegExp(config.indentationRules.increaseIndentPattern);
+ assert.ok(re.test('const mark = (v) => {'));
+});
diff --git a/extension/test/resolve.test.mjs b/extension/test/resolve.test.mjs
new file mode 100644
index 0000000..bf86892
--- /dev/null
+++ b/extension/test/resolve.test.mjs
@@ -0,0 +1,129 @@
+/**
+ * Navigation — US-6 and FR-014.
+ *
+ * The shadowing case is the one that matters. A deck component overriding a built-in must send
+ * the author to the deck's file, because that is the one the build will run; opening the
+ * built-in would show them code they replaced.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import {
+ resolveComponent,
+ candidatePaths,
+ deckRootOf,
+ isComponentName,
+ tagNameAt,
+} from '../dist/language/resolve.mjs';
+
+/** A fake tree — `exists` is injected, so no fixture directory is needed. */
+const tree = (...paths) => {
+ const set = new Set(paths);
+ return (p) => set.has(p);
+};
+
+const DECK = '/w/deck';
+const FROM = '/w/deck/slides/01-title.mdx';
+const PKG = '/w/deck/node_modules/@ambystech/axo';
+
+/* -------------------------------------------------------------- deck root */
+
+test('the deck root is found by its config file', () => {
+ const exists = tree('/w/deck/axo.config.mjs');
+ assert.equal(deckRootOf(FROM, exists), DECK);
+});
+
+test('a deck with no config is still found by its components directory', () => {
+ const exists = tree('/w/deck/components');
+ assert.equal(deckRootOf(FROM, exists), DECK);
+});
+
+test('a file outside any deck has no root', () => {
+ assert.equal(deckRootOf('/tmp/loose.axo', tree()), null);
+});
+
+test('the root is found from a component, not just a slide', () => {
+ const exists = tree('/w/deck/axo.config.mjs');
+ assert.equal(deckRootOf('/w/deck/components/Tag.axo', exists), DECK);
+});
+
+/* ------------------------------------------------------------ FR-014 order */
+
+test('FR-014 the deck is searched before the package', () => {
+ const exists = tree('/w/deck/axo.config.mjs');
+ const order = candidatePaths('Tag', FROM, { exists, packageRoot: PKG });
+
+ assert.deepEqual(order, [
+ '/w/deck/components/Tag.axo',
+ '/w/deck/layouts/Tag.axo',
+ `${PKG}/components/Tag.axo`,
+ `${PKG}/layouts/Tag.axo`,
+ ]);
+});
+
+test('FR-014 a deck component shadows the built-in, and is the ONLY result', () => {
+ const exists = tree(
+ '/w/deck/axo.config.mjs',
+ '/w/deck/components/Tag.axo',
+ `${PKG}/components/Tag.axo`
+ );
+
+ const found = resolveComponent('Tag', FROM, { exists, packageRoot: PKG });
+ assert.equal(found, '/w/deck/components/Tag.axo', 'navigated to the overridden built-in');
+});
+
+test('FR-014 a built-in resolves when the deck does not override it', () => {
+ const exists = tree('/w/deck/axo.config.mjs', `${PKG}/components/Stat.axo`);
+ assert.equal(resolveComponent('Stat', FROM, { exists, packageRoot: PKG }), `${PKG}/components/Stat.axo`);
+});
+
+test('FR-014 a layout resolves from the layouts directory', () => {
+ const exists = tree('/w/deck/axo.config.mjs', '/w/deck/layouts/Cover.axo');
+ assert.equal(resolveComponent('Cover', FROM, { exists }), '/w/deck/layouts/Cover.axo');
+});
+
+/* ----------------------------------------------------------- US-6: a miss */
+
+test('US-6 an unknown tag resolves to nothing, and raises nothing', () => {
+ const exists = tree('/w/deck/axo.config.mjs');
+ assert.equal(resolveComponent('Nope', FROM, { exists }), null);
+});
+
+test('US-6 a plain HTML element is never a component', () => {
+ for (const tag of ['div', 'p', 'span', 'slot']) {
+ assert.equal(isComponentName(tag), false, `${tag} was treated as a component`);
+ assert.equal(resolveComponent(tag, FROM, { exists: tree('/w/deck/axo.config.mjs') }), null);
+ }
+});
+
+test('US-6 a component name is capitalised — the rule JSX already uses', () => {
+ for (const tag of ['Tag', 'TwoCol', 'Stat2']) assert.ok(isComponentName(tag));
+});
+
+test('a loose .axo outside a deck resolves nothing rather than guessing', () => {
+ assert.equal(resolveComponent('Tag', '/tmp/loose.axo', { exists: tree() }), null);
+});
+
+/* ------------------------------------------------------- the cursor's tag */
+
+test('the tag under the cursor is found on the opening tag', () => {
+ const src = 'x
';
+ const at = src.indexOf('Tag');
+ assert.equal(tagNameAt(src, at), 'Tag');
+ assert.equal(tagNameAt(src, at + 2), 'Tag');
+});
+
+test('the closing tag navigates too', () => {
+ const src = 'x
';
+ assert.equal(tagNameAt(src, src.lastIndexOf('Tag')), 'Tag');
+});
+
+test('an attribute inside the tag does not navigate', () => {
+ const src = 'x';
+ assert.equal(tagNameAt(src, src.indexOf('tone')), null);
+});
+
+test('text between tags does not navigate', () => {
+ const src = 'hello';
+ assert.equal(tagNameAt(src, src.indexOf('hello')), null);
+});
diff --git a/extension/test/tokens.test.mjs b/extension/test/tokens.test.mjs
new file mode 100644
index 0000000..89c7160
--- /dev/null
+++ b/extension/test/tokens.test.mjs
@@ -0,0 +1,119 @@
+/**
+ * Expression extents — FR-005 and the US-1 acceptance criterion about `class:list`.
+ *
+ * The grammar's version of this is a first-match regex. These tests assert the scanner-backed
+ * version lands on the TRUE closing brace, which is the whole reason the semantic token layer
+ * exists.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile, readdir } from 'node:fs/promises';
+import path from 'node:path';
+
+import { expressionTokens } from '../dist/language/tokens.mjs';
+import { expressionsOf, regionAt, lineIndex } from '../dist/language/regions.mjs';
+import { PKG_ROOT } from './_tmgrammar.mjs';
+
+/** Offsets of every token, back from line/character, so assertions read in offsets. */
+const offsets = (source) => {
+ const lines = source.split('\n');
+ const starts = [0];
+ for (const l of lines) starts.push(starts.at(-1) + l.length + 1);
+ return expressionTokens(source).map((t) => starts[t.line] + t.character);
+};
+
+/* ----------------------------------------------------------------- FR-005 */
+
+test('FR-005 the closing brace of a template literal does NOT end the expression', () => {
+ const src = 't
';
+ const [expr] = expressionsOf(src);
+
+ assert.equal(src.slice(expr.start, expr.end), '{["a", `x-${y}`]}');
+
+ // the naive answer a regex gives — proof the two differ, so the layer earns its place
+ const naive = src.indexOf('}', src.indexOf('{'));
+ assert.notEqual(naive, expr.end - 1, 'first-match and balanced scan agree; pick a harder case');
+});
+
+test('FR-005 tokens mark the true delimiters, not the first brace found', () => {
+ const src = 't
';
+ const marks = offsets(src);
+
+ assert.equal(marks.length, 2, 'expected exactly an open and a close');
+ assert.equal(src[marks[0]], '{');
+ assert.equal(src[marks[1]], '}');
+ assert.equal(marks[1], src.lastIndexOf('}'), 'the close landed on the wrong brace');
+});
+
+test('FR-005 a brace inside a quoted string does not end the expression', () => {
+ const src = '{ f("}") }
';
+ const marks = offsets(src);
+ assert.equal(src[marks[1]], '}');
+ assert.equal(marks[1], src.lastIndexOf('}'));
+});
+
+test('FR-005 nested object braces belong to the outer expression', () => {
+ const src = '{ f({ a: 1 }) }
';
+ const marks = offsets(src);
+ assert.equal(marks.length, 2, 'a nested brace was reported as its own expression');
+ assert.equal(marks[1], src.lastIndexOf('}'));
+});
+
+test('tokens arrive in document order', () => {
+ const src = '{a}
\n{b}
\n{c}
\n';
+ const tokens = expressionTokens(src);
+
+ for (let i = 1; i < tokens.length; i++) {
+ const prev = tokens[i - 1];
+ const cur = tokens[i];
+ assert.ok(
+ cur.line > prev.line || (cur.line === prev.line && cur.character >= prev.character),
+ 'tokens are out of order — the editor rejects that'
+ );
+ }
+});
+
+test('a document mid-edit yields no tokens rather than throwing', () => {
+ assert.deepEqual(expressionTokens('{ oops
'), []);
+});
+
+test('a brace in a quoted attribute value produces no token', () => {
+ assert.deepEqual(expressionTokens('x
'), []);
+});
+
+/* -------------------------------------------------------- region lookup */
+
+test('regionAt reports the narrowest region containing an offset', () => {
+ const src = '---\nconst a = 1;\n---\n{a}
\n';
+
+ assert.equal(regionAt(src, src.indexOf('const')), 'frontmatter');
+ assert.equal(regionAt(src, src.indexOf('')), 'template');
+ assert.equal(regionAt(src, src.indexOf('{a}') + 1), 'expression');
+});
+
+test('lineIndex converts offsets to editor positions', () => {
+ const src = 'a\nbb\nccc';
+ const at = lineIndex(src);
+
+ assert.deepEqual(at(0), { line: 0, character: 0 });
+ assert.deepEqual(at(2), { line: 1, character: 0 });
+ assert.deepEqual(at(6), { line: 2, character: 1 });
+});
+
+/* ------------------------------------------------------------ the corpus */
+
+test('every built-in component yields balanced, in-bounds tokens', async () => {
+ for (const dir of ['components', 'layouts']) {
+ const abs = path.join(PKG_ROOT, dir);
+ for (const f of await readdir(abs)) {
+ if (!f.endsWith('.axo')) continue;
+ const source = await readFile(path.join(abs, f), 'utf8');
+ const tokens = expressionTokens(source);
+
+ assert.equal(tokens.length % 2, 0, `${dir}/${f}: an unpaired delimiter`);
+ for (const o of offsets(source)) {
+ assert.ok('{}'.includes(source[o]), `${dir}/${f}: token at ${o} is not a delimiter`);
+ }
+ }
+ }
+});
diff --git a/extension/tsconfig.json b/extension/tsconfig.json
new file mode 100644
index 0000000..2d9d1e7
--- /dev/null
+++ b/extension/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ // esbuild does the bundling, so resolution follows the bundler rather than Node's
+ // CJS/ESM split. Without this, importing the framework's ESM scanner from a file the
+ // host will load as CommonJS reads as an error that the bundle does not actually have.
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "lib": ["ES2023"],
+ "types": ["node", "vscode"],
+
+ "strict": true,
+ "noImplicitAny": true,
+
+ "noEmit": true,
+
+ "esModuleInterop": true,
+ "skipLibCheck": true
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/package.json b/package.json
index 2d5df32..5e22517 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "@ambystech/axo",
"version": "0.1.0",
- "description": "Axo — a static deck framework. Slides in .mdx, components in .axo, ships plain HTML with no runtime.",
+ "description": "Axo \u2014 a static deck framework. Slides in .mdx, components in .axo, ships plain HTML with no runtime.",
"homepage": "https://axo.ambystech.io",
"repository": {
"type": "git",
@@ -32,6 +32,10 @@
"types": "./dist/runtime.d.ts",
"import": "./dist/runtime.js"
},
+ "./scan": {
+ "types": "./dist/scan.d.ts",
+ "import": "./dist/scan.js"
+ },
"./theme/*": "./theme/*"
},
"files": [
@@ -73,7 +77,7 @@
"typecheck": "tsc -p tsconfig.json --noEmit",
"prepare": "node scripts/build-pkg.mjs",
"prepublishOnly": "node scripts/build-pkg.mjs",
- "test": "node scripts/build-pkg.mjs && node --test test/*.test.mjs",
- "test:only": "node --test test/*.test.mjs"
+ "test": "node scripts/build-pkg.mjs && node scripts/test.mjs",
+ "test:only": "node scripts/test.mjs"
}
-}
\ No newline at end of file
+}
diff --git a/scripts/test.mjs b/scripts/test.mjs
new file mode 100644
index 0000000..3b704b8
--- /dev/null
+++ b/scripts/test.mjs
@@ -0,0 +1,36 @@
+#!/usr/bin/env node
+/**
+ * Run the test suite, on any platform, on any supported Node.
+ *
+ * `node --test test/*.test.mjs` looks simpler, and it is — until you notice it depends on the
+ * SHELL expanding the glob. POSIX shells do; cmd.exe and PowerShell do not, so on Windows the
+ * literal string reaches Node. Node can expand it itself, but only from v22, and `engines`
+ * promises v20.
+ *
+ * Quoting it moves the problem rather than solving it: then it ALWAYS reaches Node, and Node 20
+ * fails everywhere instead of just on Windows.
+ *
+ * So the file list is built here, where neither the shell nor the Node version has an opinion.
+ */
+import { readdir } from 'node:fs/promises';
+import { spawn } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const DIR = path.join(ROOT, 'test');
+
+const files = (await readdir(DIR)).filter((f) => f.endsWith('.test.mjs')).sort();
+
+if (files.length === 0) {
+ console.error('no test files found in test/');
+ process.exit(1);
+}
+
+const child = spawn(
+ process.execPath,
+ ['--test', ...files.map((f) => path.join('test', f))],
+ { cwd: ROOT, stdio: 'inherit' }
+);
+
+child.on('exit', (code, signal) => process.exit(signal ? 1 : (code ?? 1)));
diff --git a/site/.gitignore b/site/.gitignore
new file mode 100644
index 0000000..2fcc3f2
--- /dev/null
+++ b/site/.gitignore
@@ -0,0 +1,13 @@
+node_modules/
+dist/
+.DS_Store
+
+# generated by axo
+index.html
+vendor/
+.axo/
+
+# PDF export — regenerate with `axo pdf`.
+# For a confidential deck this is the deliverable: keep it out of a repo you might one
+# day make public, and hand it over directly.
+*.pdf
diff --git a/site/README.md b/site/README.md
new file mode 100644
index 0000000..a93e200
--- /dev/null
+++ b/site/README.md
@@ -0,0 +1,32 @@
+# Axo
+
+Built with [Axo](https://github.com/ambystechcom) · **visibility: `public`**
+
+```bash
+npm install
+npm run dev # http://localhost:8000
+npm run pdf # -> site.pdf
+npm run build # -> dist/ (static site)
+npm run preview # check dist/ at :8080
+```
+
+## Visibility
+
+This deck is public. `.github/workflows/deck.yml` builds `dist/` and deploys it to GitHub
+Pages on `main`. The PDF is a local step — it drives a headless Chromium, which is too
+expensive to run on every push.
+
+Change it in `axo.config.mjs`. It is not a label; it is what the tooling enforces.
+
+## Structure
+
+```
+slides/ one .mdx per slide ← what you edit
+components/ your .axo components (override a built-in by name)
+layouts/ your .axo layouts
+css/deck.css this deck's CSS
+axo.config.mjs title, visibility, footer
+```
+
+The compiler, the components, the theme and Reveal all live in `@ambystech/axo`.
+Upgrade every deck you own with `npm update @ambystech/axo`.
diff --git a/site/assets/img/ambystech-axolotl.png b/site/assets/img/ambystech-axolotl.png
new file mode 100644
index 0000000..b228e20
Binary files /dev/null and b/site/assets/img/ambystech-axolotl.png differ
diff --git a/site/assets/img/favicon.png b/site/assets/img/favicon.png
new file mode 100644
index 0000000..36e41c0
Binary files /dev/null and b/site/assets/img/favicon.png differ
diff --git a/site/assets/img/isotipo.png b/site/assets/img/isotipo.png
new file mode 100644
index 0000000..36e41c0
Binary files /dev/null and b/site/assets/img/isotipo.png differ
diff --git a/site/axo.config.mjs b/site/axo.config.mjs
new file mode 100644
index 0000000..0bba327
--- /dev/null
+++ b/site/axo.config.mjs
@@ -0,0 +1,30 @@
+import { defineConfig } from '@ambystech/axo';
+
+// defineConfig gives you autocomplete and type-checking in your editor.
+// (Plain `export default {...}` works too — the types are just a nicety.)
+export default defineConfig({
+ title: "Axo",
+ lang: "en",
+
+ /**
+ * NOT a label — a guard.
+ *
+ * public `axo build` works; a deploy workflow is scaffolded
+ * internal builds, warns; nothing auto-deploys
+ * confidential `axo build` REFUSES. Deliver the PDF (`axo pdf`).
+ *
+ * Changing this changes what the tooling will let you do. A public URL cannot be
+ * un-indexed, so a confidential deck belongs in a PRIVATE repo, delivered as a PDF.
+ */
+ visibility: "public",
+
+ footer: {
+ notice: "",
+ entity: "Xolotl Byteworks S.A de C.V",
+ site: 'www.ambystech.com',
+ logo: 'assets/img/isotipo.png',
+ },
+
+ // Reveal.js options, merged over Axo's defaults.
+ reveal: {},
+});
diff --git a/site/components/README.md b/site/components/README.md
new file mode 100644
index 0000000..945fe1c
--- /dev/null
+++ b/site/components/README.md
@@ -0,0 +1,19 @@
+# Your components
+
+Drop a `.axo` file here. **The filename is the component name** — `Pricing.axo`
+gives you ``. No registration step.
+
+A file named after a built-in (`Matrix.axo`) **overrides** Axo's version — you don't have
+to fork the framework to change one component.
+
+```axo
+---
+const { name, price, featured } = Axo.props;
+---
+
+
+```
diff --git a/site/css/deck.css b/site/css/deck.css
new file mode 100644
index 0000000..3e8f1b1
--- /dev/null
+++ b/site/css/deck.css
@@ -0,0 +1,9 @@
+/* This deck's own CSS. Loaded last, so it wins.
+ *
+ * Style your components here using the theme variables, so they survive a palette change:
+ * --amby-fuchsia --amby-orchid --amby-blue --amby-cyan
+ * --amby-bg --amby-bg-2 --amby-bg-3 --amby-fg --amby-fg-dim --amby-warn --amby-ok
+ * --font-display --font-body --font-mono
+ *
+ * The brand theme lives in the Axo package. You never edit it; you override it here.
+ */
diff --git a/site/layouts/README.md b/site/layouts/README.md
new file mode 100644
index 0000000..4a3adee
--- /dev/null
+++ b/site/layouts/README.md
@@ -0,0 +1,11 @@
+# Your layouts
+
+Drop a `.axo` file here and name it in a slide's frontmatter (`layout: foo`).
+A layout named after a built-in overrides Axo's version.
+
+```axo
+---
+export const sectionClass = 'quote-slide';
+---
+
+```
diff --git a/site/package-lock.json b/site/package-lock.json
new file mode 100644
index 0000000..f84f483
--- /dev/null
+++ b/site/package-lock.json
@@ -0,0 +1,52 @@
+{
+ "name": "axo-site",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "axo-site",
+ "version": "0.1.0",
+ "devDependencies": {
+ "@ambystech/axo": "file:.."
+ }
+ },
+ "..": {
+ "name": "@ambystech/axo",
+ "version": "0.1.0",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@fontsource/inter": "^5.2.8",
+ "@fontsource/jetbrains-mono": "^5.2.8",
+ "@fontsource/space-grotesk": "^5.2.10",
+ "@mdx-js/mdx": "^3.1.1",
+ "chokidar": "^5.0.0",
+ "decktape": "^3.14.0",
+ "esbuild": "^0.28.1",
+ "http-server": "^14.1.1",
+ "live-server": "^1.2.2",
+ "mermaid": "^11.16.0",
+ "preact": "^10.29.7",
+ "preact-render-to-string": "^6.7.0",
+ "remark-frontmatter": "^5.0.0",
+ "remark-mdx-frontmatter": "^5.2.0",
+ "reveal.js": "^5.1.0"
+ },
+ "bin": {
+ "axo": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@types/node": "^26.1.1",
+ "typescript": "^7.0.2"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@ambystech/axo": {
+ "resolved": "..",
+ "link": true
+ }
+ }
+}
diff --git a/site/package.json b/site/package.json
new file mode 100644
index 0000000..04c2cd6
--- /dev/null
+++ b/site/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "axo-site",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "axo dev",
+ "build": "axo build",
+ "preview": "axo preview",
+ "pdf": "axo pdf",
+ "clean": "axo clean"
+ },
+ "devDependencies": {
+ "@ambystech/axo": "file:.."
+ },
+ "description": "The Axo landing deck \u2014 built by Axo, deployed to Pages."
+}
diff --git a/site/slides/01-title.mdx b/site/slides/01-title.mdx
new file mode 100644
index 0000000..34e45ab
--- /dev/null
+++ b/site/slides/01-title.mdx
@@ -0,0 +1,18 @@
+---
+layout: title
+---
+
+Ambystech
+
+# Axo
+
+Slides in `.mdx`, components in `.axo`, output that is just HTML.
+
+
+ npm i -D @ambystech/axo
+ MIT
+
+
+
+- This page is a deck built by Axo. Press → or space.
+
diff --git a/site/slides/02-problem.mdx b/site/slides/02-problem.mdx
new file mode 100644
index 0000000..6c89d0d
--- /dev/null
+++ b/site/slides/02-problem.mdx
@@ -0,0 +1,21 @@
+01 · The problem
+
+## A deck should still open in five years.
+
+The tools that make slides beautiful make them fragile: a runtime to boot,
+a CDN to reach, a framework to keep upgrading.
+
+
+
+ Hydration, client islands, a bundle to ship. It renders — until the wifi
+ drops, or the CDN moves, or the framework majors.
+
+
+ HTML, CSS and vendored assets. No client framework, no hydration, no CDN
+ link. `client:*` is a compile error, not a warning.
+
+
+
+
+- The failure mode is not "ugly", it is "does not open".
+
diff --git a/site/slides/03-what-it-is.mdx b/site/slides/03-what-it-is.mdx
new file mode 100644
index 0000000..d977a61
--- /dev/null
+++ b/site/slides/03-what-it-is.mdx
@@ -0,0 +1,23 @@
+02 · What it is
+
+## A compiler with a CLI around it.
+
+Write slides as `.mdx`. Write components as `.axo`. Everything is decided at
+compile time, and what lands in `dist/` is a static site.
+
+
+ MDX
+ Reveal.js
+ Preact at build time
+ Zero runtime
+
+
+
+ network requests over file://
+ components included
+ vendor payload
+
+
+
+- The zero is the one to hold on. It is a guarantee, not an aspiration.
+
diff --git a/site/slides/04-how.mdx b/site/slides/04-how.mdx
new file mode 100644
index 0000000..0be794a
--- /dev/null
+++ b/site/slides/04-how.mdx
@@ -0,0 +1,17 @@
+03 · How it works
+
+## Five stages, then it is HTML.
+
+
+ Your components and layouts, shadowing the built-ins.
+ MDX to a Reveal section, rendered to a string.
+ The page around it — fonts, theme, footer.
+ Reveal, fonts and Mermaid copied in locally.
+ `dist/`, and nothing pointing outside it.
+
+
+If the build cannot render it correctly, it fails and names the file and line.
+
+
+- Failing loudly beats emitting a deck that renders wrong.
+
diff --git a/site/slides/05-landscape.mdx b/site/slides/05-landscape.mdx
new file mode 100644
index 0000000..b9b1bc9
--- /dev/null
+++ b/site/slides/05-landscape.mdx
@@ -0,0 +1,33 @@
+04 · Writing a component
+
+## The filename is the component name.
+
+
+
+Drop `Tier.axo` in `components/` and you have ``. No registration, no
+import, no list to update.
+
+
+ Axo.props
+ class:list
+ <slot />
+
+
+
+```axo
+---
+const { name, price } = Axo.props;
+---
+
+
+```
+
+
+
+
+- The frontmatter runs at compile time. The template is what ships.
+
diff --git a/site/slides/06-close.mdx b/site/slides/06-close.mdx
new file mode 100644
index 0000000..fbdf26f
--- /dev/null
+++ b/site/slides/06-close.mdx
@@ -0,0 +1,20 @@
+---
+layout: title
+---
+
+Get started
+
+# One command.
+
+
+npx @ambystech/axo new my-deck
+
+
+
+ github.com/ambystechcom/Axo
+ Axo for VS Code
+
+
+
+- This deck is in site/ — it is built by the framework it describes.
+
diff --git a/specs/014-editor-language-support/contracts/ambient-api.md b/specs/014-editor-language-support/contracts/ambient-api.md
new file mode 100644
index 0000000..25a5e31
--- /dev/null
+++ b/specs/014-editor-language-support/contracts/ambient-api.md
@@ -0,0 +1,63 @@
+---
+feature: 014-editor-language-support
+status: draft
+created: 2026-08-24
+---
+
+# Contract — the ambient API table
+
+> One table, two consumers: completion (FR-010) and hover (FR-011). Declared once in
+> `extension/src/language/api.ts` so the two cannot drift apart, and asserted against
+> `docs/writing-components.md` so neither can drift from the documentation (SC-006).
+
+## Shape
+
+```ts
+export interface AmbientEntry {
+ name: string; // 'expect'
+ signature: string; // 'expect(cond, msg)'
+ summary: string; // one line — hover shows this verbatim
+ region: 'frontmatter' | 'template' | 'both';
+ kind: 'function' | 'namespace' | 'property' | 'element' | 'directive';
+}
+
+export const AMBIENT: readonly AmbientEntry[];
+```
+
+## Membership rule
+
+An entry exists here **iff** the name appears in the API tables of
+`docs/writing-components.md`. That biconditional is the test: neither table may gain a name the
+other lacks. It is also how FR-019 stays honest for this surface — a construct added to the format
+is added to the docs in the same change (Principle 1), which fails this test until the extension
+follows.
+
+## Required members
+
+Grouped as the docs group them; the docs are authoritative for wording.
+
+| Group | Names | Region |
+|---|---|---|
+| The `Axo` object | `Axo.props`, `Axo.children`, `Axo.slots` | frontmatter |
+| Elements | ``, `` | template |
+| Directives | `class:list`, `html:raw` | template |
+| Ambient helpers | `expect`, `pick`, `cx`, `toChildArray`, `cloneElement` | frontmatter |
+| Module scope | `export const` | frontmatter |
+
+The helpers are the reason US-4 exists: they have no import statement to follow, so an editor is
+the only place they can surface.
+
+## Consumers
+
+| Consumer | Filter | Requirement |
+|---|---|---|
+| Completion provider | by cursor region | FR-010 |
+| Hover provider | by name at cursor | FR-011 |
+| Attribute completion | `kind: 'directive'` | US-4 acceptance |
+
+## Tests
+
+- Every documented name is present, and no undocumented name is (SC-006, both directions).
+- Completion in a frontmatter region offers every `frontmatter` and `both` entry, and no
+ `template`-only entry — and the converse inside a template.
+- Hover on each name returns its signature and summary.
diff --git a/specs/014-editor-language-support/contracts/scanner.md b/specs/014-editor-language-support/contracts/scanner.md
new file mode 100644
index 0000000..828a21d
--- /dev/null
+++ b/specs/014-editor-language-support/contracts/scanner.md
@@ -0,0 +1,71 @@
+---
+feature: 014-editor-language-support
+status: draft
+created: 2026-08-24
+---
+
+# Contract — `src/scan.ts`
+
+> The one scanner both the compiler and the editor read the language through. Extracted from
+> `src/compile-axo.ts`; behaviour is unchanged, so the existing suite is the regression gate.
+> Satisfies FR-003, FR-004, FR-005, FR-013 and, by being shared rather than copied, FR-019.
+
+## Interface
+
+```ts
+/** Byte offsets into the original source. Half-open: [start, end). */
+export interface Span { start: number; end: number }
+
+export type RegionKind =
+ | 'frontmatter' // between the leading fences, exclusive
+ | 'template' // everything after the closing fence
+ | 'expression'; // a balanced { … } inside a template
+
+export interface Region extends Span { kind: RegionKind }
+
+/** Split on the LEADING fence only. No fence ⇒ the whole file is template. */
+export function splitFrontmatter(source: string): { script: Span | null; template: Span };
+
+/** Index of the `}` matching the `{` at `i`. Quote- and template-literal-aware. */
+export function matchBrace(source: string, i: number): number;
+
+/** Every region in document order, expressions nested inside their template. */
+export function scanRegions(source: string): Region[];
+```
+
+## Invariants
+
+- **I-1** — `frontmatter` and `template` never overlap, and `template` covers every offset after
+ the closing fence. `expression` regions nest strictly inside the template; a consumer applies
+ regions in order and the later, narrower one wins.
+- **I-2** — Only the leading fence is a fence. A `---` anywhere later is template content
+ (FR-004).
+- **I-3** — No fence ⇒ one `template` region spanning the file, and `script` is `null` (FR-003).
+- **I-4** — `matchBrace` never returns a `}` that sits inside a string, a template literal, or a
+ nested `${…}` (FR-005). This is the invariant a regex cannot hold and Principle 1 forbids
+ approximating.
+- **I-5** — On an imbalance, `matchBrace` throws carrying the offset of the unclosed `{`, so
+ FR-013 can report a position rather than a fact.
+- **I-6** — Pure: no I/O, no `vscode` import, no framework import. This is what lets the extension
+ bundle it and the tests run headlessly.
+
+## Difference from today
+
+`splitFrontmatter` currently returns extracted **strings**. Spans are required instead: the editor
+must map every token back to a position in the original document, which a copied string cannot do.
+`compile-axo.ts` slices the spans and is otherwise untouched.
+
+## Consumers
+
+| Consumer | Uses | For |
+|---|---|---|
+| `src/compile-axo.ts` | all three | unchanged compilation |
+| `extension/src/language/tokens.ts` | `scanRegions` | semantic tokens (FR-005) |
+| `extension/src/language/diagnostics.ts` | `matchBrace` | imbalance reporting (FR-013) |
+
+## Tests
+
+- The existing `.axo` compiler suite must pass untouched — that is the proof the extraction changed
+ nothing (Principle 2).
+- Per-invariant unit tests, with I-4 driven by the corpus: every built-in component and layout.
+- The drift test required by FR-019: the scanner bundled into the VSIX equals the framework's.
diff --git a/specs/014-editor-language-support/plan.md b/specs/014-editor-language-support/plan.md
new file mode 100644
index 0000000..31ca03e
--- /dev/null
+++ b/specs/014-editor-language-support/plan.md
@@ -0,0 +1,196 @@
+---
+feature: 014-editor-language-support
+status: draft
+created: 2026-08-24
+---
+
+# Implementation Plan — Editor language support for .axo components
+
+> The HOW. First artifact where technology appears. Must satisfy every `FR-###` in `@spec.md` and
+> honor the `@../../.amby/constitution.md`. Reference spec/UI by ID — do not restate them.
+
+No `ui.md` exists for this feature. The surface is editor-native — colouring, completion popups,
+hovers, squiggles — all rendered by the host editor's own chrome, so there is nothing to wireframe
+and no token set to define. If a design pass is wanted anyway, the one artifact worth producing is
+the scope-to-theme mapping in Phase 2.
+
+## Technical context
+
+- **Stack:** TypeScript, compiled and bundled to JavaScript with esbuild — the framework's existing
+ bundler, reused rather than introducing a second one (Principle 8). A VS Code extension running
+ in the extension host. **No language server.**
+- **Key libraries:**
+ - Runtime: the editor's extension API only. Zero third-party runtime dependencies, so FR-018
+ holds by construction.
+ - Build: `esbuild` (already a framework dependency).
+ - Test: `node --test`, no framework (Principle 2), driving `vscode-textmate` + `vscode-oniguruma`
+ to tokenize fixtures headlessly. These are tokenizer libraries, not a test framework — the
+ assertions stay `node:assert`.
+ - Publish: `@vscode/vsce` (Marketplace) and `ovsx` (Open VSX), per the distribution assumption.
+- **Constraints driving choices:**
+ - **Principle 1** — structure is parsed with a real scanner, never a lazy regex. This is the
+ binding constraint on the whole design; see Architecture.
+ - **Principle 2** — every FR maps to a test under `node --test`.
+ - **Principle 7** — no per-deck configuration, no deck-side install (FR-016).
+ - **Principle 8** — authored in TS, shipped as JS.
+ - FR-017 — the extension is a self-contained artifact, versioned and distributed separately from
+ `@ambystech/axo`.
+
+## Architecture
+
+### The binding problem
+
+FR-005 requires expression extents resolved by balanced scanning that understands quotes and
+template literals. **A TextMate grammar cannot do this** — it is line-oriented regex matching with
+no counter, so ``class:list={['a', `x-${y}`]}`` is exactly the case it gets wrong. Principle 1
+names that failure mode directly. Tree-sitter is not an option either: VS Code exposes no public
+extension API for contributing a Tree-sitter grammar, and fork support varies.
+
+So colouring is **two layers**:
+
+| Layer | Mechanism | Cost | Handles |
+|---|---|---|---|
+| 1. Baseline | TextMate grammar, declarative | Zero activation; the editor tokenizes | Regions, tags, attributes, directives, `` |
+| 2. Correction | Semantic tokens from the real scanner | Activates on `onLanguage:axo` | Exact expression extents (FR-005) |
+
+Semantic tokens are designed to layer over TextMate scopes, so the grammar's approximation is
+*corrected* rather than competing with it. The grammar alone still gives a readable file if layer 2
+is unavailable — which matters for the fork-parity risk (R1).
+
+### One scanner, two consumers
+
+The scanner primitives live in `src/compile-axo.ts` today and are private (`matchBrace`,
+`splitFrontmatter`, lines 44 and 79). Reimplementing them in the extension would guarantee the
+drift FR-019 exists to prevent.
+
+**Extract `src/scan.ts`** in the framework — one module, one responsibility (Principle 1):
+
+```
+src/scan.ts splitFrontmatter, matchBrace, scanRegions ← new, pure, no deps
+ ├── src/compile-axo.ts imports it (behaviour unchanged; existing tests must stay green)
+ └── extension/ bundles it at build time
+```
+
+The extension `devDependency`-depends on `@ambystech/axo` and esbuild-inlines `scan.ts` into the
+VSIX. The published artifact carries no runtime dependency on the framework, so FR-017 and FR-018
+hold, versions move independently, and one scanner defines the language for both the build and the
+editor. A drift test asserts the bundled scanner matches the framework's.
+
+### Extension module split
+
+```
+extension/
+ package.json manifest: language id, grammar, activation → FR-001
+ language-configuration.json comments, brackets, auto-close → FR-008, FR-009
+ syntaxes/axo.tmLanguage.json baseline grammar → FR-002…FR-007
+ src/language/ PURE functions — no vscode import
+ regions.ts scan → typed regions
+ tokens.ts regions → semantic tokens → FR-005
+ api.ts the ambient API table (single source) → FR-010, FR-011
+ diagnostics.ts client:*, unbalanced braces → FR-012, FR-013
+ resolve.ts tag name → file path → FR-014
+ src/adapters/ thin vscode API wiring; the only untested layer
+ test/ node --test over src/language/ + grammar corpus
+```
+
+Everything decidable is a pure function from document text to a result. The editor API appears only
+in `adapters/`, which is deliberately thin enough to read in one sitting — the tradeoff that lets
+the suite run under `node --test` with no editor download (R6).
+
+## Phased approach
+
+- **Phase 0 — Research:** → `research.md`. Five open technical questions, chiefly the `engines.vscode`
+ floor that stock VS Code *and* the named forks all satisfy, and whether those forks implement the
+ semantic tokens API. Both gate design decisions already load-bearing here.
+- **Phase 1 — Foundation:** `extension/` skeleton, manifest, language contribution, esbuild build,
+ CI job. Extract `src/scan.ts` and repoint `compile-axo.ts` at it — the existing suite is the
+ regression gate. → FR-001, FR-015, FR-016, FR-017, FR-018
+ Contracts: `contracts/scanner.md`, `contracts/ambient-api.md`. No `data-model.md`: the only
+ entities are document regions and tokens, which are the scanner contract itself.
+- **Phase 2 — US-1 (P1) Grammar + language configuration:** two-region grammar with embedded
+ scopes, directive and `` scopes, plus `language-configuration.json`. Corpus test over every
+ built-in component and layout. → FR-002…FR-007, SC-002, SC-003
+- **Phase 3 — US-1 (P1) Semantic tokens:** scanner-backed expression extents layered over the
+ grammar. → FR-005, SC-005
+- **Phase 4 — US-2 (P1) Publish:** package with `vsce`, publish to both registries, release
+ workflow. Needs publisher identities that do not exist yet (R2). → FR-017, SC-004
+- **Phase 5 — US-3 (P2) Editing behaviour:** region-aware comments, brackets, auto-close.
+ → FR-008, FR-009
+- **Phase 6 — US-4 (P2) Discoverability:** completion + hover generated from `api.ts`, with a test
+ asserting it covers every name in `docs/writing-components.md` (SC-006). → FR-010, FR-011
+- **Phase 7 — US-5 (P3) Diagnostics:** `client:*` and unbalanced braces from the same scanner, with
+ a position-parity test against `axo check` (SC-007). → FR-012, FR-013
+- **Phase 8 — US-6 (P3) Navigation:** definition provider, deck directories first.
+ → FR-014
+- **Deferred — TypeScript frontmatter:** blocked on feature 002 (R3). The grammar can embed the TS
+ scope in Phase 2, but it must not ship before the compiler accepts TS.
+
+## Requirement mapping
+
+| Requirement | How it's satisfied |
+|---|---|
+| US-1 | Phases 2–3: grammar for baseline, semantic tokens for exactness |
+| US-2 | Phase 4: one VSIX, published to both registries |
+| US-3 | Phase 5: `language-configuration.json` with per-region comment and bracket rules |
+| US-4 | Phase 6: `api.ts` as the single source for completion and hover |
+| US-5 | Phase 7: diagnostics derived from the shared scanner |
+| US-6 | Phase 8: definition provider over deck `components/`, `layouts/` |
+| FR-001 | `contributes.languages` with `extensions: ['.axo']` — declarative, no activation needed |
+| FR-002 | Grammar splits on the leading fence; embedded scopes per region |
+| FR-003 | `scanRegions` returns a template-only result when no fence is present — the compiler's own rule, shared not re-derived |
+| FR-004 | Fence pattern anchored to document start; later `---` carries no meaning |
+| FR-005 | `matchBrace` via semantic tokens. **The grammar cannot satisfy this alone** — this is why Layer 2 exists |
+| FR-006 | Dedicated scopes for `class:list` / `html:raw`, distinct from `entity.other.attribute-name` |
+| FR-007 | `` scoped as a language-defined element |
+| FR-008 | Per-region `comments` in the language configuration |
+| FR-009 | `brackets`, `autoClosingPairs`, `surroundingPairs`, scoped so template rules do not fire inside frontmatter |
+| FR-010 | Completion provider over `api.ts` |
+| FR-011 | Hover provider over the same table — one source, so the two cannot disagree |
+| FR-012 | `diagnostics.ts` flags any `client:*` attribute (Principle 6) |
+| FR-013 | `matchBrace` throwing an imbalance is reported at its position rather than swallowed |
+| FR-014 | `resolve.ts`: deck `components/` → `layouts/` → installed package; miss returns nothing |
+| FR-015 | Grammar contribution is workspace-independent; no deck detection anywhere in the path |
+| FR-016 | Nothing is read from the deck but its own source files; no config key is contributed |
+| FR-017 | Separate `package.json` under `extension/`, excluded from the framework's `files` array (already true: `dist`, `components`, `layouts`, `theme`, `templates`) |
+| FR-018 | No network call exists in the extension; the scanner is bundled |
+| FR-019 | Drift test: the extension's bundled scanner must equal the framework's `src/scan.ts` |
+| SC-001 | Manual check on a clean profile, once per release |
+| SC-002, SC-003 | Grammar corpus test over every built-in, asserting no region ends unterminated |
+| SC-004 | Phase 4 install check per editor |
+| SC-005 | Timed tokenization of the largest built-in |
+| SC-006 | Test asserts `api.ts` covers every name in `docs/writing-components.md` |
+| SC-007 | Position-parity test against `axo check` |
+
+## Risks & decisions
+
+- **R1 — TextMate cannot balance braces; semantic tokens are the fix.** Decision: ship both layers.
+ Rationale: Principle 1 forbids letting a regex decide expression extent, and FR-005 names the
+ exact case. Residual risk: if a fork does not implement semantic tokens, colouring degrades to
+ the grammar's approximation and FR-005 is unmet there. Phase 0 measures this; if a target fork
+ lacks the API, that is a spec question, not a plan one — it changes what FR-005 can promise.
+- **R2 — No publisher identity exists on either registry.** This blocks Phase 4, and therefore
+ US-2 and SC-004, regardless of engineering progress. It needs an owner and an account before
+ Phase 4 starts; everything else proceeds without it.
+- **R3 — TypeScript frontmatter depends on feature 002.** The compiler emits `.jsx` bundled with a
+ JSX loader (`src/compile.ts:230`), which does not strip type annotations. Shipping TS colouring
+ first would have the editor endorse syntax the build rejects — the exact failure SC-007's one-way
+ guarantee exists to prevent. Decision: build the grammar with the TS scope embedded, gate its
+ release on 002. Suggest a `clarify` on 002 to decide whether it emits `.tsx` or switches loader.
+- **R4 — Scanner drift between build and editor.** Decision: bundle the framework's module rather
+ than copy it, and enforce with a drift test (FR-019). Rejected: reimplementing in the extension;
+ it makes divergence a matter of time.
+- **R5 — No LSP.** Decision: in-process providers against the editor API. Rationale: the scope is
+ tokens, completion, hover, definition and two diagnostics — a server adds a process and a
+ protocol for no capability gained. Cost: support for non-VS-Code editors (Zed, Neovim) would mean
+ reworking this. Accepted; out of scope per US-2.
+- **R6 — Providers are tested as pure functions, not in a live editor.** `@vscode/test-electron`
+ downloads an editor per run, which is slow and needs network — poor fit for Principle 2's
+ `node --test` discipline. Consequence: `adapters/` is covered only by the manual SC-001 and
+ SC-004 checks. Mitigated by keeping the adapters trivially thin.
+- **Gap — built-in navigation target.** FR-014 says "the file the build would resolve", but for a
+ built-in that file sits in `node_modules`, which Principle 7 says a deck never references. Reading
+ it for navigation is not a build reference, so the plan permits it. Flagging rather than deciding:
+ worth a `clarify` if you read Principle 7 more strictly.
+- **Gap — SC-005 has no measurement method.** "Under 200 ms" needs a defined machine and corpus to
+ be a test rather than an impression. Phase 3 proposes the largest built-in as the fixture; a
+ `clarify` should confirm.
diff --git a/specs/014-editor-language-support/research.md b/specs/014-editor-language-support/research.md
new file mode 100644
index 0000000..cd1d68d
--- /dev/null
+++ b/specs/014-editor-language-support/research.md
@@ -0,0 +1,78 @@
+---
+feature: 014-editor-language-support
+status: draft
+created: 2026-08-24
+---
+
+# Phase 0 research — Editor language support
+
+> Decisions taken, with rationale, plus the questions that must be answered by measurement before
+> Phase 2 fixes them in place. Each open item names what changes if the answer goes the other way.
+
+## Decided
+
+### D-1 — TextMate grammar plus semantic tokens, not one or the other
+A TextMate grammar is line-oriented regex matching with no counter, so it cannot resolve a balanced
+`{ … }` containing quotes or template literals. FR-005 requires exactly that, and Principle 1
+forbids the regex approximation. Semantic tokens layer over TextMate scopes by design, so the
+grammar supplies instant baseline colour at zero activation cost and the scanner corrects the
+extents. Rejected: grammar only (fails FR-005); semantic tokens only (nothing renders until the
+extension activates, and every fork must implement the API).
+
+### D-2 — No Tree-sitter
+VS Code exposes no public extension API for contributing a Tree-sitter grammar. Fork support varies
+and none of it is contractual. This is not a preference; it is unavailable.
+
+### D-3 — No language server
+The capability set — semantic tokens, completion, hover, definition, two diagnostics — is fully
+served by in-process providers. An LSP server adds a process and a protocol boundary for no
+capability gained at this scope. Cost, accepted: supporting non-VS-Code editors later means
+reworking this layer. See R5 in `plan.md`.
+
+### D-4 — Extract `src/scan.ts`, bundle it, do not reimplement
+`matchBrace` and `splitFrontmatter` are private in `src/compile-axo.ts` (lines 44, 79). The
+extension needs the same logic; a second implementation would diverge, which is the failure FR-019
+exists to prevent. Extraction also serves Principle 1's one-module-one-responsibility rule. The
+extension bundles the module at build time, so the VSIX stays self-contained (FR-017, FR-018).
+
+### D-5 — Test with `vscode-textmate` under `node --test`
+Principle 2 mandates `node --test` and no test framework. `vscode-textmate` + `vscode-oniguruma`
+tokenize a document headlessly and return scopes, which `node:assert` then checks. They are
+tokenizer libraries, not a framework, so the discipline holds. Rejected: `vscode-tmgrammar-test`
+(its own runner and assertion dialect) and `@vscode/test-electron` (downloads an editor per run;
+slow and network-bound).
+
+## Open — must be measured before Phase 2
+
+### Q-1 — What `engines.vscode` floor do all target editors satisfy?
+Cursor, Antigravity and Windsurf each track a stock VS Code version, and they lag by varying
+amounts. The floor must be low enough for the oldest target and high enough for the APIs used.
+**Method:** install each editor, read its reported VS Code version, take the minimum.
+**Measured so far:** stock VS Code on the development machine reports **1.134.0**. That is a
+ceiling, not the answer — the floor is set by whichever fork lags furthest, and none are
+measured yet. `engines.vscode` stays provisional at `^1.75.0` until they are.
+**If it goes badly:** a floor older than the semantic tokens API would force D-1's layer 2 to be
+optional, weakening FR-005 to a best-effort promise — a spec change, not a plan change.
+
+### Q-2 — Do the named forks implement the semantic tokens API?
+Assumed yes: the API is long-standing and forks inherit it. Unverified, and R1 rests on it.
+**Method:** a throwaway extension registering a token provider, installed in each fork.
+**If it goes badly:** colouring degrades to the grammar in that fork and FR-005 is unmet there.
+
+### Q-3 — What does publishing to each registry actually require?
+Marketplace and Open VSX have separate identity, token and namespace models. Neither identity
+exists yet (R2), and this gates US-2 and SC-004 independently of any code.
+**Method:** walk both signup flows; record who owns the account and where the token lives.
+
+### Q-4 — Which compiler change unlocks TypeScript frontmatter?
+`src/compile.ts:230` bundles the generated `.jsx` with the JSX loader, which does not strip type
+annotations. Either the generated module becomes `.tsx`, or the loader changes. Both belong to
+feature 002, not here.
+**Method:** prototype both against the existing suite; the one that leaves `mapLine` intact wins,
+since error positions map back to the `.axo` through it.
+**If it goes badly:** US-1 ships JavaScript-only colouring and TS follows later.
+
+### Q-5 — How is SC-005 measured?
+"Under 200 ms" needs a fixture and a machine to be a test rather than an impression.
+**Proposal:** the largest built-in component, tokenized cold, on CI hardware. Needs confirmation —
+see the gap noted in `plan.md`.
diff --git a/specs/014-editor-language-support/spec.md b/specs/014-editor-language-support/spec.md
new file mode 100644
index 0000000..f47ac4d
--- /dev/null
+++ b/specs/014-editor-language-support/spec.md
@@ -0,0 +1,270 @@
+---
+feature: 014-editor-language-support
+title: Editor language support for .axo components
+branch: 014-editor-language-support
+status: ready
+created: 2026-08-24
+---
+
+# Spec — Editor language support for .axo components
+
+> WHAT and WHY only. No technology decisions (those belong in `plan.md`).
+> Flag unknowns inline as `[NEEDS CLARIFICATION: …]` — never guess.
+
+`.axo` is a format this project invented (feature 002). Every editor therefore treats a
+component as plain text: no colour, no bracket matching, no comment toggle. The authoring loop
+Axo is built around — write a component, see it in the deck — begins in an editor that does not
+know the language exists. This feature makes it known.
+
+The surface an editor must understand is the one `docs/writing-components.md` documents: a
+`---`-fenced script that runs at compile time, then a template with `{expressions}`,
+``, `class:list={[…]}` and `html:raw={…}`.
+
+## User scenarios & testing
+
+### US-1 — A `.axo` file reads as code (priority: P1)
+
+As a deck author, I want the editor to recognise `.axo` as a language and colour it, so that I
+can read a component without mentally parsing undifferentiated grey text.
+
+- **Why this priority:** This is the whole ask. Every other story here is comfort layered on
+ top; without this one the feature does not exist.
+- **Independent test:** Open any built-in component in a clean editor profile with only this
+ extension installed. The language indicator names Axo, the frontmatter colours as script, and
+ the template colours as markup.
+- **depends-on:** []
+- **blocked-by:** []
+- **status:** in-progress
+
+**Acceptance criteria**
+- Given a clean editor profile with the extension installed, When the author opens
+ `components/Tag.axo`, Then the editor reports the file's language as Axo.
+- Given an open `.axo` file, When the author looks at the region between the `---` fences, Then
+ it is coloured with script semantics (keywords, strings, comments), and the region after the
+ closing fence is coloured with markup semantics (tags, attributes, text).
+- Given a template containing `class:list={['step', featured && 'featured']}`, When it is
+ displayed, Then the braces delimit an expression coloured as script, and the quoted strings
+ inside do not leak their colouring into the rest of the file.
+- Given a `.axo` file with no frontmatter fence, When it is opened, Then the whole file is
+ treated as template — matching what the compiler does.
+
+### US-2 — It works in the editor I actually use (priority: P1)
+
+As a deck author working in Cursor, Antigravity, Windsurf or another VS Code derivative, I want
+to install the same extension my colleagues on stock VS Code use, so that the choice of editor
+fork is not a reason to lose language support.
+
+- **Why this priority:** This was named as part of the requirement, not as an extra. An
+ extension that only installs on stock VS Code leaves a large share of the intended audience
+ on plain text.
+- **Independent test:** Install on stock VS Code and on at least two derived editors from their
+ own extension sources; open the same component in each and confirm identical recognition and
+ colouring.
+- **depends-on:** [US-1]
+- **blocked-by:** []
+- **status:** draft
+
+**Acceptance criteria**
+- Given a supported editor with no Axo deck in the workspace, When the author opens a loose
+ `.axo` file, Then recognition and colouring work — deck detection is never a precondition.
+- Given a deck author who installed the framework with `npm i`, When they open a component,
+ Then nothing prompts them to install or configure anything per-deck (per Principle 7).
+- Given each supported editor, When the extension is installed from that editor's own extension
+ source, Then one build serves all of them.
+
+### US-3 — Editing behaves like the language, not like text (priority: P2)
+
+As a deck author, I want comment toggling, bracket matching, tag closing and indentation to
+follow whichever region my cursor is in, so that ordinary editing gestures stop producing
+broken files.
+
+- **Why this priority:** Colour makes a component readable; this makes it writable. It is the
+ next increment, but a file that highlights correctly is already useful without it.
+- **Independent test:** In one component, toggle a comment with the cursor in the frontmatter
+ and again in the template, and confirm each uses the syntax valid for that region.
+- **depends-on:** [US-1]
+- **blocked-by:** []
+- **status:** done
+
+**Acceptance criteria**
+- Given the cursor inside the frontmatter, When the author toggles a comment, Then script
+ comment syntax is used.
+- Given the cursor inside the template, When the author toggles a comment, Then markup comment
+ syntax is used.
+- Given the author types an opening brace, quote or component tag in the template, When the
+ editor auto-closes it, Then the result is syntactically valid in that region.
+- Given the cursor on a brace or tag, When the author asks to jump to its match, Then the
+ editor selects the correct partner, including across nested braces inside template literals.
+
+### US-4 — The Axo API is discoverable in place (priority: P2)
+
+As an author writing my first component, I want the ambient API to appear as completions with a
+short description, so that I can write a component without keeping the docs open beside me.
+
+- **Why this priority:** The ambient API — `expect`, `pick`, `cx`, `toChildArray`,
+ `cloneElement`, and the `Axo` object — is invisible by design: it has no import statement to
+ follow, so the editor is the only place it can be surfaced.
+- **Independent test:** In a new `.axo` file's frontmatter, request completions and confirm
+ every documented ambient name is offered with its signature.
+- **depends-on:** [US-1]
+- **blocked-by:** []
+- **status:** done
+
+**Acceptance criteria**
+- Given the cursor in the frontmatter, When the author requests completions, Then every ambient
+ helper and every `Axo` member documented in `docs/writing-components.md` is offered.
+- Given the cursor on an ambient name, When the author hovers, Then its signature and a
+ one-line description appear.
+- Given the cursor inside a template tag, When the author requests attribute completions, Then
+ `class:list` and `html:raw` are offered and described as Axo directives.
+
+### US-5 — Mistakes surface before the build (priority: P3)
+
+As a deck author, I want the format's hard rules flagged in the editor, so that I learn about a
+broken component while writing it rather than when the build stops.
+
+- **Why this priority:** The compiler already fails loudly and names file and line (Principle
+ 4), so this shortens a feedback loop that is not broken. Real value, lower urgency.
+- **Independent test:** Type `client:load` onto an element and confirm the editor marks it as an
+ error without running a build.
+- **depends-on:** [US-1]
+- **blocked-by:** []
+- **status:** done
+
+**Acceptance criteria**
+- Given a template with a `client:*` directive on any element, When the file is open, Then the
+ editor reports it as an error, because it is a compile error by Principle 6.
+- Given a template with unbalanced `{ }`, When the file is open, Then the editor reports the
+ position of the imbalance rather than silently mis-colouring the rest of the file.
+- Given a component whose reported problems the author has fixed, When the file is saved, Then
+ the reports clear.
+
+### US-6 — Jump from a tag to the component behind it (priority: P3)
+
+As a deck author reading a slide, I want to jump from `` to the file that defines it, so
+that the filename-is-the-component-name rule becomes navigable instead of merely memorable.
+
+- **Why this priority:** A convenience over an already-simple rule — one component, one file,
+ named the same. Valuable in a large deck, skippable in a small one.
+- **Independent test:** From a `` usage, invoke go-to-definition and land in the defining
+ file.
+- **depends-on:** [US-1]
+- **blocked-by:** []
+- **status:** done
+
+**Acceptance criteria**
+- Given a component tag whose name matches a file in the deck's `components/` or `layouts/`,
+ When the author invokes go-to-definition, Then that file opens.
+- Given a deck component that shadows a built-in of the same name, When the author invokes
+ go-to-definition, Then the deck's file opens — the one the build will actually use (per
+ Principle 3) — and it is the only result offered.
+- Given a tag that resolves to no file, When the author invokes go-to-definition, Then nothing
+ opens and no error is raised.
+
+## Requirements (EARS)
+
+- FR-001 WHEN a file whose name ends in `.axo` is opened, THE SYSTEM SHALL identify it as the
+ Axo component language and expose that identity to the editor.
+- FR-002 WHILE an `.axo` file is open, THE SYSTEM SHALL treat it as two regions — the
+ `---`-fenced leading script and the template that follows — applying script semantics
+ (JavaScript, including TypeScript type syntax) to the first and markup semantics to the
+ second.
+- FR-003 IF a file has no leading `---` fence, THEN THE SYSTEM SHALL treat the whole file as
+ template, matching the compiler.
+- FR-004 THE SYSTEM SHALL treat only the leading fence as a fence, and SHALL NOT interpret
+ `---` occurring later in the file as a region boundary.
+- FR-005 THE SYSTEM SHALL colour `{ … }` regions in the template as script expressions,
+ resolving the closing brace by balanced scanning that accounts for quoted strings and template
+ literals — not by first match (per Principle 1).
+- FR-006 THE SYSTEM SHALL distinguish the directives `class:list` and `html:raw` from ordinary
+ attributes.
+- FR-007 THE SYSTEM SHALL treat `` and `` as language-defined elements
+ rather than unrecognised tags.
+- FR-008 WHEN the author toggles a comment, THE SYSTEM SHALL use the comment syntax of the
+ region the cursor is in.
+- FR-009 WHILE the cursor is in the template, THE SYSTEM SHALL match and auto-close tags,
+ braces, brackets and quotes validly for that region.
+- FR-010 WHEN the author requests completions in the frontmatter, THE SYSTEM SHALL offer every
+ ambient helper and every `Axo` member that `docs/writing-components.md` documents.
+- FR-011 WHEN the author hovers an ambient API name, THE SYSTEM SHALL show its signature and a
+ one-line description.
+- FR-012 IF a `client:*` directive appears on any element, THEN THE SYSTEM SHALL report an
+ error, per Principle 6.
+- FR-013 IF the template contains unbalanced `{ }`, THEN THE SYSTEM SHALL report the position
+ of the imbalance.
+- FR-014 WHEN the author invokes go-to-definition on a component tag, THE SYSTEM SHALL open the
+ file the build would resolve that tag to, preferring a deck component over a built-in of the
+ same name.
+- FR-015 THE SYSTEM SHALL provide recognition and colouring for any `.axo` file, WHETHER OR NOT
+ the workspace is an Axo deck.
+- FR-016 THE SYSTEM SHALL NOT require a deck to add configuration, dependencies or files for
+ any behaviour in this spec to work (per Principle 7).
+- FR-017 THE SYSTEM SHALL install from a single build on VS Code and on VS Code–derived
+ editors, and SHALL be distributed independently of the `@ambystech/axo` package — installing
+ the framework does not install the extension, and shipping the extension does not change what
+ the package publishes.
+- FR-018 THE SYSTEM SHALL function with no network access at edit time.
+- FR-019 WHEN the `.axo` format gains, changes or removes a construct, THE SYSTEM SHALL be
+ updated in the same change that alters the compiler (per Principle 1's documentation rule).
+
+## Success criteria
+
+- SC-001 Opening a `.axo` file in a clean profile yields a named language and coloured regions
+ with zero configuration steps.
+- SC-002 Every construct in the `docs/writing-components.md` API table — `Axo.props`,
+ `Axo.children`, `Axo.slots.name`, ``, ``, `html:raw`, `class:list`,
+ `{expr}`, `export const`, and the five ambient helpers — is covered by a colouring assertion.
+- SC-003 Every built-in component and layout in this repository colours end-to-end with no
+ region left in an unterminated state, verified as a corpus check (per Principle 2).
+- SC-004 The extension installs and behaves identically on stock VS Code and on at least two
+ derived editors.
+- SC-005 Colouring appears without perceptible delay on open — under 200 ms for the largest
+ file in the built-in corpus.
+- SC-006 100% of the ambient API is reachable by completion and hover: no name documented in
+ `docs/` is missing from the editor.
+- SC-007 Every problem the editor reports for a file is also reported by `axo check` for that
+ file, at the same position — the editor never invents a problem the build does not have.
+ The converse does not hold: the editor reports only what FR-012 and FR-013 name, not the whole
+ of what the build can raise.
+
+## Edge cases
+
+- A `.axo` file whose frontmatter fence is present but whose script is empty.
+- A template containing a literal `---`, whether inside a string, an expression, or as text.
+- Nested `${…}` inside a template literal inside a `class:list={[…]}` — the case the compiler's
+ scanner exists to handle, and exactly where a naive highlighter breaks.
+- A file saved with CRLF line endings; the compiler tolerates them at the fence.
+- A component that is mid-edit and momentarily unparseable — colouring should degrade locally,
+ not collapse for the whole file.
+- Layouts declare module-scope `export const` values; `components/` and `layouts/` are the same
+ language, with no special-casing by path.
+- A very large component, and a deck with hundreds of components, for the navigation story.
+- Two decks open in one window, each defining a different component under the same name.
+
+## Assumptions
+
+- The `.axo` language surface is what the compiler accepts and what
+ `docs/writing-components.md` documents. Where the two disagree, the compiler is the source of
+ truth and the disagreement is a documentation bug.
+- Extension source lives in `extension/`, as requested. It is a sibling of the framework rather
+ than part of the published package payload — a deck stays thin (Principle 7) and the package
+ keeps shipping only compiled JS and assets (Principle 8).
+- Target editors are VS Code and forks that consume the same extension format; whoever publishes
+ can reach those forks' extension sources.
+- The extension is published to both the VS Code Marketplace and Open VSX: stock VS Code reads
+ the first, the named forks default to the second, and US-2 is met only by covering both. A
+ publisher identity is required on each registry, and neither exists yet.
+- Frontmatter accepts TypeScript syntax and the editor colours it. This depends on feature 002:
+ the compiler emits a `.jsx` module bundled with a JSX loader, which does not strip type
+ annotations, so TypeScript in frontmatter is a build error today. That compiler change lands
+ before this colouring ships — otherwise the editor endorses syntax the build rejects, and
+ SC-007's one-way guarantee breaks. Consumers still never need TypeScript (Principle 8).
+- The extension versions independently of the framework. FR-019 still requires the two to change
+ together when the format changes; it does not require matching numbers, so an editor-only fix
+ ships without a framework release.
+- `.mdx` slide authoring is out of scope; this feature covers `.axo` files only. Component tags
+ in slides are where most authors meet components, so extending US-6 there is a likely
+ follow-up feature rather than a widening of this one.
+- Automatic formatting of `.axo` files is out of scope — formatting a two-region file is a
+ project of its own.
+- A file-explorer icon for `.axo` is out of scope, being cosmetic.
diff --git a/specs/014-editor-language-support/tasks.md b/specs/014-editor-language-support/tasks.md
new file mode 100644
index 0000000..8ed756b
--- /dev/null
+++ b/specs/014-editor-language-support/tasks.md
@@ -0,0 +1,100 @@
+---
+feature: 014-editor-language-support
+created: 2026-08-24
+---
+
+# Tasks — Editor language support for .axo components
+
+> Line format: `- [ ] [T###] [P?] [US#] description (file/path)`
+> `[x]` = done (source of truth for `ambykit dashboard`). `[P]` = parallelizable. `[US#]` = story tag.
+> Gate: no user-story task starts until Foundational completes.
+
+Order follows the story graph in `spec.md`: US-1 (P1) first, US-2 (P1) next since it depends on
+US-1, then US-3 and US-4 (P2), then US-5 and US-6 (P3). Every story depends on US-1, so nothing
+here runs before Phase 3 lands.
+
+## Phase 1 — Setup
+
+- [x] [T001] Create the extension workspace skeleton and manifest (extension/package.json)
+- [x] [T002] [P] Add the esbuild script that emits a self-contained bundle (extension/scripts/build.mjs)
+- [x] [T003] [P] Add the extension's TypeScript config, compiled to JS per Principle 8 (extension/tsconfig.json)
+- [x] [T004] [P] Add `.vscodeignore` so only the bundle and declarative assets ship (extension/.vscodeignore)
+- [x] [T005] [P] Confirm `extension/` stays out of the published package payload (package.json)
+- [x] [T006] Add a separate extension build-and-test job to CI (.github/workflows/ci.yml)
+
+## Phase 2 — Foundational (blocks all feature work)
+
+- [ ] [T010] Answer Q-1: lowest `engines.vscode` all target editors satisfy (specs/014-editor-language-support/research.md)
+- [ ] [T011] [P] Answer Q-2: confirm the semantic tokens API exists in each named fork (specs/014-editor-language-support/research.md)
+- [x] [T012] Extract the span-based scanner per `contracts/scanner.md` (src/scan.ts)
+- [x] [T013] Repoint the compiler at the extracted scanner, slicing spans (src/compile-axo.ts)
+- [x] [T014] Confirm the existing compiler suite passes untouched — the regression gate for T012–T013 (test/compile-axo.test.mjs)
+- [x] [T015] [P] Test scanner invariants I-1 through I-6 (test/scan.test.mjs)
+- [x] [T016] Run `scanRegions` across the built-in corpus to prove I-4 (test/scan.test.mjs)
+- [x] [T017] Declare the language contribution: id, `.axo`, `onLanguage` activation (extension/package.json)
+- [x] [T018] [P] Stand up the headless tokenizer harness under `node --test` (extension/test/_tmgrammar.mjs)
+
+## Phase 3 — User story US-1 (priority: P1)
+
+- [x] [T020] [US1] Write the two-region grammar: fence split plus embedded scopes (extension/syntaxes/axo.tmLanguage.json)
+- [x] [T021] [US1] Anchor the fence to document start so a later `---` stays content (extension/syntaxes/axo.tmLanguage.json)
+- [x] [T022] [US1] Treat a file with no fence as template-only (extension/syntaxes/axo.tmLanguage.json)
+- [x] [T023] [P] [US1] Scope `class:list` and `html:raw` apart from ordinary attributes (extension/syntaxes/axo.tmLanguage.json)
+- [x] [T024] [P] [US1] Scope `` and `` as language-defined elements (extension/syntaxes/axo.tmLanguage.json)
+- [x] [T025] [US1] Tokenize every built-in component and layout, asserting no unterminated region (extension/test/grammar.test.mjs)
+- [x] [T026] [P] [US1] Assert each documented construct carries a distinct scope (extension/test/grammar.test.mjs)
+- [x] [T027] [US1] Map scanner output to typed regions (extension/src/language/regions.ts)
+- [x] [T028] [US1] Emit semantic tokens for exact expression extents (extension/src/language/tokens.ts)
+- [x] [T029] [US1] Test extents against nested `${…}` inside a template literal (extension/test/tokens.test.mjs)
+- [x] [T030] [US1] Wire the semantic tokens provider adapter (extension/src/adapters/semanticTokens.ts)
+- [ ] [T031] [US1] Check a clean profile shows the language name and coloured regions (specs/014-editor-language-support/plan.md)
+- **Checkpoint:** US-1 is demoable — a `.axo` file is recognised and correctly coloured, braces included.
+
+## Phase 4 — User story US-2 (priority: P1, depends-on US-1)
+
+- [ ] [T040] [US2] Answer Q-3: identity, token and namespace rules for both registries (specs/014-editor-language-support/research.md)
+- [ ] [T041] [US2] Obtain a publisher identity on each registry — R2, needs an owner before this phase runs (extension/package.json)
+- [ ] [T042] [US2] Set `engines.vscode` to the floor found in T010 (extension/package.json)
+- [x] [T043] [US2] Package the VSIX and verify it carries no runtime dependency and makes no network call (extension/scripts/build.mjs)
+- [x] [T044] [US2] Add the release workflow publishing to both registries (.github/workflows/extension-release.yml)
+- [ ] [T045] [US2] Install and verify on stock VS Code and two forks (specs/014-editor-language-support/plan.md)
+- **Checkpoint:** US-2 is demoable — one build installs and behaves identically across the target editors.
+
+## Phase 5 — User story US-3 (priority: P2, depends-on US-1)
+
+- [x] [T050] [US3] Define per-region comment rules (extension/language-configuration.json)
+- [x] [T051] [P] [US3] Scope brackets, auto-closing and surrounding pairs per region (extension/language-configuration.json)
+- [x] [T052] [US3] Test comment toggle and auto-close in each region (extension/test/language-config.test.mjs)
+- **Checkpoint:** US-3 is demoable — editing gestures follow the region the cursor sits in.
+
+## Phase 6 — User story US-4 (priority: P2, depends-on US-1)
+
+- [x] [T060] [US4] Declare the ambient API table per `contracts/ambient-api.md` (extension/src/language/api.ts)
+- [x] [T061] [US4] Add the completion provider, filtered by cursor region (extension/src/adapters/completion.ts)
+- [x] [T062] [P] [US4] Add the hover provider over the same table (extension/src/adapters/hover.ts)
+- [x] [T063] [US4] Assert the table and `docs/writing-components.md` cover each other exactly (extension/test/api.test.mjs)
+- **Checkpoint:** US-4 is demoable — every ambient name completes and hovers with its signature.
+
+## Phase 7 — User story US-5 (priority: P3, depends-on US-1)
+
+- [x] [T070] [US5] Flag any `client:*` attribute as an error, per Principle 6 (extension/src/language/diagnostics.ts)
+- [x] [T071] [US5] Report the position of an unbalanced brace from the scanner's throw (extension/src/language/diagnostics.ts)
+- [x] [T072] [US5] Wire the diagnostics adapter and clear reports on fix (extension/src/adapters/diagnostics.ts)
+- [x] [T073] [US5] Assert every reported position matches `axo check` for the same file (extension/test/diagnostics.test.mjs)
+- **Checkpoint:** US-5 is demoable — the two hard rules surface before a build runs.
+
+## Phase 8 — User story US-6 (priority: P3, depends-on US-1)
+
+- [x] [T080] [US6] Resolve a tag name against the deck's `components/` then `layouts/` (extension/src/language/resolve.ts)
+- [x] [T081] [US6] Fall back to the installed package, and return nothing on a miss (extension/src/language/resolve.ts)
+- [x] [T082] [US6] Wire the definition provider adapter (extension/src/adapters/definition.ts)
+- [x] [T083] [US6] Test that shadowing yields the deck file alone and an unknown tag no-ops (extension/test/resolve.test.mjs)
+- **Checkpoint:** US-6 is demoable — a component tag navigates to the file the build would use.
+
+## Phase 9 — Polish
+
+- [x] [T090] [P] Assert the bundled scanner equals the framework's, per FR-019 (extension/test/drift.test.mjs)
+- [ ] [T091] Answer Q-5, then add the timed tokenization fixture it defines (extension/test/perf.test.mjs)
+- [x] [T092] [P] Document editor support alongside the behaviour it describes, per Principle 1 (docs/editor-support.md)
+- [x] [T093] [P] Point the README at the extension (README.md)
+- [ ] [T094] Gate the TypeScript frontmatter release on feature 002 and Q-4 (specs/014-editor-language-support/plan.md)
diff --git a/src/compile-axo.ts b/src/compile-axo.ts
index 01e42a5..e878f90 100644
--- a/src/compile-axo.ts
+++ b/src/compile-axo.ts
@@ -1,4 +1,5 @@
import type { CompiledAxo } from './types.js';
+import { matchBrace, splitFrontmatter } from './scan.js';
/**
* The .axo compiler — the deck framework's component format.
@@ -35,53 +36,6 @@ import type { CompiledAxo } from './types.js';
* NOT supported, deliberately: client:* directives. This renders to static HTML.
*/
-/**
- * Scan a balanced `{ … }` starting at `i` (which must point at the `{`).
- * Quote- and template-literal-aware, so `{['a', `x-${y}`]}` doesn't end early — which a
- * lazy regex gets wrong, and which is exactly what class:list values look like.
- * Returns the index of the matching `}`.
- */
-function matchBrace(src: string, i: number): number {
- let depth = 0;
- let quote: string | null = null; // ' " `
- let tmplDepth = 0;
-
- for (let j = i; j < src.length; j++) {
- const c = src[j];
- const prev = src[j - 1];
-
- if (quote) {
- if (c === quote && prev !== '\\') {
- quote = null;
- } else if (quote === '`' && c === '$' && src[j + 1] === '{' && prev !== '\\') {
- tmplDepth++;
- j++; // skip the {
- } else if (quote === '`' && c === '}' && tmplDepth > 0) {
- tmplDepth--;
- }
- continue;
- }
-
- if (c === "'" || c === '"' || c === '`') {
- quote = c;
- continue;
- }
- if (c === '{') depth++;
- else if (c === '}') {
- depth--;
- if (depth === 0) return j;
- }
- }
- throw new Error('unbalanced { } in template');
-}
-
-/** Pull the `---` frontmatter fence off the top. */
-function splitFrontmatter(source: string): { script: string; template: string } {
- const m = /^\s*---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(source);
- if (!m) return { script: '', template: source };
- return { script: m[1], template: source.slice(m[0].length) };
-}
-
/**
* ESM needs `import`/`export` at module top level, but in a .axo file they sit in the
* frontmatter — which becomes the function body. Lift them out.
@@ -170,7 +124,9 @@ export function compileAxo(
name: string,
{ runtimeUrl }: { runtimeUrl?: string } = {}
): CompiledAxo {
- const { script, template: raw } = splitFrontmatter(source);
+ const { script: scriptSpan, template: templateSpan } = splitFrontmatter(source);
+ const script = scriptSpan ? source.slice(scriptSpan.start, scriptSpan.end) : '';
+ const raw = source.slice(templateSpan.start, templateSpan.end);
if (/\sclient:(load|idle|visible|only|media)/.test(raw)) {
throw new Error(
diff --git a/src/compile.ts b/src/compile.ts
index 41b048e..40cc5f1 100644
--- a/src/compile.ts
+++ b/src/compile.ts
@@ -16,7 +16,7 @@
* Output is static HTML. Nothing from MDX/Preact/esbuild reaches the browser.
*/
import { readFile, writeFile, readdir, mkdir } from 'node:fs/promises';
-import { existsSync } from 'node:fs';
+import { existsSync, realpathSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL, fileURLToPath } from 'node:url';
@@ -43,6 +43,26 @@ const MD_ATTRS =
const posix = (p: string) => p.split(path.sep).join('/');
+/**
+ * A canonical key for the origin map below.
+ *
+ * esbuild reports REAL paths — symlinks resolved. On macOS the system temp dir is
+ * /var/folders/…, a symlink to /private/var/folders/…, so a key written from the unresolved
+ * path never matches the path esbuild hands back, the lookup misses, and a broken component
+ * gets blamed on the generated .jsx instead of the .axo someone actually wrote. Linux and
+ * Windows do not symlink their temp dirs, which is why this only ever showed up on macOS.
+ *
+ * Resolving both ends makes them agree everywhere. A path that cannot be resolved (it does
+ * not exist yet) falls back to the plain form.
+ */
+const canonical = (p: string) => {
+ try {
+ return posix(realpathSync(p));
+ } catch {
+ return posix(p);
+ }
+};
+
/**
* Absolute path to the ambient runtime, resolved from THIS module's own location — so it is
* right in src/ during development and in dist/ after the package is built. Hard-coding
@@ -194,7 +214,7 @@ async function loadRegistry(cfg: ResolvedConfig, CACHE: string): Promise; message?: string };
const msg = be.errors
?.map((x) => {
- const o = originOf.get(posix(path.resolve(PKG_ROOT, x.location?.file ?? '')));
+ const o = originOf.get(canonical(path.resolve(PKG_ROOT, x.location?.file ?? '')));
return o
? `${o.source}:${o.mapLine(x.location!.line!)}:${x.location!.column} ${x.text}`
: `${x.location?.file}:${x.location?.line} ${x.text}`;
diff --git a/src/scan.ts b/src/scan.ts
new file mode 100644
index 0000000..055fe0c
--- /dev/null
+++ b/src/scan.ts
@@ -0,0 +1,179 @@
+/**
+ * The .axo scanner — one implementation of the format's structure.
+ *
+ * Extracted from `compile-axo.ts` so the compiler and the editor extension read the language
+ * the same way. Two implementations would drift, and the editor would eventually disagree with
+ * the build about where an expression ends.
+ *
+ * Everything here works in OFFSETS, not extracted strings: the editor has to map a token back
+ * to a position in the document the user is looking at, and a copied substring has forgotten
+ * where it came from. The compiler slices the spans and carries on as before.
+ *
+ * Pure: no I/O, no imports. That is what lets the extension bundle it.
+ */
+
+/** Half-open `[start, end)` offsets into the original source. */
+export interface Span {
+ start: number;
+ end: number;
+}
+
+export type RegionKind =
+ /** between the leading fences, exclusive of both */
+ | 'frontmatter'
+ /** everything after the closing fence */
+ | 'template'
+ /** a balanced `{ … }` inside the template */
+ | 'expression';
+
+export interface Region extends Span {
+ kind: RegionKind;
+}
+
+/**
+ * An unclosed `{`. Carries the offset so a caller can point AT the brace rather than just
+ * reporting that one exists somewhere.
+ */
+export class UnbalancedBraceError extends Error {
+ readonly offset: number;
+
+ constructor(offset: number) {
+ super('unbalanced { } in template');
+ this.name = 'UnbalancedBraceError';
+ this.offset = offset;
+ }
+}
+
+/**
+ * Only the LEADING fence is a fence. Split into three groups so the script's extent is an
+ * offset rather than a captured copy.
+ */
+const FENCE = /^(\s*---\r?\n)([\s\S]*?)(\r?\n---\r?\n?)/;
+
+/**
+ * Pull the `---` frontmatter fence off the top.
+ *
+ * No fence means the whole file is template — the rule the compiler has always followed, now
+ * stated in one place instead of two.
+ */
+export function splitFrontmatter(source: string): { script: Span | null; template: Span } {
+ const m = FENCE.exec(source);
+ if (!m) return { script: null, template: { start: 0, end: source.length } };
+
+ const start = m[1].length;
+ return {
+ script: { start, end: start + m[2].length },
+ template: { start: m[0].length, end: source.length },
+ };
+}
+
+/**
+ * Scan a balanced `{ … }` starting at `i` (which must point at the `{`).
+ * Quote- and template-literal-aware, so `{['a', `x-${y}`]}` doesn't end early — which a
+ * lazy regex gets wrong, and which is exactly what class:list values look like.
+ * Returns the index of the matching `}`.
+ */
+export function matchBrace(src: string, i: number): number {
+ let depth = 0;
+ let quote: string | null = null; // ' " `
+ let tmplDepth = 0;
+
+ for (let j = i; j < src.length; j++) {
+ const c = src[j];
+ const prev = src[j - 1];
+
+ if (quote) {
+ if (c === quote && prev !== '\\') {
+ quote = null;
+ } else if (quote === '`' && c === '$' && src[j + 1] === '{' && prev !== '\\') {
+ tmplDepth++;
+ j++; // skip the {
+ } else if (quote === '`' && c === '}' && tmplDepth > 0) {
+ tmplDepth--;
+ }
+ continue;
+ }
+
+ if (c === "'" || c === '"' || c === '`') {
+ quote = c;
+ continue;
+ }
+ if (c === '{') depth++;
+ else if (c === '}') {
+ depth--;
+ if (depth === 0) return j;
+ }
+ }
+ throw new UnbalancedBraceError(i);
+}
+
+/**
+ * Every top-level `{ … }` in the template.
+ *
+ * Nested braces belong to the expression that contains them, so scanning jumps past a match
+ * rather than descending into it. A `{` inside a quoted attribute value is markup text, not an
+ * expression — `class="a{b}"` is a literal — so quotes inside a tag are skipped, as are HTML
+ * comments.
+ */
+function scanExpressions(source: string, template: Span): Span[] {
+ const spans: Span[] = [];
+ let inTag = false;
+ let quote: string | null = null;
+
+ for (let j = template.start; j < template.end; j++) {
+ const c = source[j];
+
+ if (quote) {
+ if (c === quote) quote = null;
+ continue;
+ }
+
+ if (c === '<' && source.startsWith('', j + 4);
+ j = close === -1 ? template.end : close + 2;
+ continue;
+ }
+
+ if (inTag) {
+ if (c === '"' || c === "'") {
+ quote = c;
+ continue;
+ }
+ if (c === '>') {
+ inTag = false;
+ continue;
+ }
+ } else if (c === '<' && /[A-Za-z/]/.test(source[j + 1] ?? '')) {
+ inTag = true;
+ continue;
+ }
+
+ if (c === '{') {
+ const close = matchBrace(source, j);
+ spans.push({ start: j, end: close + 1 });
+ j = close;
+ }
+ }
+
+ return spans;
+}
+
+/**
+ * Every region in the document, in document order: the frontmatter (when there is one), the
+ * template, then the expressions that nest inside it.
+ *
+ * Expressions are listed after the template they sit in rather than interleaved — the template
+ * span covers them, so a consumer applies them in order and the later, narrower region wins.
+ */
+export function scanRegions(source: string): Region[] {
+ const { script, template } = splitFrontmatter(source);
+ const regions: Region[] = [];
+
+ if (script) regions.push({ kind: 'frontmatter', ...script });
+ regions.push({ kind: 'template', ...template });
+ for (const span of scanExpressions(source, template)) {
+ regions.push({ kind: 'expression', ...span });
+ }
+
+ return regions;
+}
diff --git a/templates/deploy.yml b/templates/deploy.yml
index e7a79c5..1f93138 100644
--- a/templates/deploy.yml
+++ b/templates/deploy.yml
@@ -17,8 +17,8 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
with:
node-version: 20
cache: npm
@@ -40,7 +40,7 @@ jobs:
! grep -q "node_modules" dist/index.html
test ! -e dist/package.json
- - uses: actions/upload-pages-artifact@v3
+ - uses: actions/upload-pages-artifact@v5
with:
path: dist
@@ -56,7 +56,7 @@ jobs:
url: ${{ steps.deploy.outputs.page_url }}
steps:
- id: deploy
- uses: actions/deploy-pages@v4
+ uses: actions/deploy-pages@v5
# The PDF export is deliberately NOT run in CI: it drives a headless Chromium (system libs
# + a browser run on every push) to produce an artifact only the presenter needs.
diff --git a/test/exports.test.mjs b/test/exports.test.mjs
index 5dc9716..5fd56c2 100644
--- a/test/exports.test.mjs
+++ b/test/exports.test.mjs
@@ -13,8 +13,11 @@ import { fromDist, PKG_ROOT } from './_helpers.mjs';
const pkg = JSON.parse(await readFile(path.join(PKG_ROOT, 'package.json'), 'utf8'));
-test('the package declares exactly three entry points', async () => {
- assert.deepEqual(Object.keys(pkg.exports).sort(), ['.', './runtime', './theme/*']);
+test('the package declares exactly four entry points', async () => {
+ // `./scan` is public because the editor extension bundles it: one scanner defines the
+ // language for both the build and the editor, and a second copy would drift (feature 014,
+ // FR-019). Adding an entry point is adding a contract — that is why this list is pinned.
+ assert.deepEqual(Object.keys(pkg.exports).sort(), ['.', './runtime', './scan', './theme/*']);
});
test('an internal module is NOT reachable through the package', async () => {
@@ -38,6 +41,7 @@ test('the public surface exposes the config helper and the phase operations', as
test('every entry point ships types alongside its implementation', async () => {
assert.ok(pkg.exports['.'].types, 'the main entry has no types condition');
assert.ok(pkg.exports['./runtime'].types, 'the runtime entry has no types condition');
+ assert.ok(pkg.exports['./scan'].types, 'the scan entry has no types condition');
assert.equal(pkg.types, './dist/index.d.ts');
});
diff --git a/test/scan.test.mjs b/test/scan.test.mjs
new file mode 100644
index 0000000..8b0c339
--- /dev/null
+++ b/test/scan.test.mjs
@@ -0,0 +1,178 @@
+/**
+ * The scanner contract — specs/014-editor-language-support/contracts/scanner.md.
+ *
+ * These are the invariants the editor extension will lean on. The compiler already exercises
+ * this code through its own suite; what is tested here is the part the editor needs and the
+ * compiler never asked for — offsets, and the promise that a `}` inside a string is not a
+ * closing brace.
+ */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readdir, readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { fromDist, PKG_ROOT } from './_helpers.mjs';
+
+const { splitFrontmatter, matchBrace, scanRegions, UnbalancedBraceError } =
+ await fromDist('scan.js');
+
+/** Every built-in component and layout — the corpus I-4 is proved against. */
+async function corpus() {
+ const out = [];
+ for (const dir of ['components', 'layouts']) {
+ const abs = path.join(PKG_ROOT, dir);
+ for (const f of await readdir(abs)) {
+ if (!f.endsWith('.axo')) continue;
+ out.push({ name: `${dir}/${f}`, source: await readFile(path.join(abs, f), 'utf8') });
+ }
+ }
+ return out;
+}
+
+const only = (regions, kind) => regions.filter((r) => r.kind === kind);
+
+/* ------------------------------------------------------------------ I-1 */
+
+test('I-1 frontmatter and template never overlap', async () => {
+ for (const { name, source } of await corpus()) {
+ const regions = scanRegions(source);
+ const [script] = only(regions, 'frontmatter');
+ const [template] = only(regions, 'template');
+ if (!script) continue;
+ assert.ok(script.end <= template.start, `${name}: script overruns the template`);
+ }
+});
+
+test('I-1 expressions nest strictly inside the template', async () => {
+ for (const { name, source } of await corpus()) {
+ const regions = scanRegions(source);
+ const [template] = only(regions, 'template');
+ for (const e of only(regions, 'expression')) {
+ assert.ok(
+ e.start >= template.start && e.end <= template.end,
+ `${name}: expression at ${e.start} escapes the template`
+ );
+ }
+ }
+});
+
+test('I-1 the template covers every offset after the closing fence', () => {
+ const src = '---\nconst a = 1;\n---\nx
\n';
+ const [template] = only(scanRegions(src), 'template');
+ assert.equal(src.slice(template.start, template.end), 'x
\n');
+ assert.equal(template.end, src.length);
+});
+
+/* ------------------------------------------------------------------ I-2 */
+
+test('I-2 only the LEADING fence is a fence', () => {
+ const src = '---\nconst a = 1;\n---\na --- b
\n
\n---\n';
+ const regions = scanRegions(src);
+ const [script] = only(regions, 'frontmatter');
+ const [template] = only(regions, 'template');
+
+ assert.equal(src.slice(script.start, script.end), 'const a = 1;');
+ // everything after the FIRST closing fence is template, later `---` included
+ assert.ok(src.slice(template.start, template.end).includes('---'));
+});
+
+/* ------------------------------------------------------------------ I-3 */
+
+test('I-3 no fence means the whole file is template', () => {
+ const src = 'just markup
\n';
+ const { script, template } = splitFrontmatter(src);
+
+ assert.equal(script, null);
+ assert.deepEqual(template, { start: 0, end: src.length });
+
+ const regions = scanRegions(src);
+ assert.equal(only(regions, 'frontmatter').length, 0);
+ assert.equal(only(regions, 'template').length, 1);
+});
+
+/* ------------------------------------------------------------------ I-4 */
+
+test('I-4 a closing brace inside a template literal is not the match', () => {
+ // 0123456789...
+ const src = '{["a", `x-${y}`]}';
+ const close = matchBrace(src, 0);
+ assert.equal(close, src.length - 1, 'stopped early — the `${y}` brace was taken as the match');
+ assert.equal(src.slice(0, close + 1), src);
+});
+
+test('I-4 a closing brace inside a quoted string is not the match', () => {
+ for (const src of ['{ "}" }', "{ '}' }", '{ `}` }']) {
+ assert.equal(matchBrace(src, 0), src.length - 1, `stopped early in ${src}`);
+ }
+});
+
+test('I-4 an escaped quote does not end the string', () => {
+ const src = '{ "a\\"}b" }';
+ assert.equal(matchBrace(src, 0), src.length - 1);
+});
+
+test('I-4 nested braces belong to the outer expression', () => {
+ const src = '{ f({ a: 1 }) }';
+ assert.equal(matchBrace(src, 0), src.length - 1);
+});
+
+test('I-4 holds across every built-in component and layout', async () => {
+ for (const { name, source } of await corpus()) {
+ const regions = scanRegions(source);
+ for (const e of only(regions, 'expression')) {
+ assert.equal(source[e.start], '{', `${name}: expression at ${e.start} does not start at {`);
+ assert.equal(source[e.end - 1], '}', `${name}: expression at ${e.start} does not end at }`);
+ // the span is balanced when read on its own
+ const inner = source.slice(e.start, e.end);
+ assert.equal(matchBrace(inner, 0), inner.length - 1, `${name}: unbalanced span`);
+ }
+ }
+});
+
+test('I-4 a brace inside a quoted attribute value is markup, not an expression', () => {
+ const src = 'text
';
+ assert.equal(only(scanRegions(src), 'expression').length, 0);
+});
+
+test('I-4 a directive value IS an expression', () => {
+ const src = "x
";
+ const [expr] = only(scanRegions(src), 'expression');
+ assert.equal(src.slice(expr.start, expr.end), "{['s', tone]}");
+});
+
+/* ------------------------------------------------------------------ I-5 */
+
+test('I-5 an imbalance throws carrying the offset of the unclosed brace', () => {
+ const src = '{ oops
';
+ assert.throws(
+ () => scanRegions(src),
+ (e) => {
+ assert.ok(e instanceof UnbalancedBraceError);
+ assert.equal(e.offset, src.indexOf('{'));
+ return true;
+ }
+ );
+});
+
+/* ------------------------------------------------------------------ I-6 */
+
+test('I-6 the module is pure — three functions and an error type, nothing else', async () => {
+ const mod = await fromDist('scan.js');
+ assert.deepEqual(Object.keys(mod).sort(), [
+ 'UnbalancedBraceError',
+ 'matchBrace',
+ 'scanRegions',
+ 'splitFrontmatter',
+ ]);
+});
+
+/* ------------------------------------------- the corpus scans at all (T016) */
+
+test('every built-in component and layout scans without throwing', async () => {
+ const files = await corpus();
+ assert.ok(files.length > 0, 'corpus is empty — the test proves nothing');
+
+ for (const { name, source } of files) {
+ assert.doesNotThrow(() => scanRegions(source), `${name} failed to scan`);
+ }
+});