@templatical/template-tools 0.50.0 → 0.51.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { Server } from "node:http";
2
2
  //#region src/live/index.d.ts
3
- export declare const EDITOR_VERSION = "0.50.0";
3
+ export declare const EDITOR_VERSION = "0.51.1";
4
4
  export declare const DEFAULT_PORT = 4747;
5
5
  export declare const WORKING_DIR = ".templatical";
6
6
  export declare const PID_FILE: string;
@@ -7,7 +7,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  //#region src/live/index.ts
9
9
  const here = dirname(fileURLToPath(import.meta.url));
10
- const EDITOR_VERSION = "0.50.0";
10
+ const EDITOR_VERSION = "0.51.1";
11
11
  const DEFAULT_PORT = 4747;
12
12
  const WORKING_DIR = ".templatical";
13
13
  const PID_FILE = join(WORKING_DIR, "live-server.pid");
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/live/index.ts"],"sourcesContent":["// The local live-preview bridge.\n//\n// It serves live/index.html (which loads the REAL Templatical editor from the\n// CDN), streams agent-driven template updates to the page over Server-Sent\n// Events, and buffers the page's hand-edits so the caller can detect divergence\n// (a user edit in the browser) before overwriting.\n//\n// This package's own `live` CLI command drives it today, over localhost HTTP.\n// It stays side-effect free at import time and writes nothing to stdout so\n// that a future stdio-based caller — an MCP server reserving stdout for\n// JSON-RPC — can be added without auditing this module first: a stray write\n// here would corrupt that protocol. Keep all human-facing output in the\n// callers (cli/output.ts is the CLI's own single writer;\n// tests/cli-output-discipline.test.ts enforces that no other module under\n// src/ touches stdout).\n\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createDefaultTemplateContent,\n type TemplateContent,\n} from \"@templatical/types\";\nimport {\n buildSpecimen,\n buildSpecimenTemplate,\n checkRecipe,\n runRecipe,\n validateCustomBlockDefinition,\n type CustomBlockWorkingFile,\n} from \"../custom-block\";\nimport {\n fetchedSpecimenBlocks,\n type FetchedSpecimen,\n} from \"../custom-block/specimen\";\nimport { validateTemplate } from \"../validate\";\n\nconst here = dirname(fileURLToPath(import.meta.url));\n\n// The CDN editor version the live harness loads. It is PINNED to this package's\n// schema version: schema.json is generated from @templatical/types, and types +\n// editor bump in lockstep (changesets fixed group), so the editor at this\n// version has the same block model the schema describes.\n//\n// Kept in step automatically by scripts/sync-pins.mjs at release time.\n// tests/cdn-pin.test.ts is the safety net that fails CI if it ever drifts.\nexport const EDITOR_VERSION = \"0.50.0\";\n\nexport const DEFAULT_PORT = 4747;\nexport const WORKING_DIR = \".templatical\";\nexport const PID_FILE = join(WORKING_DIR, \"live-server.pid\");\n\n// Resolved from this module rather than the cwd so it works identically from\n// src/live/ (tests) and dist/live/ (published) — both sit two levels under the\n// package root, where live/index.html ships.\nconst HARNESS_FILE = resolve(here, \"../../live/index.html\");\n\n// --------------------------------------------------------------------------\n// Pure helpers\n// --------------------------------------------------------------------------\n\n/** Order-insensitive structural equality for parsed-JSON template content. */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n const aList = a as unknown[];\n const bList = b as unknown[];\n if (aList.length !== bList.length) return false;\n for (let i = 0; i < aList.length; i++) {\n if (!deepEqual(aList[i], bList[i])) return false;\n }\n return true;\n }\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const ak = Object.keys(aObj);\n const bk = Object.keys(bObj);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(bObj, k)) return false;\n if (!deepEqual(aObj[k], bObj[k])) return false;\n }\n return true;\n}\n\n/** Read + parse the working file, or return null when it is absent/unparseable. */\nexport function readWorkingFile(path: string): unknown {\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return null;\n }\n}\n\n/** List the working templates in a project's `.templatical/` folder, by name. */\nexport function listWorkingFiles(cwd: string): string[] {\n const dir = resolve(cwd, WORKING_DIR);\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((f) => f.endsWith(\".json\"))\n .sort();\n}\n\nasync function readJsonBody(req: NodeJS.ReadableStream): Promise<\n | {\n content?: unknown;\n baseline?: boolean;\n blockId?: string;\n parentBlockId?: unknown;\n blockType?: unknown;\n label?: unknown;\n text?: string;\n consumeAnnotations?: boolean;\n fieldValues?: unknown;\n }\n | undefined\n> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n const raw = Buffer.concat(chunks).toString(\"utf8\");\n return raw ? JSON.parse(raw) : undefined;\n}\n\n/**\n * Open a URL in the user's default browser — best-effort and cross-platform.\n * A silent no-op where there's no browser (headless / CI / sandbox); callers\n * always surface the URL too, so nothing is lost when this does nothing.\n */\nexport function openBrowser(url: string): void {\n const [cmd, cmdArgs]: [string, string[]] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? [\"cmd\", [\"/c\", \"start\", \"\", url]]\n : [\"xdg-open\", [url]];\n try {\n const child = spawn(cmd, cmdArgs, { stdio: \"ignore\", detached: true });\n child.on(\"error\", () => {}); // no browser available — ignore\n child.unref();\n } catch {\n /* ignore — the URL is surfaced by the caller regardless */\n }\n}\n\n// --------------------------------------------------------------------------\n// Pidfile helpers (used by this package's own `live` CLI command; a future\n// stdio-based MCP server would own its process lifecycle directly and would\n// not need them)\n// --------------------------------------------------------------------------\n\nexport type LiveMode = \"template\" | \"custom-block\";\n\nexport interface PidfileInfo {\n pid: number;\n port: number;\n /** Absent in a pidfile from a template-only bridge; read as \"template\". */\n mode?: LiveMode;\n /** The absolute path the server is serving. */\n path?: string;\n /** Custom-block mode: the absolute --host template, when one was given. */\n host?: string;\n /** Custom-block mode with --fetch: the --values the recipe runs with. */\n fetch?: Record<string, unknown>;\n}\n\n/** How the data-source request for the fetched specimen state went. */\nexport type FetchSummary =\n { ok: true; unmapped: string[] } | { ok: false; error: string };\n\n/** What a reload pushed, and why it pushed nothing when `ok` is false. */\nexport interface ReloadResult {\n ok: boolean;\n clients: number;\n consumed: boolean;\n mode: LiveMode;\n error?: string;\n /** With the `fetch` option: the request behind the fetched state. */\n fetch?: FetchSummary;\n}\n\nexport function pidfilePath(cwd: string): string {\n return resolve(cwd, PID_FILE);\n}\n\nexport function readPidfile(cwd: string): PidfileInfo | null {\n const p = pidfilePath(cwd);\n if (!existsSync(p)) return null;\n try {\n return JSON.parse(readFileSync(p, \"utf8\")) as PidfileInfo;\n } catch {\n return null;\n }\n}\n\nexport function processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * A note the user left in the browser, against a block or the template as a\n * whole. Delivered on GET /content - the call the agent already makes before\n * every change - so notes need no polling and no separate endpoint to drain.\n */\nexport interface Annotation {\n id: string;\n /** null for a note about the template rather than one block. */\n blockId: string | null;\n /** The next data-block-id above the target. null at the top level and for a template note. */\n parentBlockId: string | null;\n blockType: string | null;\n /** Snapshot of the block's text at save time, already truncated. */\n label: string;\n text: string;\n createdAt: number;\n}\n\nconst NOTE_TEXT_MAX = 2000;\nconst NOTE_LABEL_MAX = 80;\nconst NOTE_BLOCK_TYPE_MAX = 40;\nconst NOTE_QUEUE_MAX = 40;\n\nfunction readNoteText(value: unknown): { text: string } | { error: string } {\n const text = typeof value === \"string\" ? value.trim() : \"\";\n if (!text) return { error: \"An annotation needs non-empty `text`.\" };\n if (text.length > NOTE_TEXT_MAX) {\n return { error: \"A note can be at most 2000 characters.\" };\n }\n return { text };\n}\n\nfunction readOptionalId(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction readBlockType(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n return value.trim().slice(0, NOTE_BLOCK_TYPE_MAX);\n}\n\nfunction readLabel(value: unknown): string {\n if (typeof value !== \"string\") return \"\";\n return value.replace(/\\s+/g, \" \").trim().slice(0, NOTE_LABEL_MAX);\n}\n\nfunction annotationIdFromPath(pathname: string): string | null {\n const prefix = \"/annotations/\";\n if (!pathname.startsWith(prefix)) return null;\n const raw = pathname.slice(prefix.length);\n if (!raw || raw.includes(\"/\")) return null;\n try {\n return decodeURIComponent(raw);\n } catch {\n return null;\n }\n}\n\nfunction loopbackNames(port: number): string[] {\n return [`localhost:${port}`, `127.0.0.1:${port}`, `[::1]:${port}`];\n}\n\nfunction noteNotFound(res: ServerResponse): void {\n res.writeHead(404, { \"content-type\": \"text/plain\" });\n res.end(\"No note with that id.\");\n}\n\n// --------------------------------------------------------------------------\n// Bridge server\n// --------------------------------------------------------------------------\n\nexport interface BridgeHandle {\n server: Server;\n port: number;\n url: string;\n /** The absolute path of the working file this bridge is serving. */\n workingPath: string;\n /** The page's latest state, for callers that drive the bridge in-process. */\n getEditorState: () => {\n divergent: boolean;\n content: unknown;\n annotations: Annotation[];\n };\n /** Re-read the working file and push it to every connected page. */\n reload: (options?: { consumeAnnotations?: boolean }) => ReloadResult;\n /** With the `fetch` option: the last data-source request's outcome. */\n lastFetch: () => FetchSummary | null;\n close: () => Promise<void>;\n}\n\nexport interface StartBridgeOptions {\n cwd?: string;\n port?: number;\n file?: string;\n harnessFile?: string;\n /** Custom-block mode: serve this definition's specimen instead of a template. */\n customBlock?: string;\n /** Custom-block mode only: a template the specimen is appended to. */\n host?: string;\n /** Environment the data-source recipe resolves `${env:…}` from. Defaults to process.env. */\n env?: Record<string, string | undefined>;\n /**\n * Custom-block mode only: run the `dataSourcePreview` recipe and add a\n * \"fetched\" state, filled from the real endpoint, to the specimen. `values`\n * override the field defaults for the request (the id it fetches by). It\n * runs before the bridge starts listening and again on every `POST\n * /reload`; the in-process `reload()` reuses the last result.\n */\n fetch?: { values: Record<string, unknown> };\n}\n\n/**\n * Start the bridge HTTP server. Pure server + in-memory sync state; callers own\n * process lifecycle. Resolves once listening.\n *\n * The returned handle exposes `getEditorState` and `reload` directly, so an\n * in-process caller (the MCP server) never has to make an HTTP request to its\n * own bridge — that is the whole reason live mode can work inside a sandboxed\n * agent. The equivalent HTTP endpoints stay for the skill's out-of-process CLI.\n */\nexport function startBridge({\n cwd = process.cwd(),\n port = 0,\n file = join(WORKING_DIR, \"template.json\"),\n harnessFile = HARNESS_FILE,\n customBlock,\n host,\n env = process.env,\n fetch: fetchOption,\n}: StartBridgeOptions = {}): Promise<BridgeHandle> {\n const abs = (p: string) => (isAbsolute(p) ? p : resolve(cwd, p));\n const customBlockPath = customBlock ? abs(customBlock) : null;\n const hostPath = host ? abs(host) : null;\n const workingPath = customBlockPath ?? abs(file);\n\n // Sync state. `baseline` is the editor's NORMALIZED view of the caller's last\n // content (captured by the page right after it applies an update), so the\n // editor's own load-time normalization never reads as a user edit.\n // `editorCurrent` is the page's latest getContent(); `divergent` is true when\n // it structurally differs from `baseline` — i.e. the user hand-edited.\n const state: {\n baseline: unknown;\n editorCurrent: unknown;\n divergent: boolean;\n annotations: Annotation[];\n } = {\n baseline: null,\n editorCurrent: null,\n divergent: false,\n annotations: [],\n };\n let nextAnnotationNumber = 1;\n function mintAnnotationId(): string {\n const n = nextAnnotationNumber++;\n return `a${n}-${Date.now().toString(36)}`;\n }\n const clients = new Set<ServerResponse>();\n\n function broadcastTemplate(content: unknown): void {\n const payload = `event: template\\ndata: ${JSON.stringify(content)}\\n\\n`;\n for (const res of clients) res.write(payload);\n }\n\n /** Why the bridge won't run this definition's recipe, or null when it will. */\n function recipeRefusal(def: CustomBlockWorkingFile): string | null {\n if (!def.dataSourcePreview) return \"This block has no dataSourcePreview.\";\n const errors = checkRecipe(def).filter((i) => i.severity === \"error\");\n return errors.length > 0\n ? `The dataSourcePreview recipe is refused: ${errors\n .map((i) => `${i.ruleId}: ${i.message}`)\n .join(\"; \")}`\n : null;\n }\n\n // The fetched state's last outcome, null until the first run.\n let fetched: (FetchedSpecimen & { unmapped?: string[] }) | null = null;\n\n async function refreshFetched(): Promise<void> {\n const data = readWorkingFile(customBlockPath as string);\n if (data === null || !validateCustomBlockDefinition(data).valid) {\n fetched = {\n ok: false,\n error: \"The custom block definition is missing or invalid.\",\n };\n return;\n }\n const def = data as CustomBlockWorkingFile;\n const recipe = def.dataSourcePreview;\n const refusal = recipeRefusal(def);\n if (!recipe || refusal !== null) {\n fetched = { ok: false, error: refusal ?? \"\" };\n return;\n }\n const values = {\n ...buildSpecimen(def)[0].fieldValues,\n ...fetchOption?.values,\n };\n const result = await runRecipe(recipe, values, { env });\n fetched = result.ok\n ? {\n ok: true,\n fieldValues: { ...values, ...result.values },\n unmapped: result.unmapped,\n }\n : { ok: false, error: result.error };\n }\n\n function lastFetch(): FetchSummary | null {\n if (!fetched) return null;\n return fetched.ok\n ? { ok: true, unmapped: fetched.unmapped ?? [] }\n : { ok: false, error: fetched.error };\n }\n\n type BlockView =\n | {\n ok: true;\n def: CustomBlockWorkingFile;\n payload: unknown;\n template: TemplateContent;\n }\n | { ok: false; error: string };\n\n // Read fresh on every request: the agent edits the file between reloads,\n // and the page must never be handed a definition that failed validation.\n function readBlockView(): BlockView {\n const data = readWorkingFile(customBlockPath as string);\n if (data === null || !validateCustomBlockDefinition(data).valid) {\n return {\n ok: false,\n error:\n \"The custom block definition is missing or invalid. Run `templatical custom-block validate` on it.\",\n };\n }\n let hostContent: TemplateContent | undefined;\n if (hostPath) {\n const h = readWorkingFile(hostPath);\n if (h === null || !validateTemplate(h).valid) {\n return {\n ok: false,\n error:\n \"The --host template is missing or invalid. Run `templatical validate` on it.\",\n };\n }\n hostContent = h as TemplateContent;\n }\n const def = data as CustomBlockWorkingFile;\n const { dataSourcePreview, ...definition } = def;\n // The fetched state leads the specimen: it is the realistic one.\n const base = hostContent ?? createDefaultTemplateContent();\n const lead =\n fetchOption && fetched ? fetchedSpecimenBlocks(def, fetched) : [];\n return {\n ok: true,\n def,\n payload: {\n definition,\n dataSource: dataSourcePreview\n ? { label: dataSourcePreview.label }\n : null,\n },\n template: buildSpecimenTemplate(def, {\n ...base,\n blocks: [...base.blocks, ...lead],\n }),\n };\n }\n\n function sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(body));\n }\n\n function getEditorState(): {\n divergent: boolean;\n content: unknown;\n annotations: Annotation[];\n } {\n return {\n divergent: state.divergent,\n content: state.editorCurrent,\n annotations: state.annotations,\n };\n }\n\n function reload(options?: { consumeAnnotations?: boolean }): ReloadResult {\n // A failed read pushes nothing and leaves the page's state alone: the\n // page still shows what it showed, so its divergence and notes still hold.\n if (customBlockPath) {\n const view = readBlockView();\n if (!view.ok) {\n return {\n ok: false,\n clients: clients.size,\n consumed: false,\n mode: \"custom-block\",\n error: view.error,\n };\n }\n state.baseline = null;\n state.editorCurrent = null;\n state.divergent = false;\n const consumed = options?.consumeAnnotations === true;\n if (consumed) state.annotations = [];\n const payload = `event: custom-block\\ndata: ${JSON.stringify({ block: view.payload, template: view.template })}\\n\\n`;\n for (const res of clients) res.write(payload);\n const fetch = fetchOption ? lastFetch() : null;\n return {\n ok: true,\n clients: clients.size,\n consumed,\n mode: \"custom-block\",\n ...(fetch ? { fetch } : {}),\n };\n }\n\n // The freshly-written file is the new baseline, so any pending user edit is\n // superseded. Notes stay: a plain reload is an ordinary edit, and clearing\n // them here would drop a queue the agent has not applied. consumeAnnotations\n // clears only after the file was actually read — clearing first would drop\n // the notes and push nothing when the file is missing.\n const content = readWorkingFile(workingPath);\n if (content === null) {\n return {\n ok: false,\n clients: clients.size,\n consumed: false,\n mode: \"template\",\n error: `${workingPath} is missing or isn't valid JSON. Run \\`templatical validate\\` on it.`,\n };\n }\n state.baseline = null;\n state.editorCurrent = null;\n state.divergent = false;\n const consumed = options?.consumeAnnotations === true;\n if (consumed) state.annotations = [];\n broadcastTemplate(content);\n return { ok: true, clients: clients.size, consumed, mode: \"template\" };\n }\n\n const server = createServer(async (req, res) => {\n const { pathname } = new URL(req.url ?? \"/\", \"http://localhost\");\n const method = req.method ?? \"GET\";\n\n try {\n // Only this listener's own loopback names are served: a DNS-rebound\n // hostname would otherwise let any web page read the bridge as same-origin.\n const addr = server.address();\n const listening =\n typeof addr === \"object\" && addr !== null ? addr.port : port;\n const hostHeader = req.headers.host ?? \"\";\n if (!loopbackNames(listening).some((n) => n === hostHeader)) {\n res\n .writeHead(403, { \"content-type\": \"text/plain\" })\n .end(\"Forbidden host.\");\n return;\n }\n\n // Writes. The Host check above doesn't stop a page on another site from\n // sending a simple cross-origin POST to localhost (text/plain, no\n // preflight): its response is unreadable, but the write still lands, so\n // a note it posts would reach the agent as the user's own. A browser\n // attaches its Origin to every such request, so a foreign one is\n // refused, and a POST must be JSON, which no simple request can be. PUT\n // and DELETE need a preflight cross-site, which the bridge never grants.\n if (method !== \"GET\" && method !== \"HEAD\") {\n const origin = req.headers.origin;\n if (\n origin !== undefined &&\n !loopbackNames(listening).some((n) => origin === `http://${n}`)\n ) {\n sendJson(res, 403, { error: \"Forbidden origin.\" });\n return;\n }\n const type = (req.headers[\"content-type\"] ?? \"\").toLowerCase();\n if (method === \"POST\" && !type.startsWith(\"application/json\")) {\n sendJson(res, 415, { error: \"Send application/json.\" });\n return;\n }\n }\n\n if (\n method === \"GET\" &&\n (pathname === \"/\" || pathname === \"/index.html\")\n ) {\n const html = readFileSync(harnessFile, \"utf8\").replaceAll(\n \"{{EDITOR_VERSION}}\",\n EDITOR_VERSION,\n );\n res.writeHead(200, { \"content-type\": \"text/html; charset=utf-8\" });\n res.end(html);\n return;\n }\n\n if (method === \"GET\" && pathname === \"/custom-block\") {\n if (!customBlockPath) {\n res.writeHead(204).end();\n return;\n }\n const view = readBlockView();\n if (view.ok) sendJson(res, 200, view.payload);\n else sendJson(res, 422, { error: view.error });\n return;\n }\n\n if (method === \"POST\" && pathname === \"/data-source/fetch\") {\n if (!customBlockPath) {\n res.writeHead(404, { \"content-type\": \"text/plain\" }).end(\"Not found\");\n return;\n }\n const view = readBlockView();\n if (!view.ok) {\n sendJson(res, 422, { error: view.error });\n return;\n }\n // The recipe gate runs before the page's request is even read: a\n // recipe `custom-block validate` rejects is never sent anywhere.\n const recipe = view.def.dataSourcePreview;\n const refusal = recipeRefusal(view.def);\n if (!recipe || refusal !== null) {\n sendJson(res, recipe ? 422 : 409, { error: refusal });\n return;\n }\n // Only fieldValues is read: the recipe (URL, headers) never comes from the page.\n const body = await readJsonBody(req);\n const fieldValues =\n body?.fieldValues &&\n typeof body.fieldValues === \"object\" &&\n !Array.isArray(body.fieldValues)\n ? (body.fieldValues as Record<string, unknown>)\n : {};\n const result = await runRecipe(recipe, fieldValues, { env });\n if (result.ok) {\n sendJson(res, 200, {\n values: result.values,\n unmapped: result.unmapped,\n });\n } else {\n sendJson(res, 502, { error: result.error });\n }\n return;\n }\n\n if (method === \"GET\" && pathname === \"/template\") {\n if (customBlockPath) {\n const view = readBlockView();\n if (view.ok) sendJson(res, 200, view.template);\n else sendJson(res, 422, { error: view.error });\n return;\n }\n const content = readWorkingFile(workingPath);\n if (content === null) {\n res.writeHead(204).end(); // no working file yet — page inits empty\n return;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(content));\n return;\n }\n\n if (method === \"GET\" && pathname === \"/events\") {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n });\n res.write(\"event: ready\\ndata: {}\\n\\n\");\n clients.add(res);\n const ping = setInterval(() => res.write(\": ping\\n\\n\"), 15000);\n req.on(\"close\", () => {\n clearInterval(ping);\n clients.delete(res);\n });\n return;\n }\n\n if (method === \"POST\" && pathname === \"/content\") {\n const body = await readJsonBody(req);\n const content = body?.content;\n if (body?.baseline) {\n // Post-apply snapshot: this is the editor's normalized view of the\n // caller's content, not a user edit.\n state.baseline = content ?? null;\n state.editorCurrent = content ?? null;\n state.divergent = false;\n } else {\n state.editorCurrent = content ?? null;\n state.divergent =\n state.baseline !== null && !deepEqual(content, state.baseline);\n }\n res.writeHead(204).end();\n return;\n }\n\n if (method === \"GET\" && pathname === \"/content\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(getEditorState()));\n return;\n }\n\n if (method === \"POST\" && pathname === \"/annotations\") {\n const body = await readJsonBody(req);\n const parsed = readNoteText(body?.text);\n if (\"error\" in parsed) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(parsed.error);\n return;\n }\n if (state.annotations.length >= NOTE_QUEUE_MAX) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(\"The note queue is full (40).\");\n return;\n }\n const blockId = readOptionalId(body?.blockId);\n let parentBlockId = readOptionalId(body?.parentBlockId);\n if (parentBlockId === blockId) parentBlockId = null;\n const annotation: Annotation = {\n id: mintAnnotationId(),\n blockId,\n parentBlockId,\n blockType: readBlockType(body?.blockType),\n label: readLabel(body?.label),\n text: parsed.text,\n createdAt: Date.now(),\n };\n state.annotations.push(annotation);\n res.writeHead(201, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(annotation));\n return;\n }\n\n const noteId = annotationIdFromPath(pathname);\n if (noteId && (method === \"PUT\" || method === \"DELETE\")) {\n const index = state.annotations.findIndex((note) => note.id === noteId);\n if (index < 0) {\n noteNotFound(res);\n return;\n }\n if (method === \"DELETE\") {\n state.annotations.splice(index, 1);\n res.writeHead(204).end();\n return;\n }\n const body = await readJsonBody(req);\n const parsed = readNoteText(body?.text);\n if (\"error\" in parsed) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(parsed.error);\n return;\n }\n const updated: Annotation = {\n ...state.annotations[index],\n text: parsed.text,\n };\n state.annotations[index] = updated;\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(updated));\n return;\n }\n\n if (method === \"POST\" && pathname === \"/reload\") {\n const body = await readJsonBody(req);\n if (fetchOption && customBlockPath) await refreshFetched();\n const result = reload({\n consumeAnnotations: body?.consumeAnnotations === true,\n });\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(result));\n return;\n }\n\n res.writeHead(404, { \"content-type\": \"text/plain\" }).end(\"Not found\");\n } catch (err) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(`Bad request: ${(err as Error).message}`);\n }\n });\n\n // The first fetch lands before the page can load, so it never shows a\n // sheet without the fetched state.\n const ready =\n fetchOption && customBlockPath ? refreshFetched() : Promise.resolve();\n\n return ready.then(\n () =>\n new Promise<BridgeHandle>((resolvePromise, rejectPromise) => {\n // listen() reports failures (e.g. EADDRINUSE) as an 'error' event, not a\n // throw — without this the error would be unhandled and crash the process.\n const onListenError = (err: Error) => rejectPromise(err);\n server.once(\"error\", onListenError);\n server.listen(port, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onListenError);\n const address = server.address();\n const actualPort =\n typeof address === \"object\" && address !== null\n ? address.port\n : port;\n resolvePromise({\n server,\n port: actualPort,\n url: `http://localhost:${actualPort}/`,\n workingPath,\n getEditorState,\n reload,\n lastFetch,\n close: () =>\n new Promise<void>((r) => {\n for (const c of clients) c.end();\n clients.clear();\n server.close(() => r());\n }),\n });\n });\n }),\n );\n}\n\nexport interface PreferringHandle extends BridgeHandle {\n fellBack: boolean;\n preferredPort?: number;\n}\n\n/**\n * Start the bridge on `preferredPort`, falling back to an OS-assigned free port\n * when that one is occupied — so a busy port never fails the launch. The page\n * uses relative URLs, so the actual port is discovered, not assumed. The\n * returned handle carries `fellBack: true` when it landed on a different port.\n */\nexport async function startBridgePreferring({\n preferredPort = DEFAULT_PORT,\n ...opts\n}: StartBridgeOptions & {\n preferredPort?: number;\n} = {}): Promise<PreferringHandle> {\n try {\n const handle = await startBridge({ ...opts, port: preferredPort });\n return { ...handle, fellBack: false };\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== \"EADDRINUSE\") throw err;\n const handle = await startBridge({ ...opts, port: 0 });\n return { ...handle, fellBack: true, preferredPort };\n }\n}\n"],"mappings":";;;;;;;;AAuCA,MAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;AASnD,MAAa,iBAAiB;AAE9B,MAAa,eAAe;AAC5B,MAAa,cAAc;AAC3B,MAAa,WAAW,KAAK,aAAa,iBAAiB;AAK3D,MAAM,eAAe,QAAQ,MAAM,uBAAuB;;AAO1D,SAAgB,UAAU,GAAY,GAAqB;CACzD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,MAAM,QAAQ,MAAM,MAAM,OAAO;CACrC,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU,OAAO;CAC3D,MAAM,OAAO,MAAM,QAAQ,CAAC;CAC5B,IAAI,SAAS,MAAM,QAAQ,CAAC,GAAG,OAAO;CACtC,IAAI,MAAM;EACR,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,IAAI,MAAM,WAAW,MAAM,QAAQ,OAAO;EAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAChC,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,EAAE,GAAG,OAAO;EAE7C,OAAO;CACT;CACA,MAAM,OAAO;CACb,MAAM,OAAO;CACb,MAAM,KAAK,OAAO,KAAK,IAAI;CAC3B,MAAM,KAAK,OAAO,KAAK,IAAI;CAC3B,IAAI,GAAG,WAAW,GAAG,QAAQ,OAAO;CACpC,KAAK,MAAM,KAAK,IAAI;EAClB,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,MAAM,CAAC,GAAG,OAAO;EAC3D,IAAI,CAAC,UAAU,KAAK,IAAI,KAAK,EAAE,GAAG,OAAO;CAC3C;CACA,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAuB;CACrD,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,IAAI;EACF,OAAO,KAAK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AK,UAAU,MAAM,CAAC;IAC9B;GACF;GAEA,IAAI,UAAU,KAAK,EAAE,gBAAgB,aAAa,CAAC,CAAC,CAAC,IAAI,WAAW;EACtE,SAAS,KAAK;GACZ,IAAI,UAAU,KAAK,EAAE,gBAAgB,aAAa,CAAC;GACnD,IAAI,IAAI,gBAAiB,IAAc,SAAS;EAClD;CACF,CAAC;CAOD,QAFE,eAAe,kBAAkB,eAAe,IAAI,QAAQ,QAAQ,EAAA,CAEzD,WAET,IAAI,SAAuB,gBAAgB,kBAAkB;EAG3D,MAAM,iBAAiB,QAAe,cAAc,GAAG;EACvD,OAAO,KAAK,SAAS,aAAa;EAClC,OAAO,OAAO,MAAM,mBAAmB;GACrC,OAAO,eAAe,SAAS,aAAa;GAC5C,MAAM,UAAU,OAAO,QAAQ;GAC/B,MAAM,aACJ,OAAO,YAAY,YAAY,YAAY,OACvC,QAAQ,OACR;GACN,eAAe;IACb;IACA,MAAM;IACN,KAAK,oBAAoB,WAAW;IACpC;IACA;IACA;IACA;IACA,aACE,IAAI,SAAe,MAAM;KACvB,KAAK,MAAM,KAAK,SAAS,EAAE,IAAI;KAC/B,QAAQ,MAAM;KACd,OAAO,YAAY,EAAE,CAAC;IACxB,CAAC;GACL,CAAC;EACH,CAAC;CACH,CAAC,CACL;AACF;;;;;;;AAaA,eAAsB,sBAAsB,EAC1C,gBAAgB,cAChB,GAAG,SAGD,CAAC,GAA8B;CACjC,IAAI;EAEF,OAAO;GAAE,GAAG,MADS,YAAY;IAAE,GAAG;IAAM,MAAM;GAAc,CAAC;GAC7C,UAAU;EAAM;CACtC,SAAS,KAAK;EACZ,IAAK,KAA+B,SAAS,cAAc,MAAM;EAEjE,OAAO;GAAE,GAAG,MADS,YAAY;IAAE,GAAG;IAAM,MAAM;GAAE,CAAC;GACjC,UAAU;GAAM;EAAc;CACpD;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/live/index.ts"],"sourcesContent":["// The local live-preview bridge.\n//\n// It serves live/index.html (which loads the REAL Templatical editor from the\n// CDN), streams agent-driven template updates to the page over Server-Sent\n// Events, and buffers the page's hand-edits so the caller can detect divergence\n// (a user edit in the browser) before overwriting.\n//\n// This package's own `live` CLI command drives it today, over localhost HTTP.\n// It stays side-effect free at import time and writes nothing to stdout so\n// that a future stdio-based caller — an MCP server reserving stdout for\n// JSON-RPC — can be added without auditing this module first: a stray write\n// here would corrupt that protocol. Keep all human-facing output in the\n// callers (cli/output.ts is the CLI's own single writer;\n// tests/cli-output-discipline.test.ts enforces that no other module under\n// src/ touches stdout).\n\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n createDefaultTemplateContent,\n type TemplateContent,\n} from \"@templatical/types\";\nimport {\n buildSpecimen,\n buildSpecimenTemplate,\n checkRecipe,\n runRecipe,\n validateCustomBlockDefinition,\n type CustomBlockWorkingFile,\n} from \"../custom-block\";\nimport {\n fetchedSpecimenBlocks,\n type FetchedSpecimen,\n} from \"../custom-block/specimen\";\nimport { validateTemplate } from \"../validate\";\n\nconst here = dirname(fileURLToPath(import.meta.url));\n\n// The CDN editor version the live harness loads. It is PINNED to this package's\n// schema version: schema.json is generated from @templatical/types, and types +\n// editor bump in lockstep (changesets fixed group), so the editor at this\n// version has the same block model the schema describes.\n//\n// Kept in step automatically by scripts/sync-pins.mjs at release time.\n// tests/cdn-pin.test.ts is the safety net that fails CI if it ever drifts.\nexport const EDITOR_VERSION = \"0.51.1\";\n\nexport const DEFAULT_PORT = 4747;\nexport const WORKING_DIR = \".templatical\";\nexport const PID_FILE = join(WORKING_DIR, \"live-server.pid\");\n\n// Resolved from this module rather than the cwd so it works identically from\n// src/live/ (tests) and dist/live/ (published) — both sit two levels under the\n// package root, where live/index.html ships.\nconst HARNESS_FILE = resolve(here, \"../../live/index.html\");\n\n// --------------------------------------------------------------------------\n// Pure helpers\n// --------------------------------------------------------------------------\n\n/** Order-insensitive structural equality for parsed-JSON template content. */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n const aList = a as unknown[];\n const bList = b as unknown[];\n if (aList.length !== bList.length) return false;\n for (let i = 0; i < aList.length; i++) {\n if (!deepEqual(aList[i], bList[i])) return false;\n }\n return true;\n }\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const ak = Object.keys(aObj);\n const bk = Object.keys(bObj);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(bObj, k)) return false;\n if (!deepEqual(aObj[k], bObj[k])) return false;\n }\n return true;\n}\n\n/** Read + parse the working file, or return null when it is absent/unparseable. */\nexport function readWorkingFile(path: string): unknown {\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return null;\n }\n}\n\n/** List the working templates in a project's `.templatical/` folder, by name. */\nexport function listWorkingFiles(cwd: string): string[] {\n const dir = resolve(cwd, WORKING_DIR);\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((f) => f.endsWith(\".json\"))\n .sort();\n}\n\nasync function readJsonBody(req: NodeJS.ReadableStream): Promise<\n | {\n content?: unknown;\n baseline?: boolean;\n blockId?: string;\n parentBlockId?: unknown;\n blockType?: unknown;\n label?: unknown;\n text?: string;\n consumeAnnotations?: boolean;\n fieldValues?: unknown;\n }\n | undefined\n> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n const raw = Buffer.concat(chunks).toString(\"utf8\");\n return raw ? JSON.parse(raw) : undefined;\n}\n\n/**\n * Open a URL in the user's default browser — best-effort and cross-platform.\n * A silent no-op where there's no browser (headless / CI / sandbox); callers\n * always surface the URL too, so nothing is lost when this does nothing.\n */\nexport function openBrowser(url: string): void {\n const [cmd, cmdArgs]: [string, string[]] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? [\"cmd\", [\"/c\", \"start\", \"\", url]]\n : [\"xdg-open\", [url]];\n try {\n const child = spawn(cmd, cmdArgs, { stdio: \"ignore\", detached: true });\n child.on(\"error\", () => {}); // no browser available — ignore\n child.unref();\n } catch {\n /* ignore — the URL is surfaced by the caller regardless */\n }\n}\n\n// --------------------------------------------------------------------------\n// Pidfile helpers (used by this package's own `live` CLI command; a future\n// stdio-based MCP server would own its process lifecycle directly and would\n// not need them)\n// --------------------------------------------------------------------------\n\nexport type LiveMode = \"template\" | \"custom-block\";\n\nexport interface PidfileInfo {\n pid: number;\n port: number;\n /** Absent in a pidfile from a template-only bridge; read as \"template\". */\n mode?: LiveMode;\n /** The absolute path the server is serving. */\n path?: string;\n /** Custom-block mode: the absolute --host template, when one was given. */\n host?: string;\n /** Custom-block mode with --fetch: the --values the recipe runs with. */\n fetch?: Record<string, unknown>;\n}\n\n/** How the data-source request for the fetched specimen state went. */\nexport type FetchSummary =\n { ok: true; unmapped: string[] } | { ok: false; error: string };\n\n/** What a reload pushed, and why it pushed nothing when `ok` is false. */\nexport interface ReloadResult {\n ok: boolean;\n clients: number;\n consumed: boolean;\n mode: LiveMode;\n error?: string;\n /** With the `fetch` option: the request behind the fetched state. */\n fetch?: FetchSummary;\n}\n\nexport function pidfilePath(cwd: string): string {\n return resolve(cwd, PID_FILE);\n}\n\nexport function readPidfile(cwd: string): PidfileInfo | null {\n const p = pidfilePath(cwd);\n if (!existsSync(p)) return null;\n try {\n return JSON.parse(readFileSync(p, \"utf8\")) as PidfileInfo;\n } catch {\n return null;\n }\n}\n\nexport function processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * A note the user left in the browser, against a block or the template as a\n * whole. Delivered on GET /content - the call the agent already makes before\n * every change - so notes need no polling and no separate endpoint to drain.\n */\nexport interface Annotation {\n id: string;\n /** null for a note about the template rather than one block. */\n blockId: string | null;\n /** The next data-block-id above the target. null at the top level and for a template note. */\n parentBlockId: string | null;\n blockType: string | null;\n /** Snapshot of the block's text at save time, already truncated. */\n label: string;\n text: string;\n createdAt: number;\n}\n\nconst NOTE_TEXT_MAX = 2000;\nconst NOTE_LABEL_MAX = 80;\nconst NOTE_BLOCK_TYPE_MAX = 40;\nconst NOTE_QUEUE_MAX = 40;\n\nfunction readNoteText(value: unknown): { text: string } | { error: string } {\n const text = typeof value === \"string\" ? value.trim() : \"\";\n if (!text) return { error: \"An annotation needs non-empty `text`.\" };\n if (text.length > NOTE_TEXT_MAX) {\n return { error: \"A note can be at most 2000 characters.\" };\n }\n return { text };\n}\n\nfunction readOptionalId(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction readBlockType(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n return value.trim().slice(0, NOTE_BLOCK_TYPE_MAX);\n}\n\nfunction readLabel(value: unknown): string {\n if (typeof value !== \"string\") return \"\";\n return value.replace(/\\s+/g, \" \").trim().slice(0, NOTE_LABEL_MAX);\n}\n\nfunction annotationIdFromPath(pathname: string): string | null {\n const prefix = \"/annotations/\";\n if (!pathname.startsWith(prefix)) return null;\n const raw = pathname.slice(prefix.length);\n if (!raw || raw.includes(\"/\")) return null;\n try {\n return decodeURIComponent(raw);\n } catch {\n return null;\n }\n}\n\nfunction loopbackNames(port: number): string[] {\n return [`localhost:${port}`, `127.0.0.1:${port}`, `[::1]:${port}`];\n}\n\nfunction noteNotFound(res: ServerResponse): void {\n res.writeHead(404, { \"content-type\": \"text/plain\" });\n res.end(\"No note with that id.\");\n}\n\n// --------------------------------------------------------------------------\n// Bridge server\n// --------------------------------------------------------------------------\n\nexport interface BridgeHandle {\n server: Server;\n port: number;\n url: string;\n /** The absolute path of the working file this bridge is serving. */\n workingPath: string;\n /** The page's latest state, for callers that drive the bridge in-process. */\n getEditorState: () => {\n divergent: boolean;\n content: unknown;\n annotations: Annotation[];\n };\n /** Re-read the working file and push it to every connected page. */\n reload: (options?: { consumeAnnotations?: boolean }) => ReloadResult;\n /** With the `fetch` option: the last data-source request's outcome. */\n lastFetch: () => FetchSummary | null;\n close: () => Promise<void>;\n}\n\nexport interface StartBridgeOptions {\n cwd?: string;\n port?: number;\n file?: string;\n harnessFile?: string;\n /** Custom-block mode: serve this definition's specimen instead of a template. */\n customBlock?: string;\n /** Custom-block mode only: a template the specimen is appended to. */\n host?: string;\n /** Environment the data-source recipe resolves `${env:…}` from. Defaults to process.env. */\n env?: Record<string, string | undefined>;\n /**\n * Custom-block mode only: run the `dataSourcePreview` recipe and add a\n * \"fetched\" state, filled from the real endpoint, to the specimen. `values`\n * override the field defaults for the request (the id it fetches by). It\n * runs before the bridge starts listening and again on every `POST\n * /reload`; the in-process `reload()` reuses the last result.\n */\n fetch?: { values: Record<string, unknown> };\n}\n\n/**\n * Start the bridge HTTP server. Pure server + in-memory sync state; callers own\n * process lifecycle. Resolves once listening.\n *\n * The returned handle exposes `getEditorState` and `reload` directly, so an\n * in-process caller (the MCP server) never has to make an HTTP request to its\n * own bridge — that is the whole reason live mode can work inside a sandboxed\n * agent. The equivalent HTTP endpoints stay for the skill's out-of-process CLI.\n */\nexport function startBridge({\n cwd = process.cwd(),\n port = 0,\n file = join(WORKING_DIR, \"template.json\"),\n harnessFile = HARNESS_FILE,\n customBlock,\n host,\n env = process.env,\n fetch: fetchOption,\n}: StartBridgeOptions = {}): Promise<BridgeHandle> {\n const abs = (p: string) => (isAbsolute(p) ? p : resolve(cwd, p));\n const customBlockPath = customBlock ? abs(customBlock) : null;\n const hostPath = host ? abs(host) : null;\n const workingPath = customBlockPath ?? abs(file);\n\n // Sync state. `baseline` is the editor's NORMALIZED view of the caller's last\n // content (captured by the page right after it applies an update), so the\n // editor's own load-time normalization never reads as a user edit.\n // `editorCurrent` is the page's latest getContent(); `divergent` is true when\n // it structurally differs from `baseline` — i.e. the user hand-edited.\n const state: {\n baseline: unknown;\n editorCurrent: unknown;\n divergent: boolean;\n annotations: Annotation[];\n } = {\n baseline: null,\n editorCurrent: null,\n divergent: false,\n annotations: [],\n };\n let nextAnnotationNumber = 1;\n function mintAnnotationId(): string {\n const n = nextAnnotationNumber++;\n return `a${n}-${Date.now().toString(36)}`;\n }\n const clients = new Set<ServerResponse>();\n\n function broadcastTemplate(content: unknown): void {\n const payload = `event: template\\ndata: ${JSON.stringify(content)}\\n\\n`;\n for (const res of clients) res.write(payload);\n }\n\n /** Why the bridge won't run this definition's recipe, or null when it will. */\n function recipeRefusal(def: CustomBlockWorkingFile): string | null {\n if (!def.dataSourcePreview) return \"This block has no dataSourcePreview.\";\n const errors = checkRecipe(def).filter((i) => i.severity === \"error\");\n return errors.length > 0\n ? `The dataSourcePreview recipe is refused: ${errors\n .map((i) => `${i.ruleId}: ${i.message}`)\n .join(\"; \")}`\n : null;\n }\n\n // The fetched state's last outcome, null until the first run.\n let fetched: (FetchedSpecimen & { unmapped?: string[] }) | null = null;\n\n async function refreshFetched(): Promise<void> {\n const data = readWorkingFile(customBlockPath as string);\n if (data === null || !validateCustomBlockDefinition(data).valid) {\n fetched = {\n ok: false,\n error: \"The custom block definition is missing or invalid.\",\n };\n return;\n }\n const def = data as CustomBlockWorkingFile;\n const recipe = def.dataSourcePreview;\n const refusal = recipeRefusal(def);\n if (!recipe || refusal !== null) {\n fetched = { ok: false, error: refusal ?? \"\" };\n return;\n }\n const values = {\n ...buildSpecimen(def)[0].fieldValues,\n ...fetchOption?.values,\n };\n const result = await runRecipe(recipe, values, { env });\n fetched = result.ok\n ? {\n ok: true,\n fieldValues: { ...values, ...result.values },\n unmapped: result.unmapped,\n }\n : { ok: false, error: result.error };\n }\n\n function lastFetch(): FetchSummary | null {\n if (!fetched) return null;\n return fetched.ok\n ? { ok: true, unmapped: fetched.unmapped ?? [] }\n : { ok: false, error: fetched.error };\n }\n\n type BlockView =\n | {\n ok: true;\n def: CustomBlockWorkingFile;\n payload: unknown;\n template: TemplateContent;\n }\n | { ok: false; error: string };\n\n // Read fresh on every request: the agent edits the file between reloads,\n // and the page must never be handed a definition that failed validation.\n function readBlockView(): BlockView {\n const data = readWorkingFile(customBlockPath as string);\n if (data === null || !validateCustomBlockDefinition(data).valid) {\n return {\n ok: false,\n error:\n \"The custom block definition is missing or invalid. Run `templatical custom-block validate` on it.\",\n };\n }\n let hostContent: TemplateContent | undefined;\n if (hostPath) {\n const h = readWorkingFile(hostPath);\n if (h === null || !validateTemplate(h).valid) {\n return {\n ok: false,\n error:\n \"The --host template is missing or invalid. Run `templatical validate` on it.\",\n };\n }\n hostContent = h as TemplateContent;\n }\n const def = data as CustomBlockWorkingFile;\n const { dataSourcePreview, ...definition } = def;\n // The fetched state leads the specimen: it is the realistic one.\n const base = hostContent ?? createDefaultTemplateContent();\n const lead =\n fetchOption && fetched ? fetchedSpecimenBlocks(def, fetched) : [];\n return {\n ok: true,\n def,\n payload: {\n definition,\n dataSource: dataSourcePreview\n ? { label: dataSourcePreview.label }\n : null,\n },\n template: buildSpecimenTemplate(def, {\n ...base,\n blocks: [...base.blocks, ...lead],\n }),\n };\n }\n\n function sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(body));\n }\n\n function getEditorState(): {\n divergent: boolean;\n content: unknown;\n annotations: Annotation[];\n } {\n return {\n divergent: state.divergent,\n content: state.editorCurrent,\n annotations: state.annotations,\n };\n }\n\n function reload(options?: { consumeAnnotations?: boolean }): ReloadResult {\n // A failed read pushes nothing and leaves the page's state alone: the\n // page still shows what it showed, so its divergence and notes still hold.\n if (customBlockPath) {\n const view = readBlockView();\n if (!view.ok) {\n return {\n ok: false,\n clients: clients.size,\n consumed: false,\n mode: \"custom-block\",\n error: view.error,\n };\n }\n state.baseline = null;\n state.editorCurrent = null;\n state.divergent = false;\n const consumed = options?.consumeAnnotations === true;\n if (consumed) state.annotations = [];\n const payload = `event: custom-block\\ndata: ${JSON.stringify({ block: view.payload, template: view.template })}\\n\\n`;\n for (const res of clients) res.write(payload);\n const fetch = fetchOption ? lastFetch() : null;\n return {\n ok: true,\n clients: clients.size,\n consumed,\n mode: \"custom-block\",\n ...(fetch ? { fetch } : {}),\n };\n }\n\n // The freshly-written file is the new baseline, so any pending user edit is\n // superseded. Notes stay: a plain reload is an ordinary edit, and clearing\n // them here would drop a queue the agent has not applied. consumeAnnotations\n // clears only after the file was actually read — clearing first would drop\n // the notes and push nothing when the file is missing.\n const content = readWorkingFile(workingPath);\n if (content === null) {\n return {\n ok: false,\n clients: clients.size,\n consumed: false,\n mode: \"template\",\n error: `${workingPath} is missing or isn't valid JSON. Run \\`templatical validate\\` on it.`,\n };\n }\n state.baseline = null;\n state.editorCurrent = null;\n state.divergent = false;\n const consumed = options?.consumeAnnotations === true;\n if (consumed) state.annotations = [];\n broadcastTemplate(content);\n return { ok: true, clients: clients.size, consumed, mode: \"template\" };\n }\n\n const server = createServer(async (req, res) => {\n const { pathname } = new URL(req.url ?? \"/\", \"http://localhost\");\n const method = req.method ?? \"GET\";\n\n try {\n // Only this listener's own loopback names are served: a DNS-rebound\n // hostname would otherwise let any web page read the bridge as same-origin.\n const addr = server.address();\n const listening =\n typeof addr === \"object\" && addr !== null ? addr.port : port;\n const hostHeader = req.headers.host ?? \"\";\n if (!loopbackNames(listening).some((n) => n === hostHeader)) {\n res\n .writeHead(403, { \"content-type\": \"text/plain\" })\n .end(\"Forbidden host.\");\n return;\n }\n\n // Writes. The Host check above doesn't stop a page on another site from\n // sending a simple cross-origin POST to localhost (text/plain, no\n // preflight): its response is unreadable, but the write still lands, so\n // a note it posts would reach the agent as the user's own. A browser\n // attaches its Origin to every such request, so a foreign one is\n // refused, and a POST must be JSON, which no simple request can be. PUT\n // and DELETE need a preflight cross-site, which the bridge never grants.\n if (method !== \"GET\" && method !== \"HEAD\") {\n const origin = req.headers.origin;\n if (\n origin !== undefined &&\n !loopbackNames(listening).some((n) => origin === `http://${n}`)\n ) {\n sendJson(res, 403, { error: \"Forbidden origin.\" });\n return;\n }\n const type = (req.headers[\"content-type\"] ?? \"\").toLowerCase();\n if (method === \"POST\" && !type.startsWith(\"application/json\")) {\n sendJson(res, 415, { error: \"Send application/json.\" });\n return;\n }\n }\n\n if (\n method === \"GET\" &&\n (pathname === \"/\" || pathname === \"/index.html\")\n ) {\n const html = readFileSync(harnessFile, \"utf8\").replaceAll(\n \"{{EDITOR_VERSION}}\",\n EDITOR_VERSION,\n );\n res.writeHead(200, { \"content-type\": \"text/html; charset=utf-8\" });\n res.end(html);\n return;\n }\n\n if (method === \"GET\" && pathname === \"/custom-block\") {\n if (!customBlockPath) {\n res.writeHead(204).end();\n return;\n }\n const view = readBlockView();\n if (view.ok) sendJson(res, 200, view.payload);\n else sendJson(res, 422, { error: view.error });\n return;\n }\n\n if (method === \"POST\" && pathname === \"/data-source/fetch\") {\n if (!customBlockPath) {\n res.writeHead(404, { \"content-type\": \"text/plain\" }).end(\"Not found\");\n return;\n }\n const view = readBlockView();\n if (!view.ok) {\n sendJson(res, 422, { error: view.error });\n return;\n }\n // The recipe gate runs before the page's request is even read: a\n // recipe `custom-block validate` rejects is never sent anywhere.\n const recipe = view.def.dataSourcePreview;\n const refusal = recipeRefusal(view.def);\n if (!recipe || refusal !== null) {\n sendJson(res, recipe ? 422 : 409, { error: refusal });\n return;\n }\n // Only fieldValues is read: the recipe (URL, headers) never comes from the page.\n const body = await readJsonBody(req);\n const fieldValues =\n body?.fieldValues &&\n typeof body.fieldValues === \"object\" &&\n !Array.isArray(body.fieldValues)\n ? (body.fieldValues as Record<string, unknown>)\n : {};\n const result = await runRecipe(recipe, fieldValues, { env });\n if (result.ok) {\n sendJson(res, 200, {\n values: result.values,\n unmapped: result.unmapped,\n });\n } else {\n sendJson(res, 502, { error: result.error });\n }\n return;\n }\n\n if (method === \"GET\" && pathname === \"/template\") {\n if (customBlockPath) {\n const view = readBlockView();\n if (view.ok) sendJson(res, 200, view.template);\n else sendJson(res, 422, { error: view.error });\n return;\n }\n const content = readWorkingFile(workingPath);\n if (content === null) {\n res.writeHead(204).end(); // no working file yet — page inits empty\n return;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(content));\n return;\n }\n\n if (method === \"GET\" && pathname === \"/events\") {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n });\n res.write(\"event: ready\\ndata: {}\\n\\n\");\n clients.add(res);\n const ping = setInterval(() => res.write(\": ping\\n\\n\"), 15000);\n req.on(\"close\", () => {\n clearInterval(ping);\n clients.delete(res);\n });\n return;\n }\n\n if (method === \"POST\" && pathname === \"/content\") {\n const body = await readJsonBody(req);\n const content = body?.content;\n if (body?.baseline) {\n // Post-apply snapshot: this is the editor's normalized view of the\n // caller's content, not a user edit.\n state.baseline = content ?? null;\n state.editorCurrent = content ?? null;\n state.divergent = false;\n } else {\n state.editorCurrent = content ?? null;\n state.divergent =\n state.baseline !== null && !deepEqual(content, state.baseline);\n }\n res.writeHead(204).end();\n return;\n }\n\n if (method === \"GET\" && pathname === \"/content\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(getEditorState()));\n return;\n }\n\n if (method === \"POST\" && pathname === \"/annotations\") {\n const body = await readJsonBody(req);\n const parsed = readNoteText(body?.text);\n if (\"error\" in parsed) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(parsed.error);\n return;\n }\n if (state.annotations.length >= NOTE_QUEUE_MAX) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(\"The note queue is full (40).\");\n return;\n }\n const blockId = readOptionalId(body?.blockId);\n let parentBlockId = readOptionalId(body?.parentBlockId);\n if (parentBlockId === blockId) parentBlockId = null;\n const annotation: Annotation = {\n id: mintAnnotationId(),\n blockId,\n parentBlockId,\n blockType: readBlockType(body?.blockType),\n label: readLabel(body?.label),\n text: parsed.text,\n createdAt: Date.now(),\n };\n state.annotations.push(annotation);\n res.writeHead(201, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(annotation));\n return;\n }\n\n const noteId = annotationIdFromPath(pathname);\n if (noteId && (method === \"PUT\" || method === \"DELETE\")) {\n const index = state.annotations.findIndex((note) => note.id === noteId);\n if (index < 0) {\n noteNotFound(res);\n return;\n }\n if (method === \"DELETE\") {\n state.annotations.splice(index, 1);\n res.writeHead(204).end();\n return;\n }\n const body = await readJsonBody(req);\n const parsed = readNoteText(body?.text);\n if (\"error\" in parsed) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(parsed.error);\n return;\n }\n const updated: Annotation = {\n ...state.annotations[index],\n text: parsed.text,\n };\n state.annotations[index] = updated;\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(updated));\n return;\n }\n\n if (method === \"POST\" && pathname === \"/reload\") {\n const body = await readJsonBody(req);\n if (fetchOption && customBlockPath) await refreshFetched();\n const result = reload({\n consumeAnnotations: body?.consumeAnnotations === true,\n });\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(result));\n return;\n }\n\n res.writeHead(404, { \"content-type\": \"text/plain\" }).end(\"Not found\");\n } catch (err) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(`Bad request: ${(err as Error).message}`);\n }\n });\n\n // The first fetch lands before the page can load, so it never shows a\n // sheet without the fetched state.\n const ready =\n fetchOption && customBlockPath ? refreshFetched() : Promise.resolve();\n\n return ready.then(\n () =>\n new Promise<BridgeHandle>((resolvePromise, rejectPromise) => {\n // listen() reports failures (e.g. EADDRINUSE) as an 'error' event, not a\n // throw — without this the error would be unhandled and crash the process.\n const onListenError = (err: Error) => rejectPromise(err);\n server.once(\"error\", onListenError);\n server.listen(port, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onListenError);\n const address = server.address();\n const actualPort =\n typeof address === \"object\" && address !== null\n ? address.port\n : port;\n resolvePromise({\n server,\n port: actualPort,\n url: `http://localhost:${actualPort}/`,\n workingPath,\n getEditorState,\n reload,\n lastFetch,\n close: () =>\n new Promise<void>((r) => {\n for (const c of clients) c.end();\n clients.clear();\n server.close(() => r());\n }),\n });\n });\n }),\n );\n}\n\nexport interface PreferringHandle extends BridgeHandle {\n fellBack: boolean;\n preferredPort?: number;\n}\n\n/**\n * Start the bridge on `preferredPort`, falling back to an OS-assigned free port\n * when that one is occupied — so a busy port never fails the launch. The page\n * uses relative URLs, so the actual port is discovered, not assumed. The\n * returned handle carries `fellBack: true` when it landed on a different port.\n */\nexport async function startBridgePreferring({\n preferredPort = DEFAULT_PORT,\n ...opts\n}: StartBridgeOptions & {\n preferredPort?: number;\n} = {}): Promise<PreferringHandle> {\n try {\n const handle = await startBridge({ ...opts, port: preferredPort });\n return { ...handle, fellBack: false };\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== \"EADDRINUSE\") throw err;\n const handle = await startBridge({ ...opts, port: 0 });\n return { ...handle, fellBack: true, preferredPort };\n }\n}\n"],"mappings":";;;;;;;;AAuCA,MAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;AASnD,MAAa,iBAAiB;AAE9B,MAAa,eAAe;AAC5B,MAAa,cAAc;AAC3B,MAAa,WAAW,KAAK,aAAa,iBAAiB;AAK3D,MAAM,eAAe,QAAQ,MAAM,uBAAuB;;AAO1D,SAAgB,UAAU,GAAY,GAAqB;CACzD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,MAAM,QAAQ,MAAM,MAAM,OAAO;CACrC,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU,OAAO;CAC3D,MAAM,OAAO,MAAM,QAAQ,CAAC;CAC5B,IAAI,SAAS,MAAM,QAAQ,CAAC,GAAG,OAAO;CACtC,IAAI,MAAM;EACR,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,IAAI,MAAM,WAAW,MAAM,QAAQ,OAAO;EAC1C,KAAK,IAAI,IAAI,GA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I;KAC/B,QAAQ,MAAM;KACd,OAAO,YAAY,EAAE,CAAC;IACxB,CAAC;GACL,CAAC;EACH,CAAC;CACH,CAAC,CACL;AACF;;;;;;;AAaA,eAAsB,sBAAsB,EAC1C,gBAAgB,cAChB,GAAG,SAGD,CAAC,GAA8B;CACjC,IAAI;EAEF,OAAO;GAAE,GAAG,MADS,YAAY;IAAE,GAAG;IAAM,MAAM;GAAc,CAAC;GAC7C,UAAU;EAAM;CACtC,SAAS,KAAK;EACZ,IAAK,KAA+B,SAAS,cAAc,MAAM;EAEjE,OAAO;GAAE,GAAG,MADS,YAAY;IAAE,GAAG;IAAM,MAAM;GAAE,CAAC;GACjC,UAAU;GAAM;EAAc;CACpD;AACF"}
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@templatical/template-tools",
3
3
  "description": "CLI and library for Templatical email templates — validate, render, edit, import, and live-preview",
4
- "version": "0.50.0",
4
+ "version": "0.51.1",
5
5
  "bin": {
6
6
  "templatical": "./dist/bin.js"
7
7
  },
8
8
  "bugs": "https://github.com/templatical/sdk/issues",
9
9
  "dependencies": {
10
- "@templatical/quality": "0.50.0",
11
- "@templatical/renderer": "0.50.0",
12
- "@templatical/types": "0.50.0",
10
+ "@templatical/quality": "0.51.1",
11
+ "@templatical/renderer": "0.51.1",
12
+ "@templatical/types": "0.51.1",
13
13
  "ajv": "^8.20.0",
14
14
  "htmlparser2": "^12.0.0",
15
15
  "liquidjs": "^10.30.0"
@@ -52,14 +52,14 @@
52
52
  "license": "MIT",
53
53
  "module": "./dist/index.js",
54
54
  "peerDependencies": {
55
- "@templatical/import-beefree": "0.50.0",
56
- "@templatical/import-chamaileon": "0.50.0",
57
- "@templatical/import-easy-email-pro": "0.50.0",
58
- "@templatical/import-html": "0.50.0",
59
- "@templatical/import-mjml": "0.50.0",
60
- "@templatical/import-stripo": "0.50.0",
61
- "@templatical/import-topol": "0.50.0",
62
- "@templatical/import-unlayer": "0.50.0",
55
+ "@templatical/import-beefree": "0.51.1",
56
+ "@templatical/import-chamaileon": "0.51.1",
57
+ "@templatical/import-easy-email-pro": "0.51.1",
58
+ "@templatical/import-html": "0.51.1",
59
+ "@templatical/import-mjml": "0.51.1",
60
+ "@templatical/import-stripo": "0.51.1",
61
+ "@templatical/import-topol": "0.51.1",
62
+ "@templatical/import-unlayer": "0.51.1",
63
63
  "mjml": "^5.4.1"
64
64
  },
65
65
  "peerDependenciesMeta": {