@getartisanflow/alpineflow 0.2.3-alpha → 0.2.4-alpha

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 +1 @@
1
- {"version":3,"file":"alpineflow-schema.esm.js","sources":["../src/core/registry.ts","../src/schema/cascade.ts","../src/schema/field-ops.ts","../src/schema/references.ts","../src/core/deep-merge.ts","../src/schema/serialization.ts","../src/schema/validate.ts","../src/schema/diff.ts","../src/schema/dot.ts","../src/schema/layout.ts","../src/schema/history.ts","../src/schema/inspector/shared.ts","../src/schema/inspector/node-inspector.ts","../src/schema/inspector/row-inspector.ts","../src/schema/inspector/edge-inspector.ts","../src/schema/reorderable.ts","../src/schema/keyboard-nav.ts","../src/schema/index.ts"],"sourcesContent":["/**\n * Addon registry — singleton via window global.\n *\n * When AlpineFlow core is loaded from one bundle (e.g., WireFlow's\n * alpineflow.bundle.esm.js) and addons are loaded from separate ESM\n * files, each bundle gets its own module scope. A module-scoped Map\n * would create disconnected registries — addons would register on\n * their copy, but the core would check its own empty copy.\n *\n * Using a window global ensures all bundles share one registry,\n * regardless of how they're loaded (CDN, npm, Vite, WireFlow bundle).\n */\n\nconst REGISTRY_KEY = '__alpineflow_registry__';\n\nexport function getRegistry(): Map<string, any> {\n if (typeof globalThis !== 'undefined') {\n if (!(globalThis as any)[REGISTRY_KEY]) {\n (globalThis as any)[REGISTRY_KEY] = new Map<string, any>();\n }\n return (globalThis as any)[REGISTRY_KEY];\n }\n // Fallback for environments without globalThis (shouldn't happen in modern runtimes)\n return new Map<string, any>();\n}\n\nexport function registerAddon(name: string, value: any): void {\n getRegistry().set(name, value);\n}\n\nexport function getAddon<T = any>(name: string): T | undefined {\n return getRegistry().get(name);\n}\n\n/** Remove a single addon by name. */\nexport function unregisterAddon(name: string): void {\n getRegistry().delete(name);\n}\n\n/** Test-only: clear all registered addons. */\nexport function _resetRegistry(): void {\n getRegistry().clear();\n}\n","// ============================================================================\n// alpineflow/schema — Edge cascade walker (internal helper)\n//\n// Pure functions that return NEW arrays. They do not mutate canvas state —\n// `field-ops.ts` is the only module that touches the live reactive arrays.\n// ============================================================================\n\nexport interface CascadeRenameResult<E> {\n edges: E[];\n cascadedIds: string[];\n}\n\nexport interface CascadeRemoveResult<E> {\n edges: E[];\n droppedIds: string[];\n}\n\ntype EdgeLike = {\n id: string;\n source: string;\n sourceHandle?: string | null;\n target: string;\n targetHandle?: string | null;\n};\n\n/**\n * Returns a new edge array where any edge touching (nodeId, oldName) has its\n * matching handle rewritten to newName. cascadedIds lists the edges that changed.\n */\nexport function cascadeEdgesOnRename<E extends EdgeLike>(\n edges: E[],\n nodeId: string,\n oldName: string,\n newName: string,\n): CascadeRenameResult<E> {\n const cascadedIds: string[] = [];\n const updated = edges.map((e) => {\n let next: E = e;\n if (e.source === nodeId && e.sourceHandle === oldName) {\n next = { ...next, sourceHandle: newName };\n }\n if (e.target === nodeId && e.targetHandle === oldName) {\n next = { ...next, targetHandle: newName };\n }\n if (next !== e) {\n cascadedIds.push(e.id);\n }\n return next;\n });\n return { edges: updated, cascadedIds };\n}\n\n/**\n * Returns a new edge array with every edge touching (nodeId, fieldName) removed.\n * droppedIds lists the edges that were filtered out.\n */\nexport function cascadeEdgesOnRemove<E extends EdgeLike>(\n edges: E[],\n nodeId: string,\n fieldName: string,\n): CascadeRemoveResult<E> {\n const droppedIds: string[] = [];\n const kept = edges.filter((e) => {\n const touches =\n (e.source === nodeId && e.sourceHandle === fieldName) ||\n (e.target === nodeId && e.targetHandle === fieldName);\n if (touches) {\n droppedIds.push(e.id);\n }\n return !touches;\n });\n return { edges: kept, droppedIds };\n}\n","// ============================================================================\n// alpineflow/schema — Field CRUD helpers\n//\n// Each helper mutates the live `canvas.nodes` / `canvas.edges` arrays through\n// their Alpine reactive proxies — render updates propagate automatically.\n// Helpers return a status object ({applied, reason, ...}) and dispatch\n// schema:* DOM events on `canvas.el` so consumers can listen without having\n// to wrap the calls.\n//\n// Validation failures (invalid name, duplicate, non-existent node/field, etc.)\n// fail silently by returning {applied: false, reason: ...} — no throws.\n// ============================================================================\n\nimport type { FlowSchemaField } from '../core/types';\nimport { cascadeEdgesOnRename, cascadeEdgesOnRemove } from './cascade';\n\n/** `snake_case` identifier: starts lowercase, letters/digits/underscores only. */\nconst FIELD_NAME_RE = /^[a-z][a-z0-9_]*$/;\nconst MAX_FIELD_NAME_LENGTH = 40;\n\nfunction isValidFieldName(name: string): boolean {\n return typeof name === 'string' && name.length <= MAX_FIELD_NAME_LENGTH && FIELD_NAME_RE.test(name);\n}\n\nfunction dispatchSchema(canvas: any, type: string, detail: Record<string, any>): void {\n const el: EventTarget | undefined = canvas?.el ?? canvas?._container;\n if (!el || typeof (el as any).dispatchEvent !== 'function') {\n return;\n }\n // Listener atomicity: a throwing listener must not abort this function\n // mid-mutation. State has already been updated; we intentionally do NOT\n // roll back, because a partial rollback would leave a different half-state.\n //\n // Per DOM spec, most environments catch listener exceptions inside\n // dispatchEvent and surface them via `window.onerror` (or ErrorEvent). We\n // install a one-shot capturing error listener so we see the throw, log it,\n // and prevent it from bubbling to a noisy default handler. We also wrap\n // dispatchEvent itself in try/catch for engines that propagate directly.\n const captured: unknown[] = [];\n const win: any = typeof window !== 'undefined' ? window : undefined;\n const onError = (event: ErrorEvent) => {\n captured.push(event.error ?? event.message);\n event.preventDefault();\n };\n if (win && typeof win.addEventListener === 'function') {\n win.addEventListener('error', onError, true);\n }\n try {\n el.dispatchEvent(new CustomEvent(type, { detail, bubbles: true }));\n } catch (err) {\n captured.push(err);\n } finally {\n if (win && typeof win.removeEventListener === 'function') {\n win.removeEventListener('error', onError, true);\n }\n }\n for (const err of captured) {\n console.error('[alpineflow/schema] listener threw while handling', type, err);\n }\n}\n\nfunction findNode(canvas: any, nodeId: string): any | null {\n return canvas?.nodes?.find((n: any) => n.id === nodeId) ?? null;\n}\n\nexport interface AddFieldResult {\n applied: boolean;\n reason?: string;\n}\n\nexport interface RenameFieldOpResult {\n applied: boolean;\n reason?: string;\n cascadedEdgeIds: string[];\n}\n\nexport interface RemoveFieldOpResult {\n applied: boolean;\n reason?: string;\n droppedEdgeIds: string[];\n}\n\nexport interface ReorderFieldsOpResult {\n applied: boolean;\n reason?: string;\n}\n\n/**\n * Append a new field to node.data.fields. Rejects invalid names, duplicates,\n * and missing nodes silently. Dispatches `schema:field-added` on success.\n */\nexport function addField(canvas: any, nodeId: string, field: FlowSchemaField & { [k: string]: any }): AddFieldResult {\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node' };\n }\n if (!isValidFieldName(field?.name)) {\n return { applied: false, reason: 'invalid-name' };\n }\n if (!node.data) {\n node.data = { label: nodeId, fields: [] };\n }\n const fields = node.data.fields ?? [];\n if (fields.some((f: any) => f.name === field.name)) {\n return { applied: false, reason: 'duplicate' };\n }\n\n // Push into the live reactive array so Alpine re-renders the node.\n if (!Array.isArray(node.data.fields)) {\n node.data.fields = [];\n }\n node.data.fields.push({ ...field });\n\n dispatchSchema(canvas, 'schema:field-added', { nodeId, field: { ...field } });\n return { applied: true };\n}\n\n/**\n * Rename a field. Cascades rewriting to every edge whose (source, sourceHandle)\n * or (target, targetHandle) touches (nodeId, oldName). Dispatches\n * `schema:field-renamed` and (if any edges changed) `schema:edges-cascaded`.\n */\nexport function renameField(canvas: any, nodeId: string, oldName: string, newName: string): RenameFieldOpResult {\n if (oldName === newName) {\n return { applied: false, reason: 'unchanged', cascadedEdgeIds: [] };\n }\n if (!isValidFieldName(newName)) {\n return { applied: false, reason: 'invalid-name', cascadedEdgeIds: [] };\n }\n\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node', cascadedEdgeIds: [] };\n }\n const fields: any[] = node.data?.fields ?? [];\n const target = fields.find((f: any) => f.name === oldName);\n if (!target) {\n return { applied: false, reason: 'no-field', cascadedEdgeIds: [] };\n }\n if (fields.some((f: any) => f.name === newName)) {\n return { applied: false, reason: 'duplicate', cascadedEdgeIds: [] };\n }\n\n // Rename in place — mutating the reactive object keeps any bindings alive.\n target.name = newName;\n\n // Cascade: mutate the affected edge objects IN PLACE so their live Alpine\n // scopes stay attached. cascadeEdgesOnRename returns NEW objects for\n // cascaded edges; splicing those into the array would orphan every cascaded\n // edge's scope and touch every reactive index. Copy just the changed handles\n // onto the existing objects instead.\n const currentEdges = canvas.edges ?? [];\n const { edges: updatedEdges, cascadedIds } = cascadeEdgesOnRename(currentEdges, nodeId, oldName, newName);\n if (cascadedIds.length > 0) {\n const updatedById = new Map(updatedEdges.map((e: any) => [e.id, e]));\n for (const edge of canvas.edges) {\n const upd = updatedById.get(edge.id);\n if (!upd || upd === edge) continue;\n if (edge.sourceHandle !== upd.sourceHandle) edge.sourceHandle = upd.sourceHandle;\n if (edge.targetHandle !== upd.targetHandle) edge.targetHandle = upd.targetHandle;\n }\n }\n\n dispatchSchema(canvas, 'schema:field-renamed', {\n nodeId,\n oldName,\n newName,\n cascadedEdgeIds: cascadedIds,\n });\n if (cascadedIds.length > 0) {\n dispatchSchema(canvas, 'schema:edges-cascaded', {\n nodeId,\n fieldName: newName,\n edgeIds: cascadedIds,\n operation: 'rename',\n });\n }\n\n return { applied: true, cascadedEdgeIds: cascadedIds };\n}\n\n/**\n * Remove a field from a node. Cascade-drops every edge whose handle references\n * it. Dispatches `schema:field-removed` and (if any edges dropped)\n * `schema:edges-cascaded`.\n */\nexport function removeField(canvas: any, nodeId: string, fieldName: string): RemoveFieldOpResult {\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node', droppedEdgeIds: [] };\n }\n const fields: any[] = node.data?.fields ?? [];\n const idx = fields.findIndex((f: any) => f.name === fieldName);\n if (idx === -1) {\n return { applied: false, reason: 'no-field', droppedEdgeIds: [] };\n }\n\n // Splice the reactive fields array in place.\n node.data.fields.splice(idx, 1);\n\n // Drop only the affected edges in place (rather than replacing the whole\n // array), and rebuild the edge map so getEdge no longer returns the dropped\n // edges — the previous full-array splice left _edgeMap stale.\n const currentEdges = canvas.edges ?? [];\n const { droppedIds } = cascadeEdgesOnRemove(currentEdges, nodeId, fieldName);\n if (droppedIds.length > 0) {\n const dropSet = new Set(droppedIds);\n for (let i = canvas.edges.length - 1; i >= 0; i--) {\n if (dropSet.has(canvas.edges[i].id)) canvas.edges.splice(i, 1);\n }\n canvas._rebuildEdgeMap?.();\n }\n\n dispatchSchema(canvas, 'schema:field-removed', {\n nodeId,\n fieldName,\n droppedEdgeIds: droppedIds,\n });\n if (droppedIds.length > 0) {\n dispatchSchema(canvas, 'schema:edges-cascaded', {\n nodeId,\n fieldName,\n edgeIds: droppedIds,\n operation: 'remove',\n });\n }\n\n return { applied: true, droppedEdgeIds: droppedIds };\n}\n\n/**\n * Reorder fields on a node to match the supplied name array. The array must\n * be a permutation of the existing field names — otherwise `mismatch`.\n */\nexport function reorderFields(canvas: any, nodeId: string, order: string[]): ReorderFieldsOpResult {\n if (!Array.isArray(order)) {\n return { applied: false, reason: 'mismatch' };\n }\n // Reject duplicate names in the supplied order explicitly — don't rely on\n // set-size comparison below, which fails open if node.data.fields somehow\n // already contains duplicates.\n if (new Set(order).size !== order.length) {\n return { applied: false, reason: 'mismatch' };\n }\n\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node' };\n }\n const fields: any[] = node.data?.fields ?? [];\n\n if (order.length !== fields.length) {\n return { applied: false, reason: 'mismatch' };\n }\n const existingNames = new Set(fields.map((f: any) => f.name));\n const orderNames = new Set(order);\n if (existingNames.size !== orderNames.size) {\n return { applied: false, reason: 'mismatch' };\n }\n for (const name of order) {\n if (!existingNames.has(name)) {\n return { applied: false, reason: 'mismatch' };\n }\n }\n\n const byName: Record<string, any> = Object.create(null);\n for (const f of fields) {\n byName[f.name] = f;\n }\n const reordered = order.map((name) => byName[name]);\n node.data.fields.splice(0, node.data.fields.length, ...reordered);\n\n return { applied: true };\n}\n","// ============================================================================\n// alpineflow/schema — Reference inference\n//\n// Pure helper: scans node field names for the `<stem>_id` pattern and, when\n// the stem exactly matches another node's id, emits a ReferenceSuggestion.\n// No canvas mutation, no events, no self-references. Consumers decide whether\n// to turn suggestions into real edges.\n// ============================================================================\n\nimport type { ReferenceSuggestion } from './types';\n\ninterface NodeLike {\n id: string;\n data?: {\n fields?: Array<{ name: string; key?: string }>;\n };\n}\n\n/**\n * Pattern-match `_id`-suffixed field names to node ids, yielding suggested\n * reference edges. Conservative: only emits when the stem is an exact node id\n * match. Consumers pick what to apply.\n */\nexport function inferReferences(nodes: NodeLike[]): ReferenceSuggestion[] {\n const byId = new Map<string, NodeLike>();\n for (const node of nodes) {\n byId.set(node.id, node);\n }\n\n const suggestions: ReferenceSuggestion[] = [];\n\n for (const node of nodes) {\n const fields = node.data?.fields ?? [];\n for (const field of fields) {\n if (typeof field?.name !== 'string') {\n continue;\n }\n if (!field.name.endsWith('_id')) {\n continue;\n }\n\n const stem = field.name.slice(0, -3);\n if (!stem) {\n continue;\n }\n\n const target = byId.get(stem);\n if (!target) {\n continue;\n }\n if (target.id === node.id) {\n continue; // no self-refs\n }\n\n const targetFields = target.data?.fields ?? [];\n const primary = targetFields.find((f) => f.key === 'primary');\n const toFieldName = primary?.name ?? targetFields[0]?.name ?? 'id';\n\n suggestions.push({\n fromNodeId: node.id,\n fromFieldName: field.name,\n toNodeId: target.id,\n toFieldName,\n confidence: 'exact',\n });\n }\n }\n\n return suggestions;\n}\n","/**\n * Deep-merge `source` into `target` in place.\n *\n * Rules:\n * - Objects are recursively merged (keys added/overwritten, unmentioned keys preserved).\n * - Arrays are replaced, not merged.\n * - `null` explicitly removes a key.\n * - `undefined` values are ignored (key is not touched).\n */\nexport function deepMerge<T extends Record<string, any>>(\n target: T,\n source: Record<string, any>,\n): T {\n for (const key of Object.keys(source)) {\n // Guard against prototype pollution\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n\n const val = source[key];\n\n // undefined → skip\n if (val === undefined) continue;\n\n // null → delete key\n if (val === null) {\n delete (target as any)[key];\n continue;\n }\n\n // Arrays → replace (not merge)\n if (Array.isArray(val)) {\n (target as any)[key] = [...val];\n continue;\n }\n\n // Plain objects → recurse\n if (typeof val === 'object' && val.constructor === Object) {\n if (\n typeof (target as any)[key] !== 'object' ||\n (target as any)[key] === null ||\n Array.isArray((target as any)[key])\n ) {\n (target as any)[key] = {};\n }\n deepMerge((target as any)[key], val);\n continue;\n }\n\n // Primitives → overwrite\n (target as any)[key] = val;\n }\n\n return target;\n}\n\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return a === b;\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Merge `incoming` entities into `existing` by id, PRESERVING the original\n * object references for ids present in both. Property writes are skipped when\n * deep-equal, so Alpine effects watching those objects only re-run for real\n * changes. Returns the merged list in `incoming` order.\n */\nexport function mergeEntitiesById<T extends { id: string }>(\n existing: T[],\n incoming: T[],\n opts: { deleteMissing?: boolean } = {},\n): T[] {\n const deleteMissing = opts.deleteMissing ?? true;\n const existingById = new Map(existing.map((e) => [e.id, e]));\n const merged: T[] = [];\n for (const inc of incoming) {\n const cur = existingById.get(inc.id);\n if (!cur) {\n merged.push(inc);\n continue;\n }\n if (deleteMissing) {\n for (const key of Object.keys(cur)) {\n if (key !== 'id' && !(key in inc)) delete (cur as Record<string, unknown>)[key];\n }\n }\n for (const [key, value] of Object.entries(inc)) {\n // Guard against prototype pollution (mirrors deepMerge): a bracket\n // assignment to `__proto__` would invoke the prototype setter.\n if (key === 'id' || key === '__proto__' || key === 'constructor' || key === 'prototype') {\n continue;\n }\n if (!jsonEqual((cur as Record<string, unknown>)[key], value)) {\n (cur as Record<string, unknown>)[key] = value;\n }\n }\n merged.push(cur);\n }\n return merged;\n}\n","import type { SchemaGraphJSON } from './types';\nimport { mergeEntitiesById } from '../core/deep-merge';\n\n/**\n * Export schema graph as a stable JSON shape. Strips internal underscore-prefixed\n * flags and only keeps the documented public fields.\n */\nexport function schemaToJSON(canvas: {\n nodes: Array<any>;\n edges: Array<any>;\n}): SchemaGraphJSON {\n const nodes = (canvas.nodes ?? []).map((n) => ({\n id: n.id,\n label: n.data?.label ?? '',\n fields: (n.data?.fields ?? []).map((f: any) => ({ ...f })),\n position: { x: n.position?.x ?? 0, y: n.position?.y ?? 0 },\n }));\n\n const edges = (canvas.edges ?? []).map((e) => {\n const edge: any = { id: e.id, source: e.source, target: e.target };\n if (e.sourceHandle !== undefined) {\n edge.sourceHandle = e.sourceHandle;\n }\n if (e.targetHandle !== undefined) {\n edge.targetHandle = e.targetHandle;\n }\n if (e.label !== undefined) {\n edge.label = e.label;\n }\n return edge;\n });\n\n return { version: 1, nodes, edges };\n}\n\n/**\n * Import a schema graph, MERGING it into the canvas's live nodes + edges arrays.\n *\n * Surviving ids keep their original object references (mutated to match the\n * imported schema), so `getNode`/`getEdge`, drag handlers, and edge effects all\n * stay bound to the live objects. `deleteMissing: false` because the schema JSON\n * is intentionally partial — non-schema props (`dimensions`, `type`, …) must\n * survive a round-trip. After merging, the node/edge lookup maps are rebuilt so\n * `getNode`/`getEdge` return the merged objects rather than orphaned ones.\n */\nexport function schemaFromJSON(\n canvas: {\n nodes: any[];\n edges: any[];\n _rebuildNodeMap?: () => void;\n _rebuildEdgeMap?: () => void;\n _layoutAnimTick?: number;\n },\n json: SchemaGraphJSON,\n): void {\n if (!json || typeof (json as any).version !== 'number') {\n throw new Error('[alpineflow/schema] schemaFromJSON: missing or invalid version');\n }\n if (json.version !== 1) {\n throw new Error(`[alpineflow/schema] schemaFromJSON: unsupported version ${json.version}`);\n }\n\n const incomingNodes = (json.nodes ?? []).map((n) => ({\n id: n.id,\n position: { x: n.position?.x ?? 0, y: n.position?.y ?? 0 },\n data: {\n label: n.label,\n fields: (n.fields ?? []).map((f) => ({ ...f })),\n },\n }));\n\n const incomingEdges = (json.edges ?? []).map((e) => {\n const edge: any = { id: e.id, source: e.source, target: e.target };\n if (e.sourceHandle !== undefined) {\n edge.sourceHandle = e.sourceHandle;\n }\n if (e.targetHandle !== undefined) {\n edge.targetHandle = e.targetHandle;\n }\n if (e.label !== undefined) {\n edge.label = e.label;\n }\n return edge;\n });\n\n const mergedNodes = mergeEntitiesById(canvas.nodes, incomingNodes, { deleteMissing: false });\n canvas.nodes.splice(0, canvas.nodes.length, ...mergedNodes);\n const mergedEdges = mergeEntitiesById(canvas.edges, incomingEdges, { deleteMissing: false });\n canvas.edges.splice(0, canvas.edges.length, ...mergedEdges);\n canvas._rebuildNodeMap?.();\n canvas._rebuildEdgeMap?.();\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => {\n canvas._layoutAnimTick = (canvas._layoutAnimTick ?? 0) + 1;\n });\n }\n}\n","// ============================================================================\n// alpineflow/schema — validateSchema\n//\n// Pure helper: inspects a canvas's nodes + edges and returns a structured list\n// of issues. No canvas mutation, no events, no throws. Safe on malformed input.\n//\n// Severities:\n// error — 'dangling-edge', 'duplicate-node-id', 'duplicate-field'\n// warning — 'missing-primary-key', 'disconnected-node', 'cycle'\n//\n// `valid` is true iff no error-severity issues are present.\n// ============================================================================\n\nimport type { SchemaValidationIssue, SchemaValidationResult } from './types';\n\ninterface NodeLike {\n id: string;\n data?: {\n fields?: Array<{ name: string; key?: string }>;\n };\n}\n\ninterface EdgeLike {\n id?: string;\n source: string;\n target: string;\n}\n\n/**\n * Iterative DFS cycle detection. Returns true as soon as any directed cycle is\n * found. Deterministic and terminating — handles self-loops, parallel edges,\n * and multi-component graphs without infinite loops.\n */\nfunction hasCycle(nodes: NodeLike[], edges: EdgeLike[]): boolean {\n // Self-loop shortcut\n for (const e of edges) {\n if (e && typeof e.source === 'string' && e.source === e.target) {\n return true;\n }\n }\n\n // Build adjacency list (outgoing only). Include nodes that only appear in\n // edges (tolerate dangling edges — they can still participate in a cycle\n // logically, but we just walk what we have).\n const adj = new Map<string, string[]>();\n const ensure = (id: string): string[] => {\n let list = adj.get(id);\n if (!list) {\n list = [];\n adj.set(id, list);\n }\n return list;\n };\n\n for (const n of nodes) {\n if (n && typeof n.id === 'string') {\n ensure(n.id);\n }\n }\n for (const e of edges) {\n if (!e || typeof e.source !== 'string' || typeof e.target !== 'string') continue;\n ensure(e.source).push(e.target);\n ensure(e.target); // ensure target is a known key\n }\n\n // Tri-color DFS: WHITE (unseen), GRAY (in current stack), BLACK (done).\n const WHITE = 0;\n const GRAY = 1;\n const BLACK = 2;\n const color = new Map<string, number>();\n for (const id of adj.keys()) {\n color.set(id, WHITE);\n }\n\n // Iterative DFS using a frame stack. Each frame tracks its iterator index\n // so we can emulate recursive post-order coloring without blowing the stack.\n for (const start of adj.keys()) {\n if (color.get(start) !== WHITE) continue;\n\n const stack: Array<{ node: string; idx: number }> = [{ node: start, idx: 0 }];\n color.set(start, GRAY);\n\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n const neighbors = adj.get(frame.node) ?? [];\n if (frame.idx < neighbors.length) {\n const next = neighbors[frame.idx++];\n const c = color.get(next);\n if (c === GRAY) {\n return true; // back-edge → cycle\n }\n if (c === WHITE) {\n color.set(next, GRAY);\n stack.push({ node: next, idx: 0 });\n }\n // BLACK → already fully explored, skip\n } else {\n color.set(frame.node, BLACK);\n stack.pop();\n }\n }\n }\n\n return false;\n}\n\n/**\n * Inspect a canvas (nodes + edges) and produce a structured list of schema\n * issues. Pure — no mutation, no events, never throws.\n */\nexport function validateSchema(canvas: { nodes?: any[]; edges?: any[] }): SchemaValidationResult {\n const issues: SchemaValidationIssue[] = [];\n const nodes: NodeLike[] = Array.isArray(canvas?.nodes) ? canvas!.nodes! : [];\n const edges: EdgeLike[] = Array.isArray(canvas?.edges) ? canvas!.edges! : [];\n\n // --- duplicate-node-id ----------------------------------------------------\n const nodeIds = new Set<string>();\n const dupNodeIds = new Set<string>();\n for (const n of nodes) {\n if (!n || typeof n.id !== 'string') continue;\n if (nodeIds.has(n.id)) {\n dupNodeIds.add(n.id);\n }\n nodeIds.add(n.id);\n }\n for (const id of dupNodeIds) {\n issues.push({\n severity: 'error',\n code: 'duplicate-node-id',\n nodeId: id,\n message: `Duplicate node id \"${id}\".`,\n });\n }\n\n // --- per-node: duplicate-field + missing-primary-key ---------------------\n for (const n of nodes) {\n if (!n || typeof n.id !== 'string') continue;\n const fields = Array.isArray(n.data?.fields) ? n.data!.fields! : [];\n if (fields.length === 0) continue;\n\n const seen = new Set<string>();\n const dup = new Set<string>();\n for (const f of fields) {\n if (!f || typeof f.name !== 'string') continue;\n if (seen.has(f.name)) {\n dup.add(f.name);\n }\n seen.add(f.name);\n }\n for (const name of dup) {\n issues.push({\n severity: 'error',\n code: 'duplicate-field',\n nodeId: n.id,\n fieldName: name,\n message: `Duplicate field \"${name}\" on node \"${n.id}\".`,\n });\n }\n\n const hasPrimary = fields.some((f) => f && f.key === 'primary');\n if (!hasPrimary) {\n issues.push({\n severity: 'warning',\n code: 'missing-primary-key',\n nodeId: n.id,\n message: `Node \"${n.id}\" has no primary-key field.`,\n });\n }\n }\n\n // --- dangling-edge -------------------------------------------------------\n for (const e of edges) {\n if (!e) continue;\n const edgeId = typeof e.id === 'string' ? e.id : undefined;\n if (typeof e.source !== 'string' || !nodeIds.has(e.source)) {\n issues.push({\n severity: 'error',\n code: 'dangling-edge',\n edgeId,\n nodeId: typeof e.source === 'string' ? e.source : undefined,\n message: `Edge ${edgeId ? `\"${edgeId}\" ` : ''}references missing source node \"${e.source}\".`,\n });\n }\n if (typeof e.target !== 'string' || !nodeIds.has(e.target)) {\n issues.push({\n severity: 'error',\n code: 'dangling-edge',\n edgeId,\n nodeId: typeof e.target === 'string' ? e.target : undefined,\n message: `Edge ${edgeId ? `\"${edgeId}\" ` : ''}references missing target node \"${e.target}\".`,\n });\n }\n }\n\n // --- disconnected-node ---------------------------------------------------\n const touched = new Set<string>();\n for (const e of edges) {\n if (!e) continue;\n if (typeof e.source === 'string') touched.add(e.source);\n if (typeof e.target === 'string') touched.add(e.target);\n }\n for (const n of nodes) {\n if (!n || typeof n.id !== 'string') continue;\n if (!touched.has(n.id)) {\n issues.push({\n severity: 'warning',\n code: 'disconnected-node',\n nodeId: n.id,\n message: `Node \"${n.id}\" has no connected edges.`,\n });\n }\n }\n\n // --- cycle (emit once) ---------------------------------------------------\n if (hasCycle(nodes, edges)) {\n issues.push({\n severity: 'warning',\n code: 'cycle',\n message: 'Directed cycle detected in edge graph.',\n });\n }\n\n const valid = !issues.some((i) => i.severity === 'error');\n return { valid, issues };\n}\n","// ============================================================================\n// alpineflow/schema — diffSchemas\n//\n// Pure helper: computes a structured delta between two `SchemaGraphJSON`\n// snapshots. No canvas coupling, no mutation, never throws on malformed input.\n//\n// Useful for migration generation, PR-review diffs, and undo/redo inspection.\n//\n// All output arrays are deterministically ordered for stability.\n// ============================================================================\n\nimport type { FlowSchemaField } from '../core/types';\nimport type { DiffOptions, SchemaDiff, SchemaGraphJSON } from './types';\n\ninterface NodeShape {\n id: string;\n label: string;\n fields: FlowSchemaField[];\n position: { x: number; y: number };\n}\n\ninterface EdgeShape {\n id: string;\n source: string;\n target: string;\n sourceHandle?: string;\n targetHandle?: string;\n label?: string;\n}\n\nfunction safeNodes(snap: Partial<SchemaGraphJSON> | null | undefined): NodeShape[] {\n if (!snap || !Array.isArray(snap.nodes)) return [];\n return snap.nodes.filter((n): n is NodeShape => !!n && typeof n.id === 'string');\n}\n\nfunction safeEdges(snap: Partial<SchemaGraphJSON> | null | undefined): EdgeShape[] {\n if (!snap || !Array.isArray(snap.edges)) return [];\n return snap.edges.filter((e): e is EdgeShape => !!e && typeof e.id === 'string');\n}\n\nfunction fieldsByName(node: NodeShape): Map<string, FlowSchemaField> {\n const map = new Map<string, FlowSchemaField>();\n const fields = Array.isArray(node.fields) ? node.fields : [];\n for (const f of fields) {\n if (f && typeof f.name === 'string') {\n map.set(f.name, f);\n }\n }\n return map;\n}\n\n/**\n * Compute a structured delta between two schema snapshots. Pure, deterministic,\n * tolerant of malformed input (missing `version`, null snapshots, nodes without\n * fields, etc.).\n */\nexport function diffSchemas(\n before: SchemaGraphJSON,\n after: SchemaGraphJSON,\n opts: DiffOptions = {},\n): SchemaDiff {\n const beforeNodes = safeNodes(before);\n const afterNodes = safeNodes(after);\n const beforeEdges = safeEdges(before);\n const afterEdges = safeEdges(after);\n\n const beforeNodeMap = new Map<string, NodeShape>();\n for (const n of beforeNodes) {\n beforeNodeMap.set(n.id, n);\n }\n const afterNodeMap = new Map<string, NodeShape>();\n for (const n of afterNodes) {\n afterNodeMap.set(n.id, n);\n }\n\n // --- Node add/remove detection ------------------------------------------\n const rawAddedNodes: string[] = [];\n const rawRemovedNodes: string[] = [];\n for (const id of afterNodeMap.keys()) {\n if (!beforeNodeMap.has(id)) rawAddedNodes.push(id);\n }\n for (const id of beforeNodeMap.keys()) {\n if (!afterNodeMap.has(id)) rawRemovedNodes.push(id);\n }\n\n // --- Node rename heuristic ----------------------------------------------\n // For each removed node, find exactly-one added node with the same set of\n // field names (ignoring types). If exactly one match, record as rename and\n // remove from added/removed. Ambiguous (multi-match) pairs are skipped.\n const renamedNodes: Array<{ from: string; to: string }> = [];\n const consumedAddedNodes = new Set<string>();\n const consumedRemovedNodes = new Set<string>();\n\n if (opts.detectRenames) {\n // Precompute field-name-set signatures.\n const sigFor = (node: NodeShape): string => {\n const names = (Array.isArray(node.fields) ? node.fields : [])\n .filter((f) => f && typeof f.name === 'string')\n .map((f) => f.name)\n .sort();\n return names.join('\\u0000');\n };\n\n for (const removedId of rawRemovedNodes) {\n const removedNode = beforeNodeMap.get(removedId);\n if (!removedNode) continue;\n const sig = sigFor(removedNode);\n\n const candidates: string[] = [];\n for (const addedId of rawAddedNodes) {\n if (consumedAddedNodes.has(addedId)) continue;\n const addedNode = afterNodeMap.get(addedId);\n if (!addedNode) continue;\n if (sigFor(addedNode) === sig) {\n candidates.push(addedId);\n }\n }\n\n if (candidates.length === 1) {\n const toId = candidates[0];\n renamedNodes.push({ from: removedId, to: toId });\n consumedAddedNodes.add(toId);\n consumedRemovedNodes.add(removedId);\n }\n // 0 or 2+ candidates → not recorded as rename\n }\n }\n\n const addedNodes = rawAddedNodes.filter((id) => !consumedAddedNodes.has(id));\n const removedNodes = rawRemovedNodes.filter((id) => !consumedRemovedNodes.has(id));\n\n // --- Field diff ----------------------------------------------------------\n // Build the set of (beforeId, afterId) pairs for nodes present in both —\n // either by matching id, or via a detected rename.\n const pairs: Array<{ beforeId: string; afterId: string }> = [];\n for (const id of beforeNodeMap.keys()) {\n if (afterNodeMap.has(id)) {\n pairs.push({ beforeId: id, afterId: id });\n }\n }\n for (const r of renamedNodes) {\n pairs.push({ beforeId: r.from, afterId: r.to });\n }\n\n // Collect field rename hints, keyed by the AFTER nodeId. This lets a\n // consumer supply hints after renaming a node: e.g., if a node was renamed\n // from 'user_old' → 'user_new' and a field was renamed from 'email' →\n // 'email_addr', the hint should target `nodeId: 'user_new'`.\n const fieldRenamesByAfterNodeId = new Map<\n string,\n Array<{ from: string; to: string }>\n >();\n for (const hint of opts.fieldRenames ?? []) {\n if (!hint || typeof hint.nodeId !== 'string') continue;\n if (typeof hint.from !== 'string' || typeof hint.to !== 'string') continue;\n let list = fieldRenamesByAfterNodeId.get(hint.nodeId);\n if (!list) {\n list = [];\n fieldRenamesByAfterNodeId.set(hint.nodeId, list);\n }\n list.push({ from: hint.from, to: hint.to });\n }\n // Also accept hints keyed by the BEFORE nodeId when the node itself was\n // renamed — map them across so renamedFields detection still fires.\n const renameFromToTo = new Map<string, string>();\n for (const r of renamedNodes) {\n renameFromToTo.set(r.from, r.to);\n }\n for (const hint of opts.fieldRenames ?? []) {\n if (!hint || typeof hint.nodeId !== 'string') continue;\n const mapped = renameFromToTo.get(hint.nodeId);\n if (mapped && !fieldRenamesByAfterNodeId.has(mapped)) {\n // Already added above under its original id; also expose under the\n // renamed key so downstream lookups find it whichever key is used.\n const list = fieldRenamesByAfterNodeId.get(hint.nodeId) ?? [];\n fieldRenamesByAfterNodeId.set(mapped, list);\n }\n }\n\n const renamedFields: Array<{ nodeId: string; from: string; to: string }> = [];\n const addedFields: Array<{ nodeId: string; fieldName: string }> = [];\n const removedFields: Array<{ nodeId: string; fieldName: string }> = [];\n const changedFieldTypes: Array<{\n nodeId: string;\n fieldName: string;\n from: string;\n to: string;\n }> = [];\n\n for (const { beforeId, afterId } of pairs) {\n const beforeNode = beforeNodeMap.get(beforeId);\n const afterNode = afterNodeMap.get(afterId);\n if (!beforeNode || !afterNode) continue;\n\n const beforeFields = fieldsByName(beforeNode);\n const afterFields = fieldsByName(afterNode);\n\n // Apply field-rename hints. The hint's nodeId is matched against the\n // AFTER node's id (most common case) — if the node was renamed, the\n // hint may target either id thanks to the dual keying above.\n const hints =\n fieldRenamesByAfterNodeId.get(afterId) ??\n fieldRenamesByAfterNodeId.get(beforeId) ??\n [];\n const consumedBefore = new Set<string>();\n const consumedAfter = new Set<string>();\n\n for (const hint of hints) {\n const oldField = beforeFields.get(hint.from);\n const newField = afterFields.get(hint.to);\n if (!oldField || !newField) continue;\n if (consumedBefore.has(hint.from) || consumedAfter.has(hint.to)) continue;\n renamedFields.push({ nodeId: afterId, from: hint.from, to: hint.to });\n consumedBefore.add(hint.from);\n consumedAfter.add(hint.to);\n\n // Type change across the rename\n const oldType = typeof oldField.type === 'string' ? oldField.type : '';\n const newType = typeof newField.type === 'string' ? newField.type : '';\n if (oldType !== newType) {\n changedFieldTypes.push({\n nodeId: afterId,\n fieldName: hint.to,\n from: oldType,\n to: newType,\n });\n }\n }\n\n // Field added / removed (after applying hints)\n for (const [name] of afterFields) {\n if (consumedAfter.has(name)) continue;\n if (!beforeFields.has(name)) {\n addedFields.push({ nodeId: afterId, fieldName: name });\n }\n }\n for (const [name] of beforeFields) {\n if (consumedBefore.has(name)) continue;\n if (!afterFields.has(name)) {\n removedFields.push({ nodeId: afterId, fieldName: name });\n }\n }\n\n // Changed field types for fields present in both (by name, no rename)\n for (const [name, beforeField] of beforeFields) {\n if (consumedBefore.has(name)) continue;\n const afterField = afterFields.get(name);\n if (!afterField) continue;\n const oldType = typeof beforeField.type === 'string' ? beforeField.type : '';\n const newType = typeof afterField.type === 'string' ? afterField.type : '';\n if (oldType !== newType) {\n changedFieldTypes.push({\n nodeId: afterId,\n fieldName: name,\n from: oldType,\n to: newType,\n });\n }\n }\n }\n\n // --- Edge diff (by id) ---------------------------------------------------\n const beforeEdgeIds = new Set<string>();\n for (const e of beforeEdges) beforeEdgeIds.add(e.id);\n const afterEdgeIds = new Set<string>();\n for (const e of afterEdges) afterEdgeIds.add(e.id);\n\n const addedEdges: string[] = [];\n const removedEdges: string[] = [];\n for (const id of afterEdgeIds) {\n if (!beforeEdgeIds.has(id)) addedEdges.push(id);\n }\n for (const id of beforeEdgeIds) {\n if (!afterEdgeIds.has(id)) removedEdges.push(id);\n }\n\n // --- Deterministic ordering ---------------------------------------------\n addedNodes.sort();\n removedNodes.sort();\n renamedNodes.sort((a, b) => a.from.localeCompare(b.from));\n const fieldKey = (f: { nodeId: string; fieldName: string }) =>\n `${f.nodeId}\\u0000${f.fieldName}`;\n addedFields.sort((a, b) => fieldKey(a).localeCompare(fieldKey(b)));\n removedFields.sort((a, b) => fieldKey(a).localeCompare(fieldKey(b)));\n renamedFields.sort((a, b) => {\n const k = a.nodeId.localeCompare(b.nodeId);\n return k !== 0 ? k : a.from.localeCompare(b.from);\n });\n changedFieldTypes.sort((a, b) => fieldKey(a).localeCompare(fieldKey(b)));\n addedEdges.sort();\n removedEdges.sort();\n\n return {\n addedNodes,\n removedNodes,\n renamedNodes,\n addedFields,\n removedFields,\n renamedFields,\n changedFieldTypes,\n addedEdges,\n removedEdges,\n };\n}\n","// ============================================================================\n// alpineflow/schema — toDot\n//\n// Pure helper: renders the current `canvas.nodes` + `canvas.edges` as a valid\n// graphviz DOT string. No canvas coupling, no mutation, never throws on\n// malformed input.\n//\n// Useful for docs generation, static image output (via `dot -Tpng`), and\n// PR-review attachments.\n//\n// Schema nodes render as HTML-like `<TABLE>` labels so field rows appear as\n// rows inside the node box in any graphviz viewer. Each field row exposes a\n// `PORT=\"<fieldName>\"` so edges can reference a specific row when\n// `sourceHandle`/`targetHandle` are set.\n// ============================================================================\n\nimport type { DotExportOptions } from './types';\n\nconst DEFAULTS: Required<DotExportOptions> = {\n rankdir: 'LR',\n nodeShape: 'plaintext',\n includeFieldTypes: true,\n includeFieldKeys: true,\n graphName: 'schema',\n};\n\n/**\n * Escape a string for inclusion inside a graphviz HTML-like label (the content\n * between the `< ... >` delimiters). Only the five XML/HTML specials need\n * escaping; the surrounding `<TAG>` markup is emitted by the renderer and is\n * not user-supplied.\n */\nfunction escapeHTML(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/**\n * Escape a string for inclusion inside a graphviz quoted string (`\"...\"`).\n * Backslash must be doubled first so the subsequent quote-escaping doesn't\n * re-escape the backslashes it just added.\n */\nfunction escapeQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\nfunction renderNode(n: any, o: Required<DotExportOptions>): string {\n const id = String(n?.id ?? '');\n const label = String(n?.data?.label ?? '');\n const fields = Array.isArray(n?.data?.fields) ? n.data.fields : [];\n\n const colSpan = 1 + (o.includeFieldKeys ? 1 : 0) + (o.includeFieldTypes ? 1 : 0);\n\n const rows: string[] = [];\n rows.push(\n ` <TR><TD BGCOLOR=\"#f0f0f0\" COLSPAN=\"${colSpan}\"><B>${escapeHTML(label)}</B></TD></TR>`,\n );\n\n for (const f of fields) {\n const name = String(f?.name ?? '');\n const cells: string[] = [];\n\n if (o.includeFieldKeys) {\n const marker = f?.key === 'primary' ? 'PK' : f?.key === 'foreign' ? 'FK' : '';\n cells.push(`<TD>${marker}</TD>`);\n }\n cells.push(`<TD PORT=\"${escapeHTML(name)}\">${escapeHTML(name)}</TD>`);\n if (o.includeFieldTypes) {\n cells.push(`<TD>${escapeHTML(String(f?.type ?? ''))}</TD>`);\n }\n\n rows.push(` <TR>${cells.join('')}</TR>`);\n }\n\n return (\n ` \"${escapeQuoted(id)}\" [label=<\\n` +\n ` <TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\">\\n` +\n `${rows.join('\\n')}\\n` +\n ` </TABLE>\\n` +\n ` >];`\n );\n}\n\nfunction renderEdge(e: any): string {\n const source = `\"${escapeQuoted(String(e?.source ?? ''))}\"`;\n const target = `\"${escapeQuoted(String(e?.target ?? ''))}\"`;\n const sourcePort = e?.sourceHandle\n ? `:\"${escapeQuoted(String(e.sourceHandle))}\"`\n : '';\n const targetPort = e?.targetHandle\n ? `:\"${escapeQuoted(String(e.targetHandle))}\"`\n : '';\n const label = e?.label\n ? ` [label=\"${escapeQuoted(String(e.label))}\"]`\n : '';\n return ` ${source}${sourcePort} -> ${target}${targetPort}${label};`;\n}\n\n/**\n * Render `canvas.nodes` + `canvas.edges` as a graphviz DOT string.\n *\n * Pure function: no canvas coupling, no mutation, safe on malformed input\n * (empty arrays, missing label, missing field type, etc.).\n */\nexport function toDot(\n canvas: { nodes: any[]; edges: any[] },\n opts: DotExportOptions = {},\n): string {\n const o = { ...DEFAULTS, ...opts };\n\n const lines: string[] = [];\n lines.push(`digraph \"${escapeQuoted(o.graphName)}\" {`);\n lines.push(` rankdir=${o.rankdir};`);\n lines.push(` node [shape=${o.nodeShape}];`);\n\n for (const n of canvas?.nodes ?? []) {\n lines.push(renderNode(n, o));\n }\n\n for (const e of canvas?.edges ?? []) {\n lines.push(renderEdge(e));\n }\n\n lines.push('}');\n return lines.join('\\n');\n}\n","// ============================================================================\n// alpineflow/schema — schemaLayout wrapper\n//\n// Thin wrapper around the host canvas's layout engines (dagre → tree → grid)\n// with schema-friendly defaults. When `deriveFromReferences` is set, uses\n// `inferReferences()` output as the graph topology instead of `canvas.edges`.\n//\n// Detection is runtime-only: the schema subpath addon must NOT hard-depend on\n// the dagre / hierarchy addons. If neither is registered, the grid fallback\n// (pure math, zero external deps) is always available.\n// ============================================================================\n\nimport type { SchemaLayoutOptions } from './types';\nimport { inferReferences } from './references';\n\ntype Algorithm = 'dagre' | 'tree' | 'grid';\n\nconst DEFAULT_ORDER: readonly Algorithm[] = ['dagre', 'tree', 'grid'] as const;\n\n/**\n * Apply a schema-tuned layout to the canvas.\n *\n * - Prefers the dagre addon (exposed via `canvas.layout()`), falls through to\n * the hierarchy addon (`canvas.treeLayout()`), then to a pure-math grid\n * fallback that is always available.\n * - When `opts.deriveFromReferences` is true, the underlying layout sees the\n * reference graph derived from `inferReferences(canvas.nodes)` instead of\n * the canvas's explicit edges. The original edges are restored afterwards,\n * even if the layout call throws.\n */\nexport async function schemaLayout(\n canvas: any,\n opts: SchemaLayoutOptions = {},\n): Promise<void> {\n const direction = opts.direction ?? 'LR';\n const nodeSpacing = opts.nodeSpacing ?? 80;\n const rankSpacing = opts.rankSpacing ?? 160;\n\n const preferred = resolvePreferredOrder(opts.algorithm);\n\n // Swap edges in-place when deriving from references so whichever algorithm\n // runs downstream sees the inferred topology. Splice is used so Alpine's\n // reactive proxy tracks the mutation.\n const swap = opts.deriveFromReferences ? prepareEdgeSwap(canvas) : null;\n\n try {\n for (const algo of preferred) {\n if (algo === 'dagre' && tryDagre(canvas, direction, nodeSpacing, rankSpacing)) {\n return;\n }\n if (algo === 'tree' && tryTree(canvas, direction, nodeSpacing, rankSpacing)) {\n return;\n }\n if (algo === 'grid') {\n applyGridLayout(canvas.nodes ?? [], nodeSpacing, rankSpacing, direction);\n return;\n }\n }\n\n // Should be unreachable because 'grid' is always in the fallback chain\n // when no explicit algorithm was requested. Reachable only when the\n // consumer pinned algorithm:'dagre' or 'tree' and that addon was\n // missing — in which case we warn and no-op.\n // eslint-disable-next-line no-console\n console.warn(\n '[alpineflow/schema] schemaLayout: no layout algorithm available. ' +\n 'Register @getartisanflow/alpineflow/dagre (or hierarchy), or pass ' +\n '{ algorithm: \"grid\" } for the always-available fallback.',\n );\n } finally {\n if (swap) {\n swap.restore();\n }\n }\n}\n\nfunction resolvePreferredOrder(pinned?: Algorithm): Algorithm[] {\n if (!pinned) {\n return [...DEFAULT_ORDER];\n }\n // When the consumer pins an algorithm, honour that first and only that —\n // they've opted out of the fallback chain. The grid path still counts as\n // \"always available\" and terminates immediately.\n return [pinned];\n}\n\ninterface EdgeSwap {\n restore: () => void;\n}\n\nfunction prepareEdgeSwap(canvas: any): EdgeSwap | null {\n const edges = canvas.edges;\n if (!Array.isArray(edges)) {\n return null;\n }\n\n const original = edges.slice();\n const inferred = inferReferences(canvas.nodes ?? []).map((suggestion, index) => ({\n id: `schema-layout-inferred-${index}`,\n source: suggestion.fromNodeId,\n target: suggestion.toNodeId,\n sourceHandle: suggestion.fromFieldName,\n targetHandle: suggestion.toFieldName,\n }));\n\n edges.splice(0, edges.length, ...inferred);\n\n return {\n restore: () => {\n edges.splice(0, edges.length, ...original);\n },\n };\n}\n\nfunction tryDagre(\n canvas: any,\n direction: 'LR' | 'TB' | 'BT' | 'RL',\n nodeSpacing: number,\n rankSpacing: number,\n): boolean {\n // `canvas.layout()` is the dagre entry point exposed by the core. When the\n // dagre addon isn't registered it throws a dedicated error — we treat that\n // as \"not available\" and fall through to the next algorithm.\n if (typeof canvas.layout !== 'function') {\n return false;\n }\n try {\n canvas.layout({\n direction,\n nodesep: nodeSpacing,\n ranksep: rankSpacing,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction tryTree(\n canvas: any,\n direction: 'LR' | 'TB' | 'BT' | 'RL',\n nodeSpacing: number,\n rankSpacing: number,\n): boolean {\n if (typeof canvas.treeLayout !== 'function') {\n return false;\n }\n // The hierarchy engine only recognises TB / LR / BT / RL; pass through\n // as-is. It derives its own spacing from `nodeWidth` / `nodeHeight`, so\n // translate our logical spacing to those knobs.\n try {\n canvas.treeLayout({\n direction,\n nodeWidth: nodeSpacing + 200,\n nodeHeight: rankSpacing + 80,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction applyGridLayout(\n nodes: any[],\n nodeSpacing: number,\n rankSpacing: number,\n direction: 'LR' | 'TB' | 'BT' | 'RL',\n): void {\n const count = nodes.length;\n if (count === 0) {\n return;\n }\n\n const cols = Math.max(1, Math.ceil(Math.sqrt(count)));\n const rows = Math.ceil(count / cols);\n const cellWidth = nodeSpacing + 300;\n const cellHeight = rankSpacing + 200;\n\n for (let i = 0; i < count; i++) {\n const col = i % cols;\n const row = Math.floor(i / cols);\n\n let x = col * cellWidth;\n let y = row * cellHeight;\n\n // Grid is axis-symmetric, so TB / LR collapse to the same arrangement;\n // BT and RL simply mirror the relevant axis so consumers who care about\n // the visual direction still see the right flow.\n if (direction === 'BT') {\n y = (rows - 1 - row) * cellHeight;\n } else if (direction === 'RL') {\n x = (cols - 1 - col) * cellWidth;\n }\n\n nodes[i].position = { x, y };\n }\n}\n","// ============================================================================\n// alpineflow/schema — attachSchemaHistory()\n//\n// Opt-in undo/redo scaffolding. Listens for `schema:*` DOM events fired by\n// field-ops helpers, snapshots the canvas via `schemaToJSON`, and restores via\n// `schemaFromJSON` on undo/redo. Bounded stack with `limit` eviction and\n// transactional `batch(fn)` semantics.\n//\n// Consumers must opt in — `registerSchemaAddon` does NOT auto-attach history.\n// ============================================================================\n\nimport type { SchemaGraphJSON, SchemaHistoryHandle, SchemaHistoryOptions } from './types';\nimport { schemaFromJSON, schemaToJSON } from './serialization';\n\nconst TRACKED_EVENTS = [\n 'schema:field-added',\n 'schema:field-renamed',\n 'schema:field-removed',\n 'schema:edges-cascaded',\n] as const;\n\n/**\n * Attach a bounded undo/redo stack to a canvas. Returns a handle with\n * `undo()`, `redo()`, `batch(fn)`, `clear()`, and `dispose()`.\n *\n * Snapshots are pushed on each `schema:field-added`, `schema:field-renamed`,\n * `schema:field-removed`, and `schema:edges-cascaded` event. The apply path\n * (undo/redo/batch rollback) suspends snapshot pushes to avoid feedback loops.\n */\nexport function attachSchemaHistory(canvas: any, opts: SchemaHistoryOptions = {}): SchemaHistoryHandle {\n const limit = Math.max(1, opts.limit ?? 50);\n const undoStack: SchemaGraphJSON[] = [];\n const redoStack: SchemaGraphJSON[] = [];\n let suspendDepth = 0;\n let batchDepth = 0;\n let batchEntrySnapshot: SchemaGraphJSON | null = null;\n let disposed = false;\n\n const target: EventTarget | null = canvas?.el ?? canvas?._container ?? null;\n if (!target || typeof (target as any).addEventListener !== 'function') {\n return makeNoopHandle();\n }\n\n const evictOldest = (): void => {\n // Always keep at least 1 entry (the floor) so we never undo past the\n // initial snapshot.\n while (undoStack.length > limit && undoStack.length > 1) {\n undoStack.shift();\n }\n };\n\n // Push a snapshot, deduping against the current stack top, then evict + clear\n // redo. Dedup identical states: a cascading op (renameField/removeField)\n // dispatches schema:field-* AND schema:edges-cascaded *after* all mutations\n // complete, yielding two byte-identical snapshots — coalesce them into a\n // single undoable step so the first undo is never a no-op. Shared by the\n // event path (pushSnapshot) and the batch-commit path.\n const pushDeduped = (snap: SchemaGraphJSON): void => {\n const top = undoStack[undoStack.length - 1];\n if (top !== undefined && JSON.stringify(top) === JSON.stringify(snap)) {\n return;\n }\n undoStack.push(snap);\n evictOldest();\n redoStack.length = 0;\n };\n\n const pushSnapshot = (): void => {\n if (disposed) {\n return;\n }\n if (suspendDepth > 0) {\n return;\n }\n if (batchDepth > 0) {\n // Inside a batch — individual events do not push. A single snapshot\n // is pushed when the outermost batch exits.\n return;\n }\n pushDeduped(schemaToJSON(canvas));\n };\n\n // Initial floor snapshot — captures pre-mutation state so the first undo\n // after a field-add reverts cleanly.\n undoStack.push(schemaToJSON(canvas));\n\n const onEvent = (): void => {\n pushSnapshot();\n };\n for (const name of TRACKED_EVENTS) {\n target.addEventListener(name, onEvent);\n }\n\n const applySnapshot = (snap: SchemaGraphJSON): void => {\n // Suspend snapshot capture while we mutate via schemaFromJSON.\n suspendDepth++;\n try {\n schemaFromJSON(canvas, snap);\n } finally {\n suspendDepth--;\n }\n };\n\n const handle: SchemaHistoryHandle = {\n get canUndo(): boolean {\n // The floor snapshot always stays; only report true when there is\n // at least one mutation snapshot above it.\n return undoStack.length > 1;\n },\n get canRedo(): boolean {\n return redoStack.length > 0;\n },\n undo(): boolean {\n if (disposed) {\n return false;\n }\n if (undoStack.length <= 1) {\n return false;\n }\n const current = undoStack.pop() as SchemaGraphJSON;\n redoStack.push(current);\n const prev = undoStack[undoStack.length - 1];\n applySnapshot(prev);\n return true;\n },\n redo(): boolean {\n if (disposed) {\n return false;\n }\n if (redoStack.length === 0) {\n return false;\n }\n const snap = redoStack.pop() as SchemaGraphJSON;\n undoStack.push(snap);\n applySnapshot(snap);\n return true;\n },\n clear(): void {\n undoStack.length = 0;\n redoStack.length = 0;\n if (!disposed) {\n undoStack.push(schemaToJSON(canvas));\n }\n },\n batch<T>(fn: () => T): T {\n if (disposed) {\n return fn();\n }\n // Outermost batch captures the pre-batch state for rollback on\n // throw. Nested batches share the outer batch's entry snapshot.\n if (batchDepth === 0) {\n batchEntrySnapshot = schemaToJSON(canvas);\n }\n batchDepth++;\n try {\n const result = fn();\n batchDepth--;\n if (batchDepth === 0) {\n // Outermost batch exiting — push one snapshot capturing\n // the aggregate result of all mutations inside.\n batchEntrySnapshot = null;\n if (suspendDepth === 0 && !disposed) {\n // A net-no-op batch must not leave a duplicate-of-top entry.\n pushDeduped(schemaToJSON(canvas));\n }\n }\n return result;\n } catch (err) {\n batchDepth--;\n if (batchDepth === 0) {\n // Roll back to pre-batch state. suspendDepth increment in\n // applySnapshot prevents the restoration from triggering\n // its own snapshot via any events fired by schemaFromJSON.\n const entry = batchEntrySnapshot;\n batchEntrySnapshot = null;\n if (entry && !disposed) {\n applySnapshot(entry);\n }\n }\n throw err;\n }\n },\n dispose(): void {\n if (disposed) {\n return;\n }\n disposed = true;\n for (const name of TRACKED_EVENTS) {\n target.removeEventListener(name, onEvent);\n }\n undoStack.length = 0;\n redoStack.length = 0;\n batchEntrySnapshot = null;\n },\n };\n\n return handle;\n}\n\nfunction makeNoopHandle(): SchemaHistoryHandle {\n return {\n get canUndo(): boolean {\n return false;\n },\n get canRedo(): boolean {\n return false;\n },\n undo: (): boolean => false,\n redo: (): boolean => false,\n clear: (): void => {},\n batch<T>(fn: () => T): T {\n return fn();\n },\n dispose: (): void => {},\n };\n}\n","// ============================================================================\n// Shared helpers for the three inspector directives.\n//\n// Keeps the per-scope files focused on the (scope-specific) default UI and\n// helper wiring. Selection lookup, canvas discovery, default-ui detection,\n// and stamping utilities live here.\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\n\nexport type InspectorScope = 'node' | 'row' | 'edge';\n\n/**\n * Pick the primary selection id from a reactive `Set<string>`.\n *\n * JS Sets preserve insertion order, so the most recently selected id is the\n * last element. For an empty set we return null.\n *\n * Iterating the set here also registers a reactive dependency with Alpine so\n * callers inside an `effect` re-run when the set changes.\n */\nexport function lastInSet(set: Set<string> | null | undefined): string | null {\n if (!set || set.size === 0) {\n return null;\n }\n let last: string | null = null;\n for (const id of set) {\n last = id;\n }\n return last;\n}\n\n/** Parse a row id of the form \"nodeId.fieldName\" — first dot only. */\nexport function parseRowId(\n rowId: string | null,\n): { nodeId: string; fieldName: string } | null {\n if (!rowId) {\n return null;\n }\n const dot = rowId.indexOf('.');\n if (dot < 1 || dot === rowId.length - 1) {\n return null;\n }\n return { nodeId: rowId.slice(0, dot), fieldName: rowId.slice(dot + 1) };\n}\n\n/**\n * Resolve the flow canvas Alpine scope associated with an inspector element.\n *\n * Three-step lookup:\n * 1. Nearest ancestor `.flow-container` — inspector nested inside the canvas\n * viewport (preset side-panel pattern).\n * 2. If none, and exactly one `.flow-container` exists on the page, use it —\n * supports outside-canvas placements (e.g. a page-level right sidebar\n * that's a sibling of the canvas). Single canvas = unambiguous.\n * 3. Multiple canvases without an ancestor match — log a one-shot warning\n * and bail out; the caller must nest the inspector inside the target\n * canvas (an explicit selector prop is on the v0.2.2 roadmap).\n *\n * Inspector directives currently call this once at init and close over the\n * returned scope. That works because inspectors render inside or alongside an\n * already-initialized canvas in every shipped pattern. If a future caller\n * mounts an inspector before its canvas's Alpine setup runs (e.g. portal-\n * teleported or tab-switched), the cached `Alpine.$data()` proxy can go stale\n * and method calls will throw — mirror the workflow addon's `ensureCanvas`\n * pattern (re-resolve at method-call time) before placing inspectors in such\n * positions.\n */\nexport function findCanvasScope(\n Alpine: Alpine,\n el: HTMLElement,\n): any | null {\n // 1. Closest ancestor .flow-container — inside-canvas placement.\n const ancestor = el.closest('.flow-container') as HTMLElement | null;\n if (ancestor) {\n try {\n return Alpine.$data(ancestor) ?? null;\n } catch {\n /* fall through to page-level fallbacks */\n }\n }\n\n // 2. Single .flow-container on the page — outside-canvas placement.\n const containers = document.querySelectorAll('.flow-container');\n if (containers.length === 1) {\n try {\n return Alpine.$data(containers[0] as HTMLElement) ?? null;\n } catch {\n /* fall through to warning / null */\n }\n }\n\n // 3. Multiple canvases and no ancestor — warn once, return null.\n if (\n containers.length > 1\n && !(window as any).__alpineflowSchemaMultiCanvasWarned\n ) {\n (window as any).__alpineflowSchemaMultiCanvasWarned = true;\n console.warn(\n '[alpineflow/schema] inspector directive found multiple .flow-container elements on the page; '\n + 'place inspector inside the canvas OR scope the directive expression to a specific canvas '\n + '(multi-canvas scope selector is on the v0.2.2 roadmap).',\n );\n }\n\n return null;\n}\n\n/**\n * Locate the opt-in default-UI template directly inside the directive element.\n *\n * Scoped to `:scope > template[x-schema-default-ui]` so nested inspector\n * consumers can't accidentally collide with a parent scaffold.\n */\nexport function findDefaultUiTemplate(el: HTMLElement): HTMLTemplateElement | null {\n return el.querySelector(\n ':scope > template[x-schema-default-ui]',\n ) as HTMLTemplateElement | null;\n}\n\n/**\n * Remove any previously-stamped default-UI content so the next render can\n * replace it cleanly. We mark our managed root with a data attribute and only\n * touch that — host children (siblings of the template) are never disturbed.\n */\nexport function clearStampedUi(el: HTMLElement): void {\n const existing = el.querySelector(':scope > [data-schema-default-ui-root]');\n if (existing) {\n existing.remove();\n }\n}\n\n/**\n * Append a managed root after the template and return it for content stamping.\n * The managed root carries `data-schema-default-ui-root` so we can find and\n * replace it on every re-render.\n */\nexport function createStampRoot(el: HTMLElement): HTMLElement {\n const root = document.createElement('div');\n root.setAttribute('data-schema-default-ui-root', '');\n el.appendChild(root);\n return root;\n}\n\n/**\n * Snapshot of a focused input inside a stamp root so we can re-focus the\n * equivalent element after a re-stamp. Identity is resolved via `data-field`\n * (our own marker on inspector inputs) and a tag-name match.\n */\nexport interface StampFocusSnapshot {\n field: string;\n tagName: string;\n selectionStart: number | null;\n selectionEnd: number | null;\n}\n\n/**\n * Capture the currently-focused element within a stamp root so re-stamps can\n * restore focus. Returns `null` when focus isn't within the root, or the\n * focused element has no `data-field` identity marker.\n */\nexport function captureStampFocus(\n root: HTMLElement | null | undefined,\n): StampFocusSnapshot | null {\n if (!root) {\n return null;\n }\n const active = document.activeElement;\n if (!active || !(active instanceof HTMLElement) || !root.contains(active)) {\n return null;\n }\n const field = active.getAttribute('data-field');\n if (!field) {\n return null;\n }\n let selectionStart: number | null = null;\n let selectionEnd: number | null = null;\n if (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) {\n try {\n selectionStart = active.selectionStart;\n selectionEnd = active.selectionEnd;\n } catch {\n /* Some input types (e.g. checkbox, number) throw on selection access. */\n }\n }\n return {\n field,\n tagName: active.tagName.toLowerCase(),\n selectionStart,\n selectionEnd,\n };\n}\n\n/**\n * Escape an attribute value for safe embedding in a CSS selector. Prefers\n * the native `CSS.escape` when available (all modern browsers) and falls\n * back to a minimal escaper for environments without it (e.g. older jsdom).\n */\nfunction escapeAttrValue(value: string): string {\n if (typeof (globalThis as any).CSS !== 'undefined' && typeof (globalThis as any).CSS.escape === 'function') {\n return (globalThis as any).CSS.escape(value);\n }\n return value.replace(/[\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Restore focus after a re-stamp. Looks up the element by `data-field` within\n * the new root (requiring a matching tag name) and re-focuses it, restoring\n * the selection range when possible. Silent on failure — focus preservation\n * is best-effort and must never crash the re-stamp cycle.\n */\nexport function restoreStampFocus(\n root: HTMLElement | null | undefined,\n captured: StampFocusSnapshot | null,\n): void {\n if (!root || !captured) {\n return;\n }\n const candidate = root.querySelector<HTMLElement>(\n `[data-field=\"${escapeAttrValue(captured.field)}\"]`,\n );\n if (!candidate) {\n return;\n }\n if (candidate.tagName.toLowerCase() !== captured.tagName) {\n return;\n }\n try {\n candidate.focus({ preventScroll: true });\n if (\n (candidate instanceof HTMLInputElement || candidate instanceof HTMLTextAreaElement)\n && captured.selectionStart !== null\n && captured.selectionEnd !== null\n ) {\n candidate.setSelectionRange(captured.selectionStart, captured.selectionEnd);\n }\n } catch {\n /* silent — focus failures shouldn't crash the re-stamp */\n }\n}\n","// ============================================================================\n// x-schema-node-inspector Directive\n//\n// Attach to any container (e.g. `<aside x-schema-node-inspector>`) to expose\n// the currently-selected node + schema helpers to the subtree. Optionally\n// stamps a minimal default field-list UI when a child\n// `<template x-schema-default-ui>` is present.\n//\n// Exposed scope (via `Alpine.addScopeToNode`):\n// selectedNode — reactive FlowNode | null\n// inspector.addField(f) — append field to selected node\n// inspector.renameField(o,n) — rename field on selected node\n// inspector.removeField(name) — remove field from selected node\n// inspector.reorderFields(names) — reorder fields on selected node\n//\n// The default UI (when opted in) is structural HTML only:\n// <div data-schema-default-ui-root>\n// <div data-schema-inspector-empty>No node selected.</div> ← empty state\n// — OR —\n// <header data-schema-inspector-label>User</header>\n// <ul data-schema-inspector-fields>\n// <li data-schema-inspector-field>\n// <span>id</span><button data-action=\"remove\">remove</button>\n// </li>\n// ...\n// </ul>\n// <form data-schema-inspector-add-field>\n// <input data-field=\"name\"><input data-field=\"type\"><button>add</button>\n// </form>\n// </div>\n//\n// Consumer themes style via CSS. This directive writes no styles of its own.\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\nimport {\n lastInSet,\n findCanvasScope,\n findDefaultUiTemplate,\n clearStampedUi,\n createStampRoot,\n captureStampFocus,\n restoreStampFocus,\n} from './shared';\n\nexport function registerNodeInspectorDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-node-inspector',\n (el, _spec, { effect, cleanup }) => {\n const host = el as HTMLElement;\n const canvas = findCanvasScope(Alpine, host);\n if (!canvas) {\n return;\n }\n\n const template = findDefaultUiTemplate(host);\n\n // Build the inspector helper object. These thin wrappers close over\n // the current selection so consumers don't have to thread nodeId\n // through every call.\n const inspector = {\n addField(field: any) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection' };\n }\n return canvas.addField?.(id, field) ?? { applied: false, reason: 'no-helper' };\n },\n renameField(oldName: string, newName: string) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection', cascadedEdgeIds: [] };\n }\n return (\n canvas.renameField?.(id, oldName, newName) ?? {\n applied: false,\n reason: 'no-helper',\n cascadedEdgeIds: [],\n }\n );\n },\n removeField(fieldName: string) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection', droppedEdgeIds: [] };\n }\n return (\n canvas.removeField?.(id, fieldName) ?? {\n applied: false,\n reason: 'no-helper',\n droppedEdgeIds: [],\n }\n );\n },\n reorderFields(order: string[]) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection' };\n }\n return (\n canvas.reorderFields?.(id, order) ?? {\n applied: false,\n reason: 'no-helper',\n }\n );\n },\n };\n\n // Inject reactive scope onto the inspector element. The `get` on\n // `selectedNode` reads `canvas.selectedNodes` + `canvas.nodes`, so\n // Alpine rewires dependents whenever either changes.\n const removeScope = Alpine.addScopeToNode(host, {\n inspector,\n get selectedNode() {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return null;\n }\n return canvas.nodes?.find((n: any) => n.id === id) ?? null;\n },\n });\n\n // Default-UI stamping. If no template is present, we do nothing\n // and the host's own children render through Alpine as normal.\n if (template) {\n effect(() => {\n stampNodeDefaultUi(host, canvas);\n });\n }\n\n cleanup(() => {\n clearStampedUi(host);\n removeScope?.();\n });\n },\n );\n}\n\nfunction stampNodeDefaultUi(host: HTMLElement, canvas: any): void {\n // Capture focus on the previous managed root BEFORE tearing it down, so a\n // reactive re-stamp triggered while the user is typing doesn't blur the\n // focused input.\n const previousRoot = host.querySelector<HTMLElement>(\n ':scope > [data-schema-default-ui-root]',\n );\n const captured = captureStampFocus(previousRoot);\n\n clearStampedUi(host);\n const root = createStampRoot(host);\n\n const id = lastInSet(canvas.selectedNodes);\n const node = id ? canvas.nodes?.find((n: any) => n.id === id) : null;\n\n if (!node) {\n const empty = document.createElement('div');\n empty.setAttribute('data-schema-inspector-empty', '');\n empty.textContent = 'No node selected.';\n root.appendChild(empty);\n restoreStampFocus(root, captured);\n return;\n }\n\n const header = document.createElement('header');\n header.setAttribute('data-schema-inspector-label', '');\n header.textContent = String(node.data?.label ?? node.id);\n root.appendChild(header);\n\n const list = document.createElement('ul');\n list.setAttribute('data-schema-inspector-fields', '');\n const fields: any[] = Array.isArray(node.data?.fields) ? node.data.fields : [];\n for (const f of fields) {\n const li = document.createElement('li');\n li.setAttribute('data-schema-inspector-field', '');\n li.dataset.fieldName = String(f?.name ?? '');\n\n const nameSpan = document.createElement('span');\n nameSpan.textContent = String(f?.name ?? '');\n li.appendChild(nameSpan);\n\n if (f?.type) {\n const typeSpan = document.createElement('span');\n typeSpan.setAttribute('data-field-type', '');\n typeSpan.textContent = String(f.type);\n li.appendChild(typeSpan);\n }\n\n const removeBtn = document.createElement('button');\n removeBtn.type = 'button';\n removeBtn.setAttribute('data-action', 'remove');\n removeBtn.textContent = 'remove';\n removeBtn.addEventListener('click', () => {\n canvas.removeField?.(node.id, f.name);\n });\n li.appendChild(removeBtn);\n\n list.appendChild(li);\n }\n root.appendChild(list);\n\n const form = document.createElement('form');\n form.setAttribute('data-schema-inspector-add-field', '');\n\n const nameInput = document.createElement('input');\n nameInput.setAttribute('data-field', 'name');\n nameInput.placeholder = 'field name';\n form.appendChild(nameInput);\n\n const registry = Array.isArray(canvas._config?.fieldTypeRegistry)\n ? (canvas._config.fieldTypeRegistry as string[])\n : null;\n\n let typeInput: HTMLInputElement | HTMLSelectElement;\n if (registry && registry.length > 0) {\n const select = document.createElement('select');\n select.setAttribute('data-field', 'type');\n for (const type of registry) {\n const option = document.createElement('option');\n option.value = type;\n option.textContent = type;\n select.appendChild(option);\n }\n select.value = registry[0];\n typeInput = select;\n } else {\n const input = document.createElement('input');\n input.setAttribute('data-field', 'type');\n input.placeholder = 'type';\n input.value = 'text';\n typeInput = input;\n }\n form.appendChild(typeInput);\n\n const addBtn = document.createElement('button');\n addBtn.type = 'submit';\n addBtn.textContent = 'add';\n form.appendChild(addBtn);\n\n form.addEventListener('submit', (e) => {\n e.preventDefault();\n const fieldName = nameInput.value.trim();\n if (!fieldName) {\n return;\n }\n const rawType = typeInput.value;\n const type = (typeof rawType === 'string' ? rawType.trim() : '') || 'text';\n const result = canvas.addField?.(node.id, { name: fieldName, type });\n if (result?.applied) {\n nameInput.value = '';\n }\n });\n\n root.appendChild(form);\n\n restoreStampFocus(root, captured);\n}\n","// ============================================================================\n// x-schema-row-inspector Directive\n//\n// Attach to any container to expose the currently-selected row\n// (`{nodeId, fieldName}`) + helpers to the subtree. Optionally stamps a\n// minimal default \"edit this field\" UI when a child\n// `<template x-schema-default-ui>` is present.\n//\n// Exposed scope:\n// selectedRow — reactive {nodeId, fieldName} | null\n// inspector.renameField(newName) — rename the selected field\n// inspector.removeField() — remove the selected field\n// inspector.updateField(patch) — mutate arbitrary field props\n// (e.g. type, required) in place\n//\n// Default UI (opt-in):\n// <div data-schema-default-ui-root>\n// <div data-schema-inspector-empty>No row selected.</div>\n// — OR —\n// <label>name <input data-field=\"name\"></label>\n// <label>type <input data-field=\"type\"></label>\n// <label>required <input type=\"checkbox\" data-field=\"required\"></label>\n// <button data-action=\"remove\">remove</button>\n// </div>\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\nimport {\n lastInSet,\n parseRowId,\n findCanvasScope,\n findDefaultUiTemplate,\n clearStampedUi,\n createStampRoot,\n captureStampFocus,\n restoreStampFocus,\n} from './shared';\n\nexport function registerRowInspectorDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-row-inspector',\n (el, _spec, { effect, cleanup }) => {\n const host = el as HTMLElement;\n const canvas = findCanvasScope(Alpine, host);\n if (!canvas) {\n return;\n }\n\n const template = findDefaultUiTemplate(host);\n\n const currentRow = () => parseRowId(lastInSet(canvas.selectedRows));\n\n const currentField = () => {\n const row = currentRow();\n if (!row) {\n return null;\n }\n const node = canvas.nodes?.find((n: any) => n.id === row.nodeId);\n if (!node) {\n return null;\n }\n const fields: any[] = node.data?.fields ?? [];\n return fields.find((f: any) => f?.name === row.fieldName) ?? null;\n };\n\n const inspector = {\n renameField(newName: string) {\n const row = currentRow();\n if (!row) {\n return { applied: false, reason: 'no-selection', cascadedEdgeIds: [] };\n }\n return (\n canvas.renameField?.(row.nodeId, row.fieldName, newName) ?? {\n applied: false,\n reason: 'no-helper',\n cascadedEdgeIds: [],\n }\n );\n },\n removeField() {\n const row = currentRow();\n if (!row) {\n return { applied: false, reason: 'no-selection', droppedEdgeIds: [] };\n }\n return (\n canvas.removeField?.(row.nodeId, row.fieldName) ?? {\n applied: false,\n reason: 'no-helper',\n droppedEdgeIds: [],\n }\n );\n },\n /**\n * Patch non-name properties (type, required, …) of the selected\n * field in place. For name changes, use `renameField` so edges\n * cascade correctly.\n */\n updateField(patch: Record<string, unknown>) {\n const field = currentField();\n if (!field) {\n return { applied: false, reason: 'no-selection' };\n }\n for (const [k, v] of Object.entries(patch)) {\n if (k === 'name') {\n continue; // use renameField\n }\n field[k] = v;\n }\n return { applied: true };\n },\n };\n\n const removeScope = Alpine.addScopeToNode(host, {\n inspector,\n get selectedRow() {\n return currentRow();\n },\n });\n\n if (template) {\n effect(() => {\n stampRowDefaultUi(host, canvas, currentRow());\n });\n }\n\n cleanup(() => {\n clearStampedUi(host);\n removeScope?.();\n });\n },\n );\n}\n\nfunction stampRowDefaultUi(\n host: HTMLElement,\n canvas: any,\n row: { nodeId: string; fieldName: string } | null,\n): void {\n // Capture focus on the previous managed root BEFORE tearing it down, so a\n // reactive re-stamp triggered while the user is typing doesn't blur the\n // focused input.\n const previousRoot = host.querySelector<HTMLElement>(\n ':scope > [data-schema-default-ui-root]',\n );\n const captured = captureStampFocus(previousRoot);\n\n clearStampedUi(host);\n const root = createStampRoot(host);\n\n if (!row) {\n const empty = document.createElement('div');\n empty.setAttribute('data-schema-inspector-empty', '');\n empty.textContent = 'No row selected.';\n root.appendChild(empty);\n restoreStampFocus(root, captured);\n return;\n }\n\n const node = canvas.nodes?.find((n: any) => n.id === row.nodeId);\n const field = node?.data?.fields?.find((f: any) => f?.name === row.fieldName) ?? null;\n\n if (!field) {\n const missing = document.createElement('div');\n missing.setAttribute('data-schema-inspector-empty', '');\n missing.textContent = 'Selected row no longer exists.';\n root.appendChild(missing);\n restoreStampFocus(root, captured);\n return;\n }\n\n // Name\n const nameLabel = document.createElement('label');\n nameLabel.textContent = 'name ';\n const nameInput = document.createElement('input');\n nameInput.setAttribute('data-field', 'name');\n nameInput.value = String(field.name ?? '');\n nameInput.addEventListener('change', () => {\n const next = nameInput.value.trim();\n if (!next || next === field.name) {\n return;\n }\n canvas.renameField?.(row.nodeId, row.fieldName, next);\n });\n nameLabel.appendChild(nameInput);\n root.appendChild(nameLabel);\n\n // Type\n const typeLabel = document.createElement('label');\n typeLabel.textContent = 'type ';\n const typeInput = document.createElement('input');\n typeInput.setAttribute('data-field', 'type');\n typeInput.value = String(field.type ?? '');\n typeInput.addEventListener('change', () => {\n field.type = typeInput.value;\n });\n typeLabel.appendChild(typeInput);\n root.appendChild(typeLabel);\n\n // Required\n const requiredLabel = document.createElement('label');\n requiredLabel.textContent = 'required ';\n const requiredInput = document.createElement('input');\n requiredInput.type = 'checkbox';\n requiredInput.setAttribute('data-field', 'required');\n requiredInput.checked = Boolean(field.required);\n requiredInput.addEventListener('change', () => {\n field.required = requiredInput.checked;\n });\n requiredLabel.appendChild(requiredInput);\n root.appendChild(requiredLabel);\n\n // Remove\n const removeBtn = document.createElement('button');\n removeBtn.type = 'button';\n removeBtn.setAttribute('data-action', 'remove');\n removeBtn.textContent = 'remove';\n removeBtn.addEventListener('click', () => {\n canvas.removeField?.(row.nodeId, row.fieldName);\n });\n root.appendChild(removeBtn);\n\n restoreStampFocus(root, captured);\n}\n","// ============================================================================\n// x-schema-edge-inspector Directive\n//\n// Attach to any container to expose the currently-selected edge + helpers to\n// the subtree. Optionally stamps a minimal label/delete UI when a child\n// `<template x-schema-default-ui>` is present.\n//\n// Exposed scope:\n// selectedEdge — reactive FlowEdge | null\n// inspector.updateEdge(patch) — patch arbitrary props (label, style, …) in place\n// inspector.setLabel(text) — convenience for updating the edge label\n// inspector.removeEdge() — drop the selected edge (delegates to removeEdges)\n//\n// Default UI (opt-in):\n// <div data-schema-default-ui-root>\n// <div data-schema-inspector-empty>No edge selected.</div>\n// — OR —\n// <label>label <input data-field=\"label\"></label>\n// <button data-action=\"delete\">delete</button>\n// </div>\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\nimport {\n lastInSet,\n findCanvasScope,\n findDefaultUiTemplate,\n clearStampedUi,\n createStampRoot,\n captureStampFocus,\n restoreStampFocus,\n} from './shared';\n\nexport function registerEdgeInspectorDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-edge-inspector',\n (el, _spec, { effect, cleanup }) => {\n const host = el as HTMLElement;\n const canvas = findCanvasScope(Alpine, host);\n if (!canvas) {\n return;\n }\n\n const template = findDefaultUiTemplate(host);\n\n const currentEdge = () => {\n const id = lastInSet(canvas.selectedEdges);\n if (!id) {\n return null;\n }\n return canvas.edges?.find((e: any) => e.id === id) ?? null;\n };\n\n const inspector = {\n updateEdge(patch: Record<string, unknown>) {\n const edge = currentEdge();\n if (!edge) {\n return { applied: false, reason: 'no-selection' };\n }\n for (const [k, v] of Object.entries(patch)) {\n edge[k] = v;\n }\n return { applied: true };\n },\n setLabel(label: string) {\n return this.updateEdge({ label });\n },\n removeEdge() {\n const edge = currentEdge();\n if (!edge) {\n return { applied: false, reason: 'no-selection' };\n }\n if (typeof canvas.removeEdges === 'function') {\n canvas.removeEdges([edge.id]);\n return { applied: true };\n }\n // Fallback: splice out of the reactive array directly.\n const idx = canvas.edges?.findIndex((e: any) => e.id === edge.id) ?? -1;\n if (idx === -1) {\n return { applied: false, reason: 'no-helper' };\n }\n canvas.edges.splice(idx, 1);\n return { applied: true };\n },\n };\n\n const removeScope = Alpine.addScopeToNode(host, {\n inspector,\n get selectedEdge() {\n return currentEdge();\n },\n });\n\n if (template) {\n effect(() => {\n stampEdgeDefaultUi(host, canvas, currentEdge());\n });\n }\n\n cleanup(() => {\n clearStampedUi(host);\n removeScope?.();\n });\n },\n );\n}\n\nfunction stampEdgeDefaultUi(host: HTMLElement, canvas: any, edge: any | null): void {\n // Capture focus on the previous managed root BEFORE tearing it down, so a\n // reactive re-stamp triggered while the user is typing doesn't blur the\n // focused input.\n const previousRoot = host.querySelector<HTMLElement>(\n ':scope > [data-schema-default-ui-root]',\n );\n const captured = captureStampFocus(previousRoot);\n\n clearStampedUi(host);\n const root = createStampRoot(host);\n\n if (!edge) {\n const empty = document.createElement('div');\n empty.setAttribute('data-schema-inspector-empty', '');\n empty.textContent = 'No edge selected.';\n root.appendChild(empty);\n restoreStampFocus(root, captured);\n return;\n }\n\n const labelWrap = document.createElement('label');\n labelWrap.textContent = 'label ';\n const labelInput = document.createElement('input');\n labelInput.setAttribute('data-field', 'label');\n labelInput.value = String(edge.label ?? '');\n labelInput.addEventListener('input', () => {\n edge.label = labelInput.value;\n });\n labelWrap.appendChild(labelInput);\n root.appendChild(labelWrap);\n\n const deleteBtn = document.createElement('button');\n deleteBtn.type = 'button';\n deleteBtn.setAttribute('data-action', 'delete');\n deleteBtn.textContent = 'delete';\n deleteBtn.addEventListener('click', () => {\n if (typeof canvas.removeEdges === 'function') {\n canvas.removeEdges([edge.id]);\n } else {\n const idx = canvas.edges?.findIndex((e: any) => e.id === edge.id) ?? -1;\n if (idx !== -1) {\n canvas.edges.splice(idx, 1);\n }\n }\n });\n root.appendChild(deleteBtn);\n\n restoreStampFocus(root, captured);\n}\n","// ============================================================================\n// x-schema-reorderable Directive\n//\n// Makes a `.flow-schema-row` draggable within its parent `.flow-schema-body`\n// to reorder fields. On drop, commits via `canvas.reorderFields(nodeId,\n// newOrder)`.\n//\n// Opt-in: auto-stamped on rows by `x-flow-schema` when\n// `canvas.rowsReorderable: true`, or manually stamped by consumers writing\n// custom node templates.\n//\n// Conflict with row-select: both directives listen for pointerdown-derived\n// events. This directive only COMMITS a reorder when the cursor moves more\n// than `DRAG_THRESHOLD_PX` vertically; below that it behaves as a click and\n// row-select wins. On a successful drag, the following click event is\n// swallowed (capture-phase listener) so the row isn't selected.\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\n\n/** Pixels of vertical movement before we consider the interaction a drag. */\nconst DRAG_THRESHOLD_PX = 4;\n\nexport function registerSchemaReorderableDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-reorderable',\n (el, _spec, { cleanup }) => {\n const row = el as HTMLElement;\n row.classList.add('flow-schema-reorderable');\n // Prevent browsers from stealing the pointer stream for scroll/zoom\n // gestures during a drag.\n row.style.touchAction = 'none';\n\n // Live drag state — kept in closure so listeners share state.\n let dragging = false;\n let dragged = false;\n let startY = 0;\n let startIndex = 0;\n let currentDropIndex = 0;\n let activePointerId: number | null = null;\n\n /** All sibling rows that participate in the reorder (includes self). */\n const siblingRows = (): HTMLElement[] => {\n const parent = row.parentElement;\n if (!parent) return [];\n return Array.from(\n parent.querySelectorAll(':scope > .flow-schema-row'),\n ) as HTMLElement[];\n };\n\n /** Remove all drop-target classes from sibling rows. */\n const clearDropTargets = (): void => {\n for (const r of siblingRows()) {\n r.classList.remove('flow-schema-row-drop-target');\n }\n };\n\n /**\n * Determine the drop-target index given the current pointer Y.\n *\n * Semantics: the returned index is an insertion index in the\n * \"already-removed\" array — i.e. after splicing the dragging row\n * out of the field list, `newOrder.splice(dropIndex, 0, moved)`\n * yields the final order. It equals the number of OTHER rows\n * whose midline sits above the cursor.\n *\n * This produces intuitive no-op behaviour: a small nudge within\n * the dragging row's original bounds leaves dropIndex equal to\n * startIndex.\n */\n const computeDropIndex = (clientY: number): number => {\n const parent = row.parentElement;\n if (!parent) return startIndex;\n const others = Array.from(\n parent.querySelectorAll(':scope > .flow-schema-row'),\n ).filter((r) => r !== row) as HTMLElement[];\n if (others.length === 0) return startIndex;\n\n let aboveCount = 0;\n for (const sib of others) {\n const rect = sib.getBoundingClientRect();\n const mid = rect.top + rect.height / 2;\n if (mid < clientY) aboveCount++;\n }\n return aboveCount;\n };\n\n const updateDropTargetClass = (dropIndex: number): void => {\n clearDropTargets();\n const all = siblingRows();\n // Visual hint: highlight the neighbour the dragging row\n // would swap with at the current drop slot. We map the\n // remove-then-insert index back to the nearest sibling.\n let targetIdx = dropIndex;\n if (dropIndex >= startIndex) targetIdx = dropIndex + 1;\n const target = all[targetIdx] ?? all[dropIndex];\n if (target && target !== row) {\n target.classList.add('flow-schema-row-drop-target');\n }\n };\n\n const resetRow = (): void => {\n row.style.transform = '';\n row.classList.remove('flow-schema-row-dragging');\n clearDropTargets();\n };\n\n const onPointerDown = (e: PointerEvent): void => {\n if (dragging) return;\n // Only primary button / pen / touch.\n if (e.button !== undefined && e.button !== 0) return;\n\n dragging = true;\n dragged = false;\n startY = e.clientY;\n activePointerId = e.pointerId ?? null;\n\n const all = siblingRows();\n startIndex = all.indexOf(row);\n currentDropIndex = startIndex;\n\n row.classList.add('flow-schema-row-dragging');\n\n // Try to capture the pointer so subsequent pointermove/up fire\n // on the row even if the cursor leaves it. In jsdom this may\n // not be supported — fall back to document-level listeners in\n // that case.\n try {\n if (activePointerId !== null && typeof row.setPointerCapture === 'function') {\n row.setPointerCapture(activePointerId);\n }\n } catch {\n /* capture not supported — rely on document listeners */\n }\n\n document.addEventListener('pointermove', onPointerMove);\n document.addEventListener('pointerup', onPointerUp);\n document.addEventListener('pointercancel', onPointerUp);\n };\n\n const onPointerMove = (e: PointerEvent): void => {\n if (!dragging) return;\n const deltaY = e.clientY - startY;\n\n if (!dragged && Math.abs(deltaY) > DRAG_THRESHOLD_PX) {\n dragged = true;\n }\n\n row.style.transform = `translateY(${deltaY}px)`;\n\n if (dragged) {\n currentDropIndex = computeDropIndex(e.clientY);\n updateDropTargetClass(currentDropIndex);\n }\n };\n\n const onPointerUp = (e: PointerEvent): void => {\n if (!dragging) return;\n const wasDragged = dragged;\n const dropIndex = currentDropIndex;\n const startIdx = startIndex;\n\n // Release pointer capture if we took it.\n try {\n if (\n activePointerId !== null\n && typeof row.releasePointerCapture === 'function'\n && typeof row.hasPointerCapture === 'function'\n && row.hasPointerCapture(activePointerId)\n ) {\n row.releasePointerCapture(activePointerId);\n }\n } catch {\n /* ignore */\n }\n\n document.removeEventListener('pointermove', onPointerMove);\n document.removeEventListener('pointerup', onPointerUp);\n document.removeEventListener('pointercancel', onPointerUp);\n\n dragging = false;\n activePointerId = null;\n resetRow();\n\n if (!wasDragged) {\n // A click — let row-select handle it.\n return;\n }\n\n // Suppress the click that browsers fire after pointerup. We\n // add a capture-phase listener that swallows the next click\n // event on this row (or its descendants). Self-removes after\n // one tick in case no click arrives.\n const suppressClick = (ev: Event): void => {\n ev.stopImmediatePropagation();\n ev.stopPropagation();\n ev.preventDefault();\n };\n row.addEventListener('click', suppressClick, { capture: true, once: true });\n // Belt-and-suspenders cleanup in case no click fires.\n setTimeout(() => {\n row.removeEventListener('click', suppressClick, { capture: true } as any);\n }, 0);\n\n // Resolve nodeId + canvas from the DOM tree.\n const nodeEl = row.closest('[data-flow-node-id]') as HTMLElement | null;\n const nodeId = nodeEl?.getAttribute('data-flow-node-id') ?? null;\n if (!nodeId) return;\n\n const canvasEl = row.closest('.flow-container') as HTMLElement | null;\n if (!canvasEl) return;\n\n let canvas: any;\n try {\n canvas = Alpine.$data(canvasEl);\n } catch {\n return;\n }\n if (!canvas || typeof canvas.reorderFields !== 'function') return;\n\n // Read the current field order off the canvas node.\n const node = (canvas.nodes ?? []).find((n: any) => n?.id === nodeId);\n const fields: any[] = node?.data?.fields ?? [];\n if (!Array.isArray(fields) || fields.length < 2) return;\n\n const names = fields.map((f: any) => f.name);\n if (startIdx < 0 || startIdx >= names.length) return;\n\n const [moved] = names.splice(startIdx, 1);\n // Clamp dropIndex into the post-removal array's valid range.\n const target = Math.max(0, Math.min(dropIndex, names.length));\n names.splice(target, 0, moved);\n\n // If the order is unchanged, skip the commit — lets\n // canvas.reorderFields stay a pure \"real change\" event.\n const unchanged = names.every(\n (name, i) => fields[i]?.name === name,\n );\n if (unchanged) return;\n\n canvas.reorderFields(nodeId, names);\n\n // `e` (pointerup) isn't a click; we've already installed a\n // capture-phase one-shot click listener above to swallow the\n // synthetic click that browsers fire after pointerup.\n void e;\n };\n\n row.addEventListener('pointerdown', onPointerDown);\n\n cleanup(() => {\n try {\n row.removeEventListener('pointerdown', onPointerDown);\n if (typeof document !== 'undefined') {\n document.removeEventListener('pointermove', onPointerMove);\n document.removeEventListener('pointerup', onPointerUp);\n document.removeEventListener('pointercancel', onPointerUp);\n }\n row.classList.remove('flow-schema-reorderable');\n row.classList.remove('flow-schema-row-dragging');\n clearDropTargets();\n row.style.transform = '';\n row.style.touchAction = '';\n } catch {\n /* environment may be torn down (jsdom) */\n }\n });\n },\n );\n}\n","// ============================================================================\n// x-schema-keyboard-nav Directive\n//\n// Makes a `.flow-schema-row` focusable and keyboard-navigable:\n// - Arrow Up / Down : move focus to previous / next row within the same node\n// - Tab / Shift+Tab : move focus to the first / last row of the next /\n// previous node. When at the outermost row with no\n// neighbor, default tab behaviour is preserved so focus\n// can exit the canvas naturally.\n// - Enter / Space : trigger row selection (reuses the row's own click\n// handler so `x-flow-row-select` remains the single\n// authoritative selection path).\n// - Escape : blur the focused row.\n//\n// The directive also stamps `tabindex=\"0\"`, `role=\"row\"`, and a reactive\n// `aria-label` so screen readers can announce the field name and type.\n//\n// Opt-in: auto-stamped on rows by `x-flow-schema` when\n// `canvas._config.keyboardConnect: true`. The keyboard-connect flag is reused\n// intentionally — consumers that opt into keyboard-driven connect almost\n// always also want keyboard-driven field focus, so bundling them keeps the\n// opt-in surface small.\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\n\n/**\n * Sibling rows within the same `.flow-schema-body` — used for ArrowUp /\n * ArrowDown. Uses `:scope > .flow-schema-row` so nested schema tables (a\n * future-proofing concern) do not leak their rows into the iteration.\n */\nfunction siblingRowsOf(row: HTMLElement): HTMLElement[] {\n const body = row.parentElement;\n if (!body) return [];\n return Array.from(\n body.querySelectorAll(':scope > .flow-schema-row'),\n ) as HTMLElement[];\n}\n\n/**\n * Move focus to the row `direction` slots away (±1) within the same node.\n * No-op when the target slot is out of range — we deliberately do not wrap\n * so the focus indicator stays predictable during rapid arrow presses.\n */\nfunction moveWithinNode(row: HTMLElement, direction: 1 | -1): void {\n const rows = siblingRowsOf(row);\n const idx = rows.indexOf(row);\n if (idx === -1) return;\n const next = rows[idx + direction];\n if (next) next.focus();\n}\n\n/**\n * Move focus to the first (direction=1) or last (direction=-1) row of the\n * sibling node. Returns true when focus moved — the caller then calls\n * preventDefault on the Tab event. When false, we let the browser handle Tab\n * naturally so focus can leave the canvas.\n *\n * Node discovery walks up to the closest `.flow-container` (the canvas root)\n * and collects every `[data-flow-node-id]` descendant in document order. This\n * mirrors the selector used by `x-schema-reorderable` for nodeId resolution.\n */\nfunction moveBetweenNodes(row: HTMLElement, direction: 1 | -1): boolean {\n const currentNode = row.closest('[data-flow-node-id]') as HTMLElement | null;\n if (!currentNode) return false;\n const container = row.closest('.flow-container') as HTMLElement | null;\n if (!container) return false;\n const allNodes = Array.from(\n container.querySelectorAll('[data-flow-node-id]'),\n ) as HTMLElement[];\n const idx = allNodes.indexOf(currentNode);\n if (idx === -1) return false;\n const next = allNodes[idx + direction];\n if (!next) return false;\n const targetRow = (\n direction === 1\n ? next.querySelector('.flow-schema-row')\n : (() => {\n const rows = next.querySelectorAll('.flow-schema-row');\n return rows.length > 0 ? rows[rows.length - 1] : null;\n })()\n ) as HTMLElement | null;\n if (!targetRow) return false;\n targetRow.focus();\n return true;\n}\n\n/**\n * Trigger selection by dispatching a click on the row. `x-flow-row-select`\n * already listens for clicks and encapsulates single-vs-shift selection logic\n * — reusing its handler keeps this directive a thin a11y shell with no\n * duplicate selection logic to drift out of sync.\n */\nfunction selectRow(row: HTMLElement): void {\n row.click();\n}\n\nexport function registerSchemaKeyboardNavDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-keyboard-nav',\n (el, _spec, { effect, cleanup }) => {\n const row = el as HTMLElement;\n row.setAttribute('tabindex', '0');\n row.setAttribute('role', 'row');\n\n // Reactive aria-label. We read the field name from the row's\n // data-flow-schema-field attribute (stamped by x-flow-schema) and\n // the type from the rendered `.flow-schema-row-type` span. Running\n // this inside `effect` means Alpine re-invokes it on any reactive\n // mutation that touched these reads — but since these are DOM\n // reads, not reactive state reads, the effect fires once at init.\n // That's fine: x-flow-schema owns the row contents and re-stamps\n // them on field changes, which re-binds this directive and gives\n // us a fresh aria-label read.\n effect(() => {\n const fieldName = row.dataset.flowSchemaField ?? '';\n const typeEl = row.querySelector('.flow-schema-row-type');\n const fieldType = typeEl?.textContent ?? '';\n row.setAttribute(\n 'aria-label',\n `${fieldName}${fieldType ? ' (' + fieldType + ')' : ''}`,\n );\n });\n\n const onKey = (e: KeyboardEvent): void => {\n const key = e.key;\n if (key === 'ArrowDown' || key === 'ArrowUp') {\n e.preventDefault();\n e.stopPropagation();\n moveWithinNode(row, key === 'ArrowDown' ? 1 : -1);\n return;\n }\n if (key === 'Tab') {\n // Intercept Tab so focus jumps between sibling schema\n // nodes instead of walking through every focusable child\n // (handles, inputs, etc.). preventDefault only when we\n // actually moved focus — otherwise the browser's default\n // tab-out lets the user escape the canvas.\n if (moveBetweenNodes(row, e.shiftKey ? -1 : 1)) {\n e.preventDefault();\n }\n return;\n }\n if (key === 'Enter' || key === ' ') {\n e.preventDefault();\n selectRow(row);\n return;\n }\n if (key === 'Escape') {\n row.blur();\n return;\n }\n };\n\n row.addEventListener('keydown', onKey);\n\n cleanup(() => {\n try {\n row.removeEventListener('keydown', onKey);\n row.removeAttribute('tabindex');\n row.removeAttribute('role');\n row.removeAttribute('aria-label');\n } catch {\n /* environment may be torn down (jsdom) */\n }\n });\n },\n );\n}\n","// ============================================================================\n// alpineflow/schema — Subpath Addon\n//\n// Import: `import Schema from '@getartisanflow/alpineflow/schema'`\n// Register: `Alpine.plugin(Schema)`\n//\n// Capabilities are added in Tasks 9–12:\n// - Field CRUD with edge cascade (Task 9) ← landed\n// - inferReferences() (Task 10)\n// - schemaToJSON / schemaFromJSON (Task 11)\n// - Three-scope inspector scaffold (Task 12)\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\nimport { registerAddon } from '../core/registry';\nimport { addField, renameField, removeField, reorderFields } from './field-ops';\nimport type {\n AddFieldResult,\n RenameFieldOpResult,\n RemoveFieldOpResult,\n ReorderFieldsOpResult,\n} from './field-ops';\nimport { inferReferences } from './references';\nimport { schemaToJSON, schemaFromJSON } from './serialization';\nimport { validateSchema } from './validate';\nimport { diffSchemas } from './diff';\nimport { toDot } from './dot';\nimport { schemaLayout } from './layout';\nimport { attachSchemaHistory } from './history';\nimport { registerNodeInspectorDirective } from './inspector/node-inspector';\nimport { registerRowInspectorDirective } from './inspector/row-inspector';\nimport { registerEdgeInspectorDirective } from './inspector/edge-inspector';\nimport { registerSchemaReorderableDirective } from './reorderable';\nimport { registerSchemaKeyboardNavDirective } from './keyboard-nav';\nimport type {\n DotExportOptions,\n SchemaLayoutOptions,\n SchemaGraphJSON,\n SchemaValidationResult,\n SchemaDiff,\n DiffOptions,\n ReferenceSuggestion,\n} from './types';\nimport type { FlowSchemaField } from '../core/types';\n\nexport * from './types';\nexport * from './validate';\nexport * from './diff';\nexport * from './dot';\nexport * from './layout';\nexport * from './history';\nexport { addField, renameField, removeField, reorderFields, inferReferences, schemaToJSON, schemaFromJSON, validateSchema, diffSchemas, toDot, schemaLayout, attachSchemaHistory };\nexport { registerNodeInspectorDirective, registerRowInspectorDirective, registerEdgeInspectorDirective, registerSchemaReorderableDirective, registerSchemaKeyboardNavDirective };\nexport type { AddFieldResult, RenameFieldOpResult, RemoveFieldOpResult, ReorderFieldsOpResult } from './field-ops';\n\nexport default function registerSchemaAddon(Alpine: Alpine): void {\n // Register the three-scope inspector directives. Guarded so stub calls in\n // tests (passing `{}` as Alpine) don't throw — only wire up when a real\n // Alpine.directive hook is available.\n if (Alpine && typeof Alpine.directive === 'function') {\n registerNodeInspectorDirective(Alpine);\n registerRowInspectorDirective(Alpine);\n registerEdgeInspectorDirective(Alpine);\n registerSchemaReorderableDirective(Alpine);\n registerSchemaKeyboardNavDirective(Alpine);\n }\n\n registerAddon('schema', {\n setup(canvas: any) {\n // Use the canvas container as the DOM event target so listeners\n // bound via @schema-* attributes on the container fire naturally.\n if (!canvas.el && canvas._container) {\n canvas.el = canvas._container;\n }\n\n canvas.addField = function (nodeId: string, field: any) {\n return addField(this, nodeId, field);\n };\n canvas.renameField = function (nodeId: string, oldName: string, newName: string) {\n return renameField(this, nodeId, oldName, newName);\n };\n canvas.removeField = function (nodeId: string, fieldName: string) {\n return removeField(this, nodeId, fieldName);\n };\n canvas.reorderFields = function (nodeId: string, order: string[]) {\n return reorderFields(this, nodeId, order);\n };\n canvas.inferReferences = function () {\n return inferReferences(this.nodes ?? []);\n };\n canvas.schemaToJSON = function () {\n return schemaToJSON(this);\n };\n canvas.schemaFromJSON = function (json: any) {\n return schemaFromJSON(this, json);\n };\n canvas.validateSchema = function () {\n return validateSchema(this);\n };\n canvas.diffSchemas = function (before: any, after: any, opts?: any) {\n return diffSchemas(before, after, opts);\n };\n canvas.toDot = function (opts?: DotExportOptions) {\n return toDot(this, opts);\n };\n canvas.schemaLayout = function (opts?: SchemaLayoutOptions) {\n return schemaLayout(this, opts);\n };\n },\n });\n}\n\n// ============================================================================\n// Type augmentation — declare the methods `setup()` attaches at runtime on the\n// shared `CanvasContext` interface, so consumers get typed access without\n// importing the standalone `addField(canvas, …)` helpers and casting.\n//\n// Scoped to this entry's emitted types: the augmentation only reaches a program\n// that imports `@getartisanflow/alpineflow/schema`. Purely type-level — erased\n// from the JS bundle. Signatures mirror the wrapped standalone functions above.\n// ============================================================================\ndeclare module '../plugin/data/canvas-context' {\n interface CanvasContext {\n /** Append a field to a schema node. Rejects invalid/duplicate names silently. _(schema addon)_ */\n addField(nodeId: string, field: FlowSchemaField): AddFieldResult;\n /** Rename a field, cascading the change onto edges that reference it. _(schema addon)_ */\n renameField(nodeId: string, oldName: string, newName: string): RenameFieldOpResult;\n /** Remove a field, dropping edges that referenced it. _(schema addon)_ */\n removeField(nodeId: string, fieldName: string): RemoveFieldOpResult;\n /** Reorder a node's fields to match `order` (a list of field names). _(schema addon)_ */\n reorderFields(nodeId: string, order: string[]): ReorderFieldsOpResult;\n /** Suggest reference edges inferred from `<stem>_id` field-name conventions. _(schema addon)_ */\n inferReferences(): ReferenceSuggestion[];\n /** Serialize the schema graph to a stable, versioned JSON shape. _(schema addon)_ */\n schemaToJSON(): SchemaGraphJSON;\n /** Merge a schema-graph JSON into the live canvas nodes/edges. _(schema addon)_ */\n schemaFromJSON(json: SchemaGraphJSON): void;\n /** Validate the schema graph (dangling edges, duplicate fields, cycles, …). _(schema addon)_ */\n validateSchema(): SchemaValidationResult;\n /** Compute a structured delta between two schema snapshots. _(schema addon)_ */\n diffSchemas(before: SchemaGraphJSON, after: SchemaGraphJSON, opts?: DiffOptions): SchemaDiff;\n /** Render the schema graph as a graphviz DOT string. _(schema addon)_ */\n toDot(opts?: DotExportOptions): string;\n /** Lay out schema nodes by their reference graph. _(schema addon)_ */\n schemaLayout(opts?: SchemaLayoutOptions): Promise<void>;\n }\n}\n"],"names":["REGISTRY_KEY","getRegistry","registerAddon","name","value","cascadeEdgesOnRename","edges","nodeId","oldName","newName","cascadedIds","e","next","cascadeEdgesOnRemove","fieldName","droppedIds","touches","FIELD_NAME_RE","MAX_FIELD_NAME_LENGTH","isValidFieldName","dispatchSchema","canvas","type","detail","el","captured","win","onError","event","err","findNode","n","addField","field","node","f","renameField","fields","target","currentEdges","updatedEdges","updatedById","edge","upd","removeField","idx","dropSet","i","reorderFields","order","existingNames","orderNames","byName","reordered","inferReferences","nodes","byId","suggestions","stem","targetFields","toFieldName","jsonEqual","a","b","mergeEntitiesById","existing","incoming","opts","deleteMissing","existingById","merged","inc","cur","key","schemaToJSON","schemaFromJSON","json","incomingNodes","incomingEdges","mergedNodes","mergedEdges","hasCycle","adj","ensure","id","list","WHITE","GRAY","BLACK","color","start","stack","frame","neighbors","c","validateSchema","issues","nodeIds","dupNodeIds","seen","dup","edgeId","touched","safeNodes","snap","safeEdges","fieldsByName","map","diffSchemas","before","after","beforeNodes","afterNodes","beforeEdges","afterEdges","beforeNodeMap","afterNodeMap","rawAddedNodes","rawRemovedNodes","renamedNodes","consumedAddedNodes","consumedRemovedNodes","sigFor","removedId","removedNode","sig","candidates","addedId","addedNode","toId","addedNodes","removedNodes","pairs","r","fieldRenamesByAfterNodeId","hint","renameFromToTo","mapped","renamedFields","addedFields","removedFields","changedFieldTypes","beforeId","afterId","beforeNode","afterNode","beforeFields","afterFields","hints","consumedBefore","consumedAfter","oldField","newField","oldType","newType","beforeField","afterField","beforeEdgeIds","afterEdgeIds","addedEdges","removedEdges","fieldKey","k","DEFAULTS","escapeHTML","s","escapeQuoted","renderNode","o","label","colSpan","rows","cells","marker","renderEdge","source","sourcePort","targetPort","toDot","lines","DEFAULT_ORDER","schemaLayout","direction","nodeSpacing","rankSpacing","preferred","resolvePreferredOrder","swap","prepareEdgeSwap","algo","tryDagre","tryTree","applyGridLayout","pinned","original","inferred","suggestion","index","count","cols","cellWidth","cellHeight","col","row","x","y","TRACKED_EVENTS","attachSchemaHistory","limit","undoStack","redoStack","suspendDepth","batchDepth","batchEntrySnapshot","disposed","makeNoopHandle","evictOldest","pushDeduped","top","pushSnapshot","onEvent","applySnapshot","current","prev","fn","result","entry","lastInSet","set","last","parseRowId","rowId","dot","findCanvasScope","Alpine","ancestor","containers","findDefaultUiTemplate","clearStampedUi","createStampRoot","root","captureStampFocus","active","selectionStart","selectionEnd","escapeAttrValue","restoreStampFocus","candidate","registerNodeInspectorDirective","_spec","effect","cleanup","host","template","inspector","removeScope","stampNodeDefaultUi","previousRoot","empty","header","li","nameSpan","typeSpan","removeBtn","form","nameInput","registry","typeInput","select","option","input","addBtn","rawType","registerRowInspectorDirective","currentRow","currentField","patch","v","stampRowDefaultUi","missing","nameLabel","typeLabel","requiredLabel","requiredInput","registerEdgeInspectorDirective","currentEdge","stampEdgeDefaultUi","labelWrap","labelInput","deleteBtn","DRAG_THRESHOLD_PX","registerSchemaReorderableDirective","dragging","dragged","startY","startIndex","currentDropIndex","activePointerId","siblingRows","parent","clearDropTargets","computeDropIndex","clientY","others","aboveCount","sib","rect","updateDropTargetClass","dropIndex","all","targetIdx","resetRow","onPointerDown","onPointerMove","onPointerUp","deltaY","wasDragged","startIdx","suppressClick","ev","canvasEl","names","moved","siblingRowsOf","body","moveWithinNode","moveBetweenNodes","currentNode","container","allNodes","targetRow","selectRow","registerSchemaKeyboardNavDirective","fieldType","onKey","registerSchemaAddon"],"mappings":"AAaA,MAAMA,IAAe;AAEd,SAASC,KAAgC;AAC9C,SAAI,OAAO,aAAe,OAClB,WAAmBD,CAAY,MAClC,WAAmBA,CAAY,IAAI,oBAAI,IAAA,IAElC,WAAmBA,CAAY,yBAG9B,IAAA;AACb;AAEO,SAASE,GAAcC,GAAcC,GAAkB;AAC5D,EAAAH,KAAc,IAAIE,GAAMC,CAAK;AAC/B;ACCO,SAASC,GACZC,GACAC,GACAC,GACAC,GACsB;AACtB,QAAMC,IAAwB,CAAA;AAc9B,SAAO,EAAE,OAbOJ,EAAM,IAAI,CAACK,MAAM;AAC7B,QAAIC,IAAUD;AACd,WAAIA,EAAE,WAAWJ,KAAUI,EAAE,iBAAiBH,MAC1CI,IAAO,EAAE,GAAGA,GAAM,cAAcH,EAAA,IAEhCE,EAAE,WAAWJ,KAAUI,EAAE,iBAAiBH,MAC1CI,IAAO,EAAE,GAAGA,GAAM,cAAcH,EAAA,IA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"file":"alpineflow-schema.esm.js","sources":["../src/core/registry.ts","../src/schema/cascade.ts","../src/schema/field-ops.ts","../src/schema/references.ts","../src/core/deep-merge.ts","../src/schema/serialization.ts","../src/schema/validate.ts","../src/schema/diff.ts","../src/schema/dot.ts","../src/schema/layout.ts","../src/schema/history.ts","../src/core/translations.ts","../src/schema/inspector/shared.ts","../src/schema/inspector/node-inspector.ts","../src/schema/inspector/row-inspector.ts","../src/schema/inspector/edge-inspector.ts","../src/schema/reorderable.ts","../src/schema/keyboard-nav.ts","../src/schema/index.ts"],"sourcesContent":["/**\n * Addon registry — singleton via window global.\n *\n * When AlpineFlow core is loaded from one bundle (e.g., WireFlow's\n * alpineflow.bundle.esm.js) and addons are loaded from separate ESM\n * files, each bundle gets its own module scope. A module-scoped Map\n * would create disconnected registries — addons would register on\n * their copy, but the core would check its own empty copy.\n *\n * Using a window global ensures all bundles share one registry,\n * regardless of how they're loaded (CDN, npm, Vite, WireFlow bundle).\n */\n\nconst REGISTRY_KEY = '__alpineflow_registry__';\n\nexport function getRegistry(): Map<string, any> {\n if (typeof globalThis !== 'undefined') {\n if (!(globalThis as any)[REGISTRY_KEY]) {\n (globalThis as any)[REGISTRY_KEY] = new Map<string, any>();\n }\n return (globalThis as any)[REGISTRY_KEY];\n }\n // Fallback for environments without globalThis (shouldn't happen in modern runtimes)\n return new Map<string, any>();\n}\n\nexport function registerAddon(name: string, value: any): void {\n getRegistry().set(name, value);\n}\n\nexport function getAddon<T = any>(name: string): T | undefined {\n return getRegistry().get(name);\n}\n\n/** Remove a single addon by name. */\nexport function unregisterAddon(name: string): void {\n getRegistry().delete(name);\n}\n\n/** Test-only: clear all registered addons. */\nexport function _resetRegistry(): void {\n getRegistry().clear();\n}\n","// ============================================================================\n// alpineflow/schema — Edge cascade walker (internal helper)\n//\n// Pure functions that return NEW arrays. They do not mutate canvas state —\n// `field-ops.ts` is the only module that touches the live reactive arrays.\n// ============================================================================\n\nexport interface CascadeRenameResult<E> {\n edges: E[];\n cascadedIds: string[];\n}\n\nexport interface CascadeRemoveResult<E> {\n edges: E[];\n droppedIds: string[];\n}\n\ntype EdgeLike = {\n id: string;\n source: string;\n sourceHandle?: string | null;\n target: string;\n targetHandle?: string | null;\n};\n\n/**\n * Returns a new edge array where any edge touching (nodeId, oldName) has its\n * matching handle rewritten to newName. cascadedIds lists the edges that changed.\n */\nexport function cascadeEdgesOnRename<E extends EdgeLike>(\n edges: E[],\n nodeId: string,\n oldName: string,\n newName: string,\n): CascadeRenameResult<E> {\n const cascadedIds: string[] = [];\n const updated = edges.map((e) => {\n let next: E = e;\n if (e.source === nodeId && e.sourceHandle === oldName) {\n next = { ...next, sourceHandle: newName };\n }\n if (e.target === nodeId && e.targetHandle === oldName) {\n next = { ...next, targetHandle: newName };\n }\n if (next !== e) {\n cascadedIds.push(e.id);\n }\n return next;\n });\n return { edges: updated, cascadedIds };\n}\n\n/**\n * Returns a new edge array with every edge touching (nodeId, fieldName) removed.\n * droppedIds lists the edges that were filtered out.\n */\nexport function cascadeEdgesOnRemove<E extends EdgeLike>(\n edges: E[],\n nodeId: string,\n fieldName: string,\n): CascadeRemoveResult<E> {\n const droppedIds: string[] = [];\n const kept = edges.filter((e) => {\n const touches =\n (e.source === nodeId && e.sourceHandle === fieldName) ||\n (e.target === nodeId && e.targetHandle === fieldName);\n if (touches) {\n droppedIds.push(e.id);\n }\n return !touches;\n });\n return { edges: kept, droppedIds };\n}\n","// ============================================================================\n// alpineflow/schema — Field CRUD helpers\n//\n// Each helper mutates the live `canvas.nodes` / `canvas.edges` arrays through\n// their Alpine reactive proxies — render updates propagate automatically.\n// Helpers return a status object ({applied, reason, ...}) and dispatch\n// schema:* DOM events on `canvas.el` so consumers can listen without having\n// to wrap the calls.\n//\n// Validation failures (invalid name, duplicate, non-existent node/field, etc.)\n// fail silently by returning {applied: false, reason: ...} — no throws.\n// ============================================================================\n\nimport type { FlowSchemaField } from '../core/types';\nimport { cascadeEdgesOnRename, cascadeEdgesOnRemove } from './cascade';\n\n/** `snake_case` identifier: starts lowercase, letters/digits/underscores only. */\nconst FIELD_NAME_RE = /^[a-z][a-z0-9_]*$/;\nconst MAX_FIELD_NAME_LENGTH = 40;\n\nfunction isValidFieldName(name: string): boolean {\n return typeof name === 'string' && name.length <= MAX_FIELD_NAME_LENGTH && FIELD_NAME_RE.test(name);\n}\n\nfunction dispatchSchema(canvas: any, type: string, detail: Record<string, any>): void {\n const el: EventTarget | undefined = canvas?.el ?? canvas?._container;\n if (!el || typeof (el as any).dispatchEvent !== 'function') {\n return;\n }\n // Listener atomicity: a throwing listener must not abort this function\n // mid-mutation. State has already been updated; we intentionally do NOT\n // roll back, because a partial rollback would leave a different half-state.\n //\n // Per DOM spec, most environments catch listener exceptions inside\n // dispatchEvent and surface them via `window.onerror` (or ErrorEvent). We\n // install a one-shot capturing error listener so we see the throw, log it,\n // and prevent it from bubbling to a noisy default handler. We also wrap\n // dispatchEvent itself in try/catch for engines that propagate directly.\n const captured: unknown[] = [];\n const win: any = typeof window !== 'undefined' ? window : undefined;\n const onError = (event: ErrorEvent) => {\n captured.push(event.error ?? event.message);\n event.preventDefault();\n };\n if (win && typeof win.addEventListener === 'function') {\n win.addEventListener('error', onError, true);\n }\n try {\n el.dispatchEvent(new CustomEvent(type, { detail, bubbles: true }));\n } catch (err) {\n captured.push(err);\n } finally {\n if (win && typeof win.removeEventListener === 'function') {\n win.removeEventListener('error', onError, true);\n }\n }\n for (const err of captured) {\n console.error('[alpineflow/schema] listener threw while handling', type, err);\n }\n}\n\nfunction findNode(canvas: any, nodeId: string): any | null {\n return canvas?.nodes?.find((n: any) => n.id === nodeId) ?? null;\n}\n\nexport interface AddFieldResult {\n applied: boolean;\n reason?: string;\n}\n\nexport interface RenameFieldOpResult {\n applied: boolean;\n reason?: string;\n cascadedEdgeIds: string[];\n}\n\nexport interface RemoveFieldOpResult {\n applied: boolean;\n reason?: string;\n droppedEdgeIds: string[];\n}\n\nexport interface ReorderFieldsOpResult {\n applied: boolean;\n reason?: string;\n}\n\n/**\n * Append a new field to node.data.fields. Rejects invalid names, duplicates,\n * and missing nodes silently. Dispatches `schema:field-added` on success.\n */\nexport function addField(canvas: any, nodeId: string, field: FlowSchemaField & { [k: string]: any }): AddFieldResult {\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node' };\n }\n if (!isValidFieldName(field?.name)) {\n return { applied: false, reason: 'invalid-name' };\n }\n if (!node.data) {\n node.data = { label: nodeId, fields: [] };\n }\n const fields = node.data.fields ?? [];\n if (fields.some((f: any) => f.name === field.name)) {\n return { applied: false, reason: 'duplicate' };\n }\n\n // Push into the live reactive array so Alpine re-renders the node.\n if (!Array.isArray(node.data.fields)) {\n node.data.fields = [];\n }\n node.data.fields.push({ ...field });\n\n dispatchSchema(canvas, 'schema:field-added', { nodeId, field: { ...field } });\n return { applied: true };\n}\n\n/**\n * Rename a field. Cascades rewriting to every edge whose (source, sourceHandle)\n * or (target, targetHandle) touches (nodeId, oldName). Dispatches\n * `schema:field-renamed` and (if any edges changed) `schema:edges-cascaded`.\n */\nexport function renameField(canvas: any, nodeId: string, oldName: string, newName: string): RenameFieldOpResult {\n if (oldName === newName) {\n return { applied: false, reason: 'unchanged', cascadedEdgeIds: [] };\n }\n if (!isValidFieldName(newName)) {\n return { applied: false, reason: 'invalid-name', cascadedEdgeIds: [] };\n }\n\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node', cascadedEdgeIds: [] };\n }\n const fields: any[] = node.data?.fields ?? [];\n const target = fields.find((f: any) => f.name === oldName);\n if (!target) {\n return { applied: false, reason: 'no-field', cascadedEdgeIds: [] };\n }\n if (fields.some((f: any) => f.name === newName)) {\n return { applied: false, reason: 'duplicate', cascadedEdgeIds: [] };\n }\n\n // Rename in place — mutating the reactive object keeps any bindings alive.\n target.name = newName;\n\n // Cascade: mutate the affected edge objects IN PLACE so their live Alpine\n // scopes stay attached. cascadeEdgesOnRename returns NEW objects for\n // cascaded edges; splicing those into the array would orphan every cascaded\n // edge's scope and touch every reactive index. Copy just the changed handles\n // onto the existing objects instead.\n const currentEdges = canvas.edges ?? [];\n const { edges: updatedEdges, cascadedIds } = cascadeEdgesOnRename(currentEdges, nodeId, oldName, newName);\n if (cascadedIds.length > 0) {\n const updatedById = new Map(updatedEdges.map((e: any) => [e.id, e]));\n for (const edge of canvas.edges) {\n const upd = updatedById.get(edge.id);\n if (!upd || upd === edge) continue;\n if (edge.sourceHandle !== upd.sourceHandle) edge.sourceHandle = upd.sourceHandle;\n if (edge.targetHandle !== upd.targetHandle) edge.targetHandle = upd.targetHandle;\n }\n }\n\n dispatchSchema(canvas, 'schema:field-renamed', {\n nodeId,\n oldName,\n newName,\n cascadedEdgeIds: cascadedIds,\n });\n if (cascadedIds.length > 0) {\n dispatchSchema(canvas, 'schema:edges-cascaded', {\n nodeId,\n fieldName: newName,\n edgeIds: cascadedIds,\n operation: 'rename',\n });\n }\n\n return { applied: true, cascadedEdgeIds: cascadedIds };\n}\n\n/**\n * Remove a field from a node. Cascade-drops every edge whose handle references\n * it. Dispatches `schema:field-removed` and (if any edges dropped)\n * `schema:edges-cascaded`.\n */\nexport function removeField(canvas: any, nodeId: string, fieldName: string): RemoveFieldOpResult {\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node', droppedEdgeIds: [] };\n }\n const fields: any[] = node.data?.fields ?? [];\n const idx = fields.findIndex((f: any) => f.name === fieldName);\n if (idx === -1) {\n return { applied: false, reason: 'no-field', droppedEdgeIds: [] };\n }\n\n // Splice the reactive fields array in place.\n node.data.fields.splice(idx, 1);\n\n // Drop only the affected edges in place (rather than replacing the whole\n // array), and rebuild the edge map so getEdge no longer returns the dropped\n // edges — the previous full-array splice left _edgeMap stale.\n const currentEdges = canvas.edges ?? [];\n const { droppedIds } = cascadeEdgesOnRemove(currentEdges, nodeId, fieldName);\n if (droppedIds.length > 0) {\n const dropSet = new Set(droppedIds);\n for (let i = canvas.edges.length - 1; i >= 0; i--) {\n if (dropSet.has(canvas.edges[i].id)) canvas.edges.splice(i, 1);\n }\n canvas._rebuildEdgeMap?.();\n }\n\n dispatchSchema(canvas, 'schema:field-removed', {\n nodeId,\n fieldName,\n droppedEdgeIds: droppedIds,\n });\n if (droppedIds.length > 0) {\n dispatchSchema(canvas, 'schema:edges-cascaded', {\n nodeId,\n fieldName,\n edgeIds: droppedIds,\n operation: 'remove',\n });\n }\n\n return { applied: true, droppedEdgeIds: droppedIds };\n}\n\n/**\n * Reorder fields on a node to match the supplied name array. The array must\n * be a permutation of the existing field names — otherwise `mismatch`.\n */\nexport function reorderFields(canvas: any, nodeId: string, order: string[]): ReorderFieldsOpResult {\n if (!Array.isArray(order)) {\n return { applied: false, reason: 'mismatch' };\n }\n // Reject duplicate names in the supplied order explicitly — don't rely on\n // set-size comparison below, which fails open if node.data.fields somehow\n // already contains duplicates.\n if (new Set(order).size !== order.length) {\n return { applied: false, reason: 'mismatch' };\n }\n\n const node = findNode(canvas, nodeId);\n if (!node) {\n return { applied: false, reason: 'no-node' };\n }\n const fields: any[] = node.data?.fields ?? [];\n\n if (order.length !== fields.length) {\n return { applied: false, reason: 'mismatch' };\n }\n const existingNames = new Set(fields.map((f: any) => f.name));\n const orderNames = new Set(order);\n if (existingNames.size !== orderNames.size) {\n return { applied: false, reason: 'mismatch' };\n }\n for (const name of order) {\n if (!existingNames.has(name)) {\n return { applied: false, reason: 'mismatch' };\n }\n }\n\n const byName: Record<string, any> = Object.create(null);\n for (const f of fields) {\n byName[f.name] = f;\n }\n const reordered = order.map((name) => byName[name]);\n node.data.fields.splice(0, node.data.fields.length, ...reordered);\n\n return { applied: true };\n}\n","// ============================================================================\n// alpineflow/schema — Reference inference\n//\n// Pure helper: scans node field names for the `<stem>_id` pattern and, when\n// the stem exactly matches another node's id, emits a ReferenceSuggestion.\n// No canvas mutation, no events, no self-references. Consumers decide whether\n// to turn suggestions into real edges.\n// ============================================================================\n\nimport type { ReferenceSuggestion } from './types';\n\ninterface NodeLike {\n id: string;\n data?: {\n fields?: Array<{ name: string; key?: string }>;\n };\n}\n\n/**\n * Pattern-match `_id`-suffixed field names to node ids, yielding suggested\n * reference edges. Conservative: only emits when the stem is an exact node id\n * match. Consumers pick what to apply.\n */\nexport function inferReferences(nodes: NodeLike[]): ReferenceSuggestion[] {\n const byId = new Map<string, NodeLike>();\n for (const node of nodes) {\n byId.set(node.id, node);\n }\n\n const suggestions: ReferenceSuggestion[] = [];\n\n for (const node of nodes) {\n const fields = node.data?.fields ?? [];\n for (const field of fields) {\n if (typeof field?.name !== 'string') {\n continue;\n }\n if (!field.name.endsWith('_id')) {\n continue;\n }\n\n const stem = field.name.slice(0, -3);\n if (!stem) {\n continue;\n }\n\n const target = byId.get(stem);\n if (!target) {\n continue;\n }\n if (target.id === node.id) {\n continue; // no self-refs\n }\n\n const targetFields = target.data?.fields ?? [];\n const primary = targetFields.find((f) => f.key === 'primary');\n const toFieldName = primary?.name ?? targetFields[0]?.name ?? 'id';\n\n suggestions.push({\n fromNodeId: node.id,\n fromFieldName: field.name,\n toNodeId: target.id,\n toFieldName,\n confidence: 'exact',\n });\n }\n }\n\n return suggestions;\n}\n","/**\n * Deep-merge `source` into `target` in place.\n *\n * Rules:\n * - Objects are recursively merged (keys added/overwritten, unmentioned keys preserved).\n * - Arrays are replaced, not merged.\n * - `null` explicitly removes a key.\n * - `undefined` values are ignored (key is not touched).\n */\nexport function deepMerge<T extends Record<string, any>>(\n target: T,\n source: Record<string, any>,\n): T {\n for (const key of Object.keys(source)) {\n // Guard against prototype pollution\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;\n\n const val = source[key];\n\n // undefined → skip\n if (val === undefined) continue;\n\n // null → delete key\n if (val === null) {\n delete (target as any)[key];\n continue;\n }\n\n // Arrays → replace (not merge)\n if (Array.isArray(val)) {\n (target as any)[key] = [...val];\n continue;\n }\n\n // Plain objects → recurse\n if (typeof val === 'object' && val.constructor === Object) {\n if (\n typeof (target as any)[key] !== 'object' ||\n (target as any)[key] === null ||\n Array.isArray((target as any)[key])\n ) {\n (target as any)[key] = {};\n }\n deepMerge((target as any)[key], val);\n continue;\n }\n\n // Primitives → overwrite\n (target as any)[key] = val;\n }\n\n return target;\n}\n\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return a === b;\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Merge `incoming` entities into `existing` by id, PRESERVING the original\n * object references for ids present in both. Property writes are skipped when\n * deep-equal, so Alpine effects watching those objects only re-run for real\n * changes. Returns the merged list in `incoming` order.\n */\nexport function mergeEntitiesById<T extends { id: string }>(\n existing: T[],\n incoming: T[],\n opts: { deleteMissing?: boolean } = {},\n): T[] {\n const deleteMissing = opts.deleteMissing ?? true;\n const existingById = new Map(existing.map((e) => [e.id, e]));\n const merged: T[] = [];\n for (const inc of incoming) {\n const cur = existingById.get(inc.id);\n if (!cur) {\n merged.push(inc);\n continue;\n }\n if (deleteMissing) {\n for (const key of Object.keys(cur)) {\n if (key !== 'id' && !(key in inc)) delete (cur as Record<string, unknown>)[key];\n }\n }\n for (const [key, value] of Object.entries(inc)) {\n // Guard against prototype pollution (mirrors deepMerge): a bracket\n // assignment to `__proto__` would invoke the prototype setter.\n if (key === 'id' || key === '__proto__' || key === 'constructor' || key === 'prototype') {\n continue;\n }\n if (!jsonEqual((cur as Record<string, unknown>)[key], value)) {\n (cur as Record<string, unknown>)[key] = value;\n }\n }\n merged.push(cur);\n }\n return merged;\n}\n","import type { SchemaGraphJSON } from './types';\nimport { mergeEntitiesById } from '../core/deep-merge';\n\n/**\n * Export schema graph as a stable JSON shape. Strips internal underscore-prefixed\n * flags and only keeps the documented public fields.\n */\nexport function schemaToJSON(canvas: {\n nodes: Array<any>;\n edges: Array<any>;\n}): SchemaGraphJSON {\n const nodes = (canvas.nodes ?? []).map((n) => ({\n id: n.id,\n label: n.data?.label ?? '',\n fields: (n.data?.fields ?? []).map((f: any) => ({ ...f })),\n position: { x: n.position?.x ?? 0, y: n.position?.y ?? 0 },\n }));\n\n const edges = (canvas.edges ?? []).map((e) => {\n const edge: any = { id: e.id, source: e.source, target: e.target };\n if (e.sourceHandle !== undefined) {\n edge.sourceHandle = e.sourceHandle;\n }\n if (e.targetHandle !== undefined) {\n edge.targetHandle = e.targetHandle;\n }\n if (e.label !== undefined) {\n edge.label = e.label;\n }\n return edge;\n });\n\n return { version: 1, nodes, edges };\n}\n\n/**\n * Import a schema graph, MERGING it into the canvas's live nodes + edges arrays.\n *\n * Surviving ids keep their original object references (mutated to match the\n * imported schema), so `getNode`/`getEdge`, drag handlers, and edge effects all\n * stay bound to the live objects. `deleteMissing: false` because the schema JSON\n * is intentionally partial — non-schema props (`dimensions`, `type`, …) must\n * survive a round-trip. After merging, the node/edge lookup maps are rebuilt so\n * `getNode`/`getEdge` return the merged objects rather than orphaned ones.\n */\nexport function schemaFromJSON(\n canvas: {\n nodes: any[];\n edges: any[];\n _rebuildNodeMap?: () => void;\n _rebuildEdgeMap?: () => void;\n _layoutAnimTick?: number;\n },\n json: SchemaGraphJSON,\n): void {\n if (!json || typeof (json as any).version !== 'number') {\n throw new Error('[alpineflow/schema] schemaFromJSON: missing or invalid version');\n }\n if (json.version !== 1) {\n throw new Error(`[alpineflow/schema] schemaFromJSON: unsupported version ${json.version}`);\n }\n\n const incomingNodes = (json.nodes ?? []).map((n) => ({\n id: n.id,\n position: { x: n.position?.x ?? 0, y: n.position?.y ?? 0 },\n data: {\n label: n.label,\n fields: (n.fields ?? []).map((f) => ({ ...f })),\n },\n }));\n\n const incomingEdges = (json.edges ?? []).map((e) => {\n const edge: any = { id: e.id, source: e.source, target: e.target };\n if (e.sourceHandle !== undefined) {\n edge.sourceHandle = e.sourceHandle;\n }\n if (e.targetHandle !== undefined) {\n edge.targetHandle = e.targetHandle;\n }\n if (e.label !== undefined) {\n edge.label = e.label;\n }\n return edge;\n });\n\n const mergedNodes = mergeEntitiesById(canvas.nodes, incomingNodes, { deleteMissing: false });\n canvas.nodes.splice(0, canvas.nodes.length, ...mergedNodes);\n const mergedEdges = mergeEntitiesById(canvas.edges, incomingEdges, { deleteMissing: false });\n canvas.edges.splice(0, canvas.edges.length, ...mergedEdges);\n canvas._rebuildNodeMap?.();\n canvas._rebuildEdgeMap?.();\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => {\n canvas._layoutAnimTick = (canvas._layoutAnimTick ?? 0) + 1;\n });\n }\n}\n","// ============================================================================\n// alpineflow/schema — validateSchema\n//\n// Pure helper: inspects a canvas's nodes + edges and returns a structured list\n// of issues. No canvas mutation, no events, no throws. Safe on malformed input.\n//\n// Severities:\n// error — 'dangling-edge', 'duplicate-node-id', 'duplicate-field'\n// warning — 'missing-primary-key', 'disconnected-node', 'cycle'\n//\n// `valid` is true iff no error-severity issues are present.\n// ============================================================================\n\nimport type { SchemaValidationIssue, SchemaValidationResult } from './types';\n\ninterface NodeLike {\n id: string;\n data?: {\n fields?: Array<{ name: string; key?: string }>;\n };\n}\n\ninterface EdgeLike {\n id?: string;\n source: string;\n target: string;\n}\n\n/**\n * Iterative DFS cycle detection. Returns true as soon as any directed cycle is\n * found. Deterministic and terminating — handles self-loops, parallel edges,\n * and multi-component graphs without infinite loops.\n */\nfunction hasCycle(nodes: NodeLike[], edges: EdgeLike[]): boolean {\n // Self-loop shortcut\n for (const e of edges) {\n if (e && typeof e.source === 'string' && e.source === e.target) {\n return true;\n }\n }\n\n // Build adjacency list (outgoing only). Include nodes that only appear in\n // edges (tolerate dangling edges — they can still participate in a cycle\n // logically, but we just walk what we have).\n const adj = new Map<string, string[]>();\n const ensure = (id: string): string[] => {\n let list = adj.get(id);\n if (!list) {\n list = [];\n adj.set(id, list);\n }\n return list;\n };\n\n for (const n of nodes) {\n if (n && typeof n.id === 'string') {\n ensure(n.id);\n }\n }\n for (const e of edges) {\n if (!e || typeof e.source !== 'string' || typeof e.target !== 'string') continue;\n ensure(e.source).push(e.target);\n ensure(e.target); // ensure target is a known key\n }\n\n // Tri-color DFS: WHITE (unseen), GRAY (in current stack), BLACK (done).\n const WHITE = 0;\n const GRAY = 1;\n const BLACK = 2;\n const color = new Map<string, number>();\n for (const id of adj.keys()) {\n color.set(id, WHITE);\n }\n\n // Iterative DFS using a frame stack. Each frame tracks its iterator index\n // so we can emulate recursive post-order coloring without blowing the stack.\n for (const start of adj.keys()) {\n if (color.get(start) !== WHITE) continue;\n\n const stack: Array<{ node: string; idx: number }> = [{ node: start, idx: 0 }];\n color.set(start, GRAY);\n\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n const neighbors = adj.get(frame.node) ?? [];\n if (frame.idx < neighbors.length) {\n const next = neighbors[frame.idx++];\n const c = color.get(next);\n if (c === GRAY) {\n return true; // back-edge → cycle\n }\n if (c === WHITE) {\n color.set(next, GRAY);\n stack.push({ node: next, idx: 0 });\n }\n // BLACK → already fully explored, skip\n } else {\n color.set(frame.node, BLACK);\n stack.pop();\n }\n }\n }\n\n return false;\n}\n\n/**\n * Inspect a canvas (nodes + edges) and produce a structured list of schema\n * issues. Pure — no mutation, no events, never throws.\n */\nexport function validateSchema(canvas: { nodes?: any[]; edges?: any[] }): SchemaValidationResult {\n const issues: SchemaValidationIssue[] = [];\n const nodes: NodeLike[] = Array.isArray(canvas?.nodes) ? canvas!.nodes! : [];\n const edges: EdgeLike[] = Array.isArray(canvas?.edges) ? canvas!.edges! : [];\n\n // --- duplicate-node-id ----------------------------------------------------\n const nodeIds = new Set<string>();\n const dupNodeIds = new Set<string>();\n for (const n of nodes) {\n if (!n || typeof n.id !== 'string') continue;\n if (nodeIds.has(n.id)) {\n dupNodeIds.add(n.id);\n }\n nodeIds.add(n.id);\n }\n for (const id of dupNodeIds) {\n issues.push({\n severity: 'error',\n code: 'duplicate-node-id',\n nodeId: id,\n message: `Duplicate node id \"${id}\".`,\n });\n }\n\n // --- per-node: duplicate-field + missing-primary-key ---------------------\n for (const n of nodes) {\n if (!n || typeof n.id !== 'string') continue;\n const fields = Array.isArray(n.data?.fields) ? n.data!.fields! : [];\n if (fields.length === 0) continue;\n\n const seen = new Set<string>();\n const dup = new Set<string>();\n for (const f of fields) {\n if (!f || typeof f.name !== 'string') continue;\n if (seen.has(f.name)) {\n dup.add(f.name);\n }\n seen.add(f.name);\n }\n for (const name of dup) {\n issues.push({\n severity: 'error',\n code: 'duplicate-field',\n nodeId: n.id,\n fieldName: name,\n message: `Duplicate field \"${name}\" on node \"${n.id}\".`,\n });\n }\n\n const hasPrimary = fields.some((f) => f && f.key === 'primary');\n if (!hasPrimary) {\n issues.push({\n severity: 'warning',\n code: 'missing-primary-key',\n nodeId: n.id,\n message: `Node \"${n.id}\" has no primary-key field.`,\n });\n }\n }\n\n // --- dangling-edge -------------------------------------------------------\n for (const e of edges) {\n if (!e) continue;\n const edgeId = typeof e.id === 'string' ? e.id : undefined;\n if (typeof e.source !== 'string' || !nodeIds.has(e.source)) {\n issues.push({\n severity: 'error',\n code: 'dangling-edge',\n edgeId,\n nodeId: typeof e.source === 'string' ? e.source : undefined,\n message: `Edge ${edgeId ? `\"${edgeId}\" ` : ''}references missing source node \"${e.source}\".`,\n });\n }\n if (typeof e.target !== 'string' || !nodeIds.has(e.target)) {\n issues.push({\n severity: 'error',\n code: 'dangling-edge',\n edgeId,\n nodeId: typeof e.target === 'string' ? e.target : undefined,\n message: `Edge ${edgeId ? `\"${edgeId}\" ` : ''}references missing target node \"${e.target}\".`,\n });\n }\n }\n\n // --- disconnected-node ---------------------------------------------------\n const touched = new Set<string>();\n for (const e of edges) {\n if (!e) continue;\n if (typeof e.source === 'string') touched.add(e.source);\n if (typeof e.target === 'string') touched.add(e.target);\n }\n for (const n of nodes) {\n if (!n || typeof n.id !== 'string') continue;\n if (!touched.has(n.id)) {\n issues.push({\n severity: 'warning',\n code: 'disconnected-node',\n nodeId: n.id,\n message: `Node \"${n.id}\" has no connected edges.`,\n });\n }\n }\n\n // --- cycle (emit once) ---------------------------------------------------\n if (hasCycle(nodes, edges)) {\n issues.push({\n severity: 'warning',\n code: 'cycle',\n message: 'Directed cycle detected in edge graph.',\n });\n }\n\n const valid = !issues.some((i) => i.severity === 'error');\n return { valid, issues };\n}\n","// ============================================================================\n// alpineflow/schema — diffSchemas\n//\n// Pure helper: computes a structured delta between two `SchemaGraphJSON`\n// snapshots. No canvas coupling, no mutation, never throws on malformed input.\n//\n// Useful for migration generation, PR-review diffs, and undo/redo inspection.\n//\n// All output arrays are deterministically ordered for stability.\n// ============================================================================\n\nimport type { FlowSchemaField } from '../core/types';\nimport type { DiffOptions, SchemaDiff, SchemaGraphJSON } from './types';\n\ninterface NodeShape {\n id: string;\n label: string;\n fields: FlowSchemaField[];\n position: { x: number; y: number };\n}\n\ninterface EdgeShape {\n id: string;\n source: string;\n target: string;\n sourceHandle?: string;\n targetHandle?: string;\n label?: string;\n}\n\nfunction safeNodes(snap: Partial<SchemaGraphJSON> | null | undefined): NodeShape[] {\n if (!snap || !Array.isArray(snap.nodes)) return [];\n return snap.nodes.filter((n): n is NodeShape => !!n && typeof n.id === 'string');\n}\n\nfunction safeEdges(snap: Partial<SchemaGraphJSON> | null | undefined): EdgeShape[] {\n if (!snap || !Array.isArray(snap.edges)) return [];\n return snap.edges.filter((e): e is EdgeShape => !!e && typeof e.id === 'string');\n}\n\nfunction fieldsByName(node: NodeShape): Map<string, FlowSchemaField> {\n const map = new Map<string, FlowSchemaField>();\n const fields = Array.isArray(node.fields) ? node.fields : [];\n for (const f of fields) {\n if (f && typeof f.name === 'string') {\n map.set(f.name, f);\n }\n }\n return map;\n}\n\n/**\n * Compute a structured delta between two schema snapshots. Pure, deterministic,\n * tolerant of malformed input (missing `version`, null snapshots, nodes without\n * fields, etc.).\n */\nexport function diffSchemas(\n before: SchemaGraphJSON,\n after: SchemaGraphJSON,\n opts: DiffOptions = {},\n): SchemaDiff {\n const beforeNodes = safeNodes(before);\n const afterNodes = safeNodes(after);\n const beforeEdges = safeEdges(before);\n const afterEdges = safeEdges(after);\n\n const beforeNodeMap = new Map<string, NodeShape>();\n for (const n of beforeNodes) {\n beforeNodeMap.set(n.id, n);\n }\n const afterNodeMap = new Map<string, NodeShape>();\n for (const n of afterNodes) {\n afterNodeMap.set(n.id, n);\n }\n\n // --- Node add/remove detection ------------------------------------------\n const rawAddedNodes: string[] = [];\n const rawRemovedNodes: string[] = [];\n for (const id of afterNodeMap.keys()) {\n if (!beforeNodeMap.has(id)) rawAddedNodes.push(id);\n }\n for (const id of beforeNodeMap.keys()) {\n if (!afterNodeMap.has(id)) rawRemovedNodes.push(id);\n }\n\n // --- Node rename heuristic ----------------------------------------------\n // For each removed node, find exactly-one added node with the same set of\n // field names (ignoring types). If exactly one match, record as rename and\n // remove from added/removed. Ambiguous (multi-match) pairs are skipped.\n const renamedNodes: Array<{ from: string; to: string }> = [];\n const consumedAddedNodes = new Set<string>();\n const consumedRemovedNodes = new Set<string>();\n\n if (opts.detectRenames) {\n // Precompute field-name-set signatures.\n const sigFor = (node: NodeShape): string => {\n const names = (Array.isArray(node.fields) ? node.fields : [])\n .filter((f) => f && typeof f.name === 'string')\n .map((f) => f.name)\n .sort();\n return names.join('\\u0000');\n };\n\n for (const removedId of rawRemovedNodes) {\n const removedNode = beforeNodeMap.get(removedId);\n if (!removedNode) continue;\n const sig = sigFor(removedNode);\n\n const candidates: string[] = [];\n for (const addedId of rawAddedNodes) {\n if (consumedAddedNodes.has(addedId)) continue;\n const addedNode = afterNodeMap.get(addedId);\n if (!addedNode) continue;\n if (sigFor(addedNode) === sig) {\n candidates.push(addedId);\n }\n }\n\n if (candidates.length === 1) {\n const toId = candidates[0];\n renamedNodes.push({ from: removedId, to: toId });\n consumedAddedNodes.add(toId);\n consumedRemovedNodes.add(removedId);\n }\n // 0 or 2+ candidates → not recorded as rename\n }\n }\n\n const addedNodes = rawAddedNodes.filter((id) => !consumedAddedNodes.has(id));\n const removedNodes = rawRemovedNodes.filter((id) => !consumedRemovedNodes.has(id));\n\n // --- Field diff ----------------------------------------------------------\n // Build the set of (beforeId, afterId) pairs for nodes present in both —\n // either by matching id, or via a detected rename.\n const pairs: Array<{ beforeId: string; afterId: string }> = [];\n for (const id of beforeNodeMap.keys()) {\n if (afterNodeMap.has(id)) {\n pairs.push({ beforeId: id, afterId: id });\n }\n }\n for (const r of renamedNodes) {\n pairs.push({ beforeId: r.from, afterId: r.to });\n }\n\n // Collect field rename hints, keyed by the AFTER nodeId. This lets a\n // consumer supply hints after renaming a node: e.g., if a node was renamed\n // from 'user_old' → 'user_new' and a field was renamed from 'email' →\n // 'email_addr', the hint should target `nodeId: 'user_new'`.\n const fieldRenamesByAfterNodeId = new Map<\n string,\n Array<{ from: string; to: string }>\n >();\n for (const hint of opts.fieldRenames ?? []) {\n if (!hint || typeof hint.nodeId !== 'string') continue;\n if (typeof hint.from !== 'string' || typeof hint.to !== 'string') continue;\n let list = fieldRenamesByAfterNodeId.get(hint.nodeId);\n if (!list) {\n list = [];\n fieldRenamesByAfterNodeId.set(hint.nodeId, list);\n }\n list.push({ from: hint.from, to: hint.to });\n }\n // Also accept hints keyed by the BEFORE nodeId when the node itself was\n // renamed — map them across so renamedFields detection still fires.\n const renameFromToTo = new Map<string, string>();\n for (const r of renamedNodes) {\n renameFromToTo.set(r.from, r.to);\n }\n for (const hint of opts.fieldRenames ?? []) {\n if (!hint || typeof hint.nodeId !== 'string') continue;\n const mapped = renameFromToTo.get(hint.nodeId);\n if (mapped && !fieldRenamesByAfterNodeId.has(mapped)) {\n // Already added above under its original id; also expose under the\n // renamed key so downstream lookups find it whichever key is used.\n const list = fieldRenamesByAfterNodeId.get(hint.nodeId) ?? [];\n fieldRenamesByAfterNodeId.set(mapped, list);\n }\n }\n\n const renamedFields: Array<{ nodeId: string; from: string; to: string }> = [];\n const addedFields: Array<{ nodeId: string; fieldName: string }> = [];\n const removedFields: Array<{ nodeId: string; fieldName: string }> = [];\n const changedFieldTypes: Array<{\n nodeId: string;\n fieldName: string;\n from: string;\n to: string;\n }> = [];\n\n for (const { beforeId, afterId } of pairs) {\n const beforeNode = beforeNodeMap.get(beforeId);\n const afterNode = afterNodeMap.get(afterId);\n if (!beforeNode || !afterNode) continue;\n\n const beforeFields = fieldsByName(beforeNode);\n const afterFields = fieldsByName(afterNode);\n\n // Apply field-rename hints. The hint's nodeId is matched against the\n // AFTER node's id (most common case) — if the node was renamed, the\n // hint may target either id thanks to the dual keying above.\n const hints =\n fieldRenamesByAfterNodeId.get(afterId) ??\n fieldRenamesByAfterNodeId.get(beforeId) ??\n [];\n const consumedBefore = new Set<string>();\n const consumedAfter = new Set<string>();\n\n for (const hint of hints) {\n const oldField = beforeFields.get(hint.from);\n const newField = afterFields.get(hint.to);\n if (!oldField || !newField) continue;\n if (consumedBefore.has(hint.from) || consumedAfter.has(hint.to)) continue;\n renamedFields.push({ nodeId: afterId, from: hint.from, to: hint.to });\n consumedBefore.add(hint.from);\n consumedAfter.add(hint.to);\n\n // Type change across the rename\n const oldType = typeof oldField.type === 'string' ? oldField.type : '';\n const newType = typeof newField.type === 'string' ? newField.type : '';\n if (oldType !== newType) {\n changedFieldTypes.push({\n nodeId: afterId,\n fieldName: hint.to,\n from: oldType,\n to: newType,\n });\n }\n }\n\n // Field added / removed (after applying hints)\n for (const [name] of afterFields) {\n if (consumedAfter.has(name)) continue;\n if (!beforeFields.has(name)) {\n addedFields.push({ nodeId: afterId, fieldName: name });\n }\n }\n for (const [name] of beforeFields) {\n if (consumedBefore.has(name)) continue;\n if (!afterFields.has(name)) {\n removedFields.push({ nodeId: afterId, fieldName: name });\n }\n }\n\n // Changed field types for fields present in both (by name, no rename)\n for (const [name, beforeField] of beforeFields) {\n if (consumedBefore.has(name)) continue;\n const afterField = afterFields.get(name);\n if (!afterField) continue;\n const oldType = typeof beforeField.type === 'string' ? beforeField.type : '';\n const newType = typeof afterField.type === 'string' ? afterField.type : '';\n if (oldType !== newType) {\n changedFieldTypes.push({\n nodeId: afterId,\n fieldName: name,\n from: oldType,\n to: newType,\n });\n }\n }\n }\n\n // --- Edge diff (by id) ---------------------------------------------------\n const beforeEdgeIds = new Set<string>();\n for (const e of beforeEdges) beforeEdgeIds.add(e.id);\n const afterEdgeIds = new Set<string>();\n for (const e of afterEdges) afterEdgeIds.add(e.id);\n\n const addedEdges: string[] = [];\n const removedEdges: string[] = [];\n for (const id of afterEdgeIds) {\n if (!beforeEdgeIds.has(id)) addedEdges.push(id);\n }\n for (const id of beforeEdgeIds) {\n if (!afterEdgeIds.has(id)) removedEdges.push(id);\n }\n\n // --- Deterministic ordering ---------------------------------------------\n addedNodes.sort();\n removedNodes.sort();\n renamedNodes.sort((a, b) => a.from.localeCompare(b.from));\n const fieldKey = (f: { nodeId: string; fieldName: string }) =>\n `${f.nodeId}\\u0000${f.fieldName}`;\n addedFields.sort((a, b) => fieldKey(a).localeCompare(fieldKey(b)));\n removedFields.sort((a, b) => fieldKey(a).localeCompare(fieldKey(b)));\n renamedFields.sort((a, b) => {\n const k = a.nodeId.localeCompare(b.nodeId);\n return k !== 0 ? k : a.from.localeCompare(b.from);\n });\n changedFieldTypes.sort((a, b) => fieldKey(a).localeCompare(fieldKey(b)));\n addedEdges.sort();\n removedEdges.sort();\n\n return {\n addedNodes,\n removedNodes,\n renamedNodes,\n addedFields,\n removedFields,\n renamedFields,\n changedFieldTypes,\n addedEdges,\n removedEdges,\n };\n}\n","// ============================================================================\n// alpineflow/schema — toDot\n//\n// Pure helper: renders the current `canvas.nodes` + `canvas.edges` as a valid\n// graphviz DOT string. No canvas coupling, no mutation, never throws on\n// malformed input.\n//\n// Useful for docs generation, static image output (via `dot -Tpng`), and\n// PR-review attachments.\n//\n// Schema nodes render as HTML-like `<TABLE>` labels so field rows appear as\n// rows inside the node box in any graphviz viewer. Each field row exposes a\n// `PORT=\"<fieldName>\"` so edges can reference a specific row when\n// `sourceHandle`/`targetHandle` are set.\n// ============================================================================\n\nimport type { DotExportOptions } from './types';\n\nconst DEFAULTS: Required<DotExportOptions> = {\n rankdir: 'LR',\n nodeShape: 'plaintext',\n includeFieldTypes: true,\n includeFieldKeys: true,\n graphName: 'schema',\n};\n\n/**\n * Escape a string for inclusion inside a graphviz HTML-like label (the content\n * between the `< ... >` delimiters). Only the five XML/HTML specials need\n * escaping; the surrounding `<TAG>` markup is emitted by the renderer and is\n * not user-supplied.\n */\nfunction escapeHTML(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/**\n * Escape a string for inclusion inside a graphviz quoted string (`\"...\"`).\n * Backslash must be doubled first so the subsequent quote-escaping doesn't\n * re-escape the backslashes it just added.\n */\nfunction escapeQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\nfunction renderNode(n: any, o: Required<DotExportOptions>): string {\n const id = String(n?.id ?? '');\n const label = String(n?.data?.label ?? '');\n const fields = Array.isArray(n?.data?.fields) ? n.data.fields : [];\n\n const colSpan = 1 + (o.includeFieldKeys ? 1 : 0) + (o.includeFieldTypes ? 1 : 0);\n\n const rows: string[] = [];\n rows.push(\n ` <TR><TD BGCOLOR=\"#f0f0f0\" COLSPAN=\"${colSpan}\"><B>${escapeHTML(label)}</B></TD></TR>`,\n );\n\n for (const f of fields) {\n const name = String(f?.name ?? '');\n const cells: string[] = [];\n\n if (o.includeFieldKeys) {\n const marker = f?.key === 'primary' ? 'PK' : f?.key === 'foreign' ? 'FK' : '';\n cells.push(`<TD>${marker}</TD>`);\n }\n cells.push(`<TD PORT=\"${escapeHTML(name)}\">${escapeHTML(name)}</TD>`);\n if (o.includeFieldTypes) {\n cells.push(`<TD>${escapeHTML(String(f?.type ?? ''))}</TD>`);\n }\n\n rows.push(` <TR>${cells.join('')}</TR>`);\n }\n\n return (\n ` \"${escapeQuoted(id)}\" [label=<\\n` +\n ` <TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\">\\n` +\n `${rows.join('\\n')}\\n` +\n ` </TABLE>\\n` +\n ` >];`\n );\n}\n\nfunction renderEdge(e: any): string {\n const source = `\"${escapeQuoted(String(e?.source ?? ''))}\"`;\n const target = `\"${escapeQuoted(String(e?.target ?? ''))}\"`;\n const sourcePort = e?.sourceHandle\n ? `:\"${escapeQuoted(String(e.sourceHandle))}\"`\n : '';\n const targetPort = e?.targetHandle\n ? `:\"${escapeQuoted(String(e.targetHandle))}\"`\n : '';\n const label = e?.label\n ? ` [label=\"${escapeQuoted(String(e.label))}\"]`\n : '';\n return ` ${source}${sourcePort} -> ${target}${targetPort}${label};`;\n}\n\n/**\n * Render `canvas.nodes` + `canvas.edges` as a graphviz DOT string.\n *\n * Pure function: no canvas coupling, no mutation, safe on malformed input\n * (empty arrays, missing label, missing field type, etc.).\n */\nexport function toDot(\n canvas: { nodes: any[]; edges: any[] },\n opts: DotExportOptions = {},\n): string {\n const o = { ...DEFAULTS, ...opts };\n\n const lines: string[] = [];\n lines.push(`digraph \"${escapeQuoted(o.graphName)}\" {`);\n lines.push(` rankdir=${o.rankdir};`);\n lines.push(` node [shape=${o.nodeShape}];`);\n\n for (const n of canvas?.nodes ?? []) {\n lines.push(renderNode(n, o));\n }\n\n for (const e of canvas?.edges ?? []) {\n lines.push(renderEdge(e));\n }\n\n lines.push('}');\n return lines.join('\\n');\n}\n","// ============================================================================\n// alpineflow/schema — schemaLayout wrapper\n//\n// Thin wrapper around the host canvas's layout engines (dagre → tree → grid)\n// with schema-friendly defaults. When `deriveFromReferences` is set, uses\n// `inferReferences()` output as the graph topology instead of `canvas.edges`.\n//\n// Detection is runtime-only: the schema subpath addon must NOT hard-depend on\n// the dagre / hierarchy addons. If neither is registered, the grid fallback\n// (pure math, zero external deps) is always available.\n// ============================================================================\n\nimport type { SchemaLayoutOptions } from './types';\nimport { inferReferences } from './references';\n\ntype Algorithm = 'dagre' | 'tree' | 'grid';\n\nconst DEFAULT_ORDER: readonly Algorithm[] = ['dagre', 'tree', 'grid'] as const;\n\n/**\n * Apply a schema-tuned layout to the canvas.\n *\n * - Prefers the dagre addon (exposed via `canvas.layout()`), falls through to\n * the hierarchy addon (`canvas.treeLayout()`), then to a pure-math grid\n * fallback that is always available.\n * - When `opts.deriveFromReferences` is true, the underlying layout sees the\n * reference graph derived from `inferReferences(canvas.nodes)` instead of\n * the canvas's explicit edges. The original edges are restored afterwards,\n * even if the layout call throws.\n */\nexport async function schemaLayout(\n canvas: any,\n opts: SchemaLayoutOptions = {},\n): Promise<void> {\n const direction = opts.direction ?? 'LR';\n const nodeSpacing = opts.nodeSpacing ?? 80;\n const rankSpacing = opts.rankSpacing ?? 160;\n\n const preferred = resolvePreferredOrder(opts.algorithm);\n\n // Swap edges in-place when deriving from references so whichever algorithm\n // runs downstream sees the inferred topology. Splice is used so Alpine's\n // reactive proxy tracks the mutation.\n const swap = opts.deriveFromReferences ? prepareEdgeSwap(canvas) : null;\n\n try {\n for (const algo of preferred) {\n if (algo === 'dagre' && tryDagre(canvas, direction, nodeSpacing, rankSpacing)) {\n return;\n }\n if (algo === 'tree' && tryTree(canvas, direction, nodeSpacing, rankSpacing)) {\n return;\n }\n if (algo === 'grid') {\n applyGridLayout(canvas.nodes ?? [], nodeSpacing, rankSpacing, direction);\n return;\n }\n }\n\n // Should be unreachable because 'grid' is always in the fallback chain\n // when no explicit algorithm was requested. Reachable only when the\n // consumer pinned algorithm:'dagre' or 'tree' and that addon was\n // missing — in which case we warn and no-op.\n // eslint-disable-next-line no-console\n console.warn(\n '[alpineflow/schema] schemaLayout: no layout algorithm available. ' +\n 'Register @getartisanflow/alpineflow/dagre (or hierarchy), or pass ' +\n '{ algorithm: \"grid\" } for the always-available fallback.',\n );\n } finally {\n if (swap) {\n swap.restore();\n }\n }\n}\n\nfunction resolvePreferredOrder(pinned?: Algorithm): Algorithm[] {\n if (!pinned) {\n return [...DEFAULT_ORDER];\n }\n // When the consumer pins an algorithm, honour that first and only that —\n // they've opted out of the fallback chain. The grid path still counts as\n // \"always available\" and terminates immediately.\n return [pinned];\n}\n\ninterface EdgeSwap {\n restore: () => void;\n}\n\nfunction prepareEdgeSwap(canvas: any): EdgeSwap | null {\n const edges = canvas.edges;\n if (!Array.isArray(edges)) {\n return null;\n }\n\n const original = edges.slice();\n const inferred = inferReferences(canvas.nodes ?? []).map((suggestion, index) => ({\n id: `schema-layout-inferred-${index}`,\n source: suggestion.fromNodeId,\n target: suggestion.toNodeId,\n sourceHandle: suggestion.fromFieldName,\n targetHandle: suggestion.toFieldName,\n }));\n\n edges.splice(0, edges.length, ...inferred);\n\n return {\n restore: () => {\n edges.splice(0, edges.length, ...original);\n },\n };\n}\n\nfunction tryDagre(\n canvas: any,\n direction: 'LR' | 'TB' | 'BT' | 'RL',\n nodeSpacing: number,\n rankSpacing: number,\n): boolean {\n // `canvas.layout()` is the dagre entry point exposed by the core. When the\n // dagre addon isn't registered it throws a dedicated error — we treat that\n // as \"not available\" and fall through to the next algorithm.\n if (typeof canvas.layout !== 'function') {\n return false;\n }\n try {\n canvas.layout({\n direction,\n nodesep: nodeSpacing,\n ranksep: rankSpacing,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction tryTree(\n canvas: any,\n direction: 'LR' | 'TB' | 'BT' | 'RL',\n nodeSpacing: number,\n rankSpacing: number,\n): boolean {\n if (typeof canvas.treeLayout !== 'function') {\n return false;\n }\n // The hierarchy engine only recognises TB / LR / BT / RL; pass through\n // as-is. It derives its own spacing from `nodeWidth` / `nodeHeight`, so\n // translate our logical spacing to those knobs.\n try {\n canvas.treeLayout({\n direction,\n nodeWidth: nodeSpacing + 200,\n nodeHeight: rankSpacing + 80,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction applyGridLayout(\n nodes: any[],\n nodeSpacing: number,\n rankSpacing: number,\n direction: 'LR' | 'TB' | 'BT' | 'RL',\n): void {\n const count = nodes.length;\n if (count === 0) {\n return;\n }\n\n const cols = Math.max(1, Math.ceil(Math.sqrt(count)));\n const rows = Math.ceil(count / cols);\n const cellWidth = nodeSpacing + 300;\n const cellHeight = rankSpacing + 200;\n\n for (let i = 0; i < count; i++) {\n const col = i % cols;\n const row = Math.floor(i / cols);\n\n let x = col * cellWidth;\n let y = row * cellHeight;\n\n // Grid is axis-symmetric, so TB / LR collapse to the same arrangement;\n // BT and RL simply mirror the relevant axis so consumers who care about\n // the visual direction still see the right flow.\n if (direction === 'BT') {\n y = (rows - 1 - row) * cellHeight;\n } else if (direction === 'RL') {\n x = (cols - 1 - col) * cellWidth;\n }\n\n nodes[i].position = { x, y };\n }\n}\n","// ============================================================================\n// alpineflow/schema — attachSchemaHistory()\n//\n// Opt-in undo/redo scaffolding. Listens for `schema:*` DOM events fired by\n// field-ops helpers, snapshots the canvas via `schemaToJSON`, and restores via\n// `schemaFromJSON` on undo/redo. Bounded stack with `limit` eviction and\n// transactional `batch(fn)` semantics.\n//\n// Consumers must opt in — `registerSchemaAddon` does NOT auto-attach history.\n// ============================================================================\n\nimport type { SchemaGraphJSON, SchemaHistoryHandle, SchemaHistoryOptions } from './types';\nimport { schemaFromJSON, schemaToJSON } from './serialization';\n\nconst TRACKED_EVENTS = [\n 'schema:field-added',\n 'schema:field-renamed',\n 'schema:field-removed',\n 'schema:edges-cascaded',\n] as const;\n\n/**\n * Attach a bounded undo/redo stack to a canvas. Returns a handle with\n * `undo()`, `redo()`, `batch(fn)`, `clear()`, and `dispose()`.\n *\n * Snapshots are pushed on each `schema:field-added`, `schema:field-renamed`,\n * `schema:field-removed`, and `schema:edges-cascaded` event. The apply path\n * (undo/redo/batch rollback) suspends snapshot pushes to avoid feedback loops.\n */\nexport function attachSchemaHistory(canvas: any, opts: SchemaHistoryOptions = {}): SchemaHistoryHandle {\n const limit = Math.max(1, opts.limit ?? 50);\n const undoStack: SchemaGraphJSON[] = [];\n const redoStack: SchemaGraphJSON[] = [];\n let suspendDepth = 0;\n let batchDepth = 0;\n let batchEntrySnapshot: SchemaGraphJSON | null = null;\n let disposed = false;\n\n const target: EventTarget | null = canvas?.el ?? canvas?._container ?? null;\n if (!target || typeof (target as any).addEventListener !== 'function') {\n return makeNoopHandle();\n }\n\n const evictOldest = (): void => {\n // Always keep at least 1 entry (the floor) so we never undo past the\n // initial snapshot.\n while (undoStack.length > limit && undoStack.length > 1) {\n undoStack.shift();\n }\n };\n\n // Push a snapshot, deduping against the current stack top, then evict + clear\n // redo. Dedup identical states: a cascading op (renameField/removeField)\n // dispatches schema:field-* AND schema:edges-cascaded *after* all mutations\n // complete, yielding two byte-identical snapshots — coalesce them into a\n // single undoable step so the first undo is never a no-op. Shared by the\n // event path (pushSnapshot) and the batch-commit path.\n const pushDeduped = (snap: SchemaGraphJSON): void => {\n const top = undoStack[undoStack.length - 1];\n if (top !== undefined && JSON.stringify(top) === JSON.stringify(snap)) {\n return;\n }\n undoStack.push(snap);\n evictOldest();\n redoStack.length = 0;\n };\n\n const pushSnapshot = (): void => {\n if (disposed) {\n return;\n }\n if (suspendDepth > 0) {\n return;\n }\n if (batchDepth > 0) {\n // Inside a batch — individual events do not push. A single snapshot\n // is pushed when the outermost batch exits.\n return;\n }\n pushDeduped(schemaToJSON(canvas));\n };\n\n // Initial floor snapshot — captures pre-mutation state so the first undo\n // after a field-add reverts cleanly.\n undoStack.push(schemaToJSON(canvas));\n\n const onEvent = (): void => {\n pushSnapshot();\n };\n for (const name of TRACKED_EVENTS) {\n target.addEventListener(name, onEvent);\n }\n\n const applySnapshot = (snap: SchemaGraphJSON): void => {\n // Suspend snapshot capture while we mutate via schemaFromJSON.\n suspendDepth++;\n try {\n schemaFromJSON(canvas, snap);\n } finally {\n suspendDepth--;\n }\n };\n\n const handle: SchemaHistoryHandle = {\n get canUndo(): boolean {\n // The floor snapshot always stays; only report true when there is\n // at least one mutation snapshot above it.\n return undoStack.length > 1;\n },\n get canRedo(): boolean {\n return redoStack.length > 0;\n },\n undo(): boolean {\n if (disposed) {\n return false;\n }\n if (undoStack.length <= 1) {\n return false;\n }\n const current = undoStack.pop() as SchemaGraphJSON;\n redoStack.push(current);\n const prev = undoStack[undoStack.length - 1];\n applySnapshot(prev);\n return true;\n },\n redo(): boolean {\n if (disposed) {\n return false;\n }\n if (redoStack.length === 0) {\n return false;\n }\n const snap = redoStack.pop() as SchemaGraphJSON;\n undoStack.push(snap);\n applySnapshot(snap);\n return true;\n },\n clear(): void {\n undoStack.length = 0;\n redoStack.length = 0;\n if (!disposed) {\n undoStack.push(schemaToJSON(canvas));\n }\n },\n batch<T>(fn: () => T): T {\n if (disposed) {\n return fn();\n }\n // Outermost batch captures the pre-batch state for rollback on\n // throw. Nested batches share the outer batch's entry snapshot.\n if (batchDepth === 0) {\n batchEntrySnapshot = schemaToJSON(canvas);\n }\n batchDepth++;\n try {\n const result = fn();\n batchDepth--;\n if (batchDepth === 0) {\n // Outermost batch exiting — push one snapshot capturing\n // the aggregate result of all mutations inside.\n batchEntrySnapshot = null;\n if (suspendDepth === 0 && !disposed) {\n // A net-no-op batch must not leave a duplicate-of-top entry.\n pushDeduped(schemaToJSON(canvas));\n }\n }\n return result;\n } catch (err) {\n batchDepth--;\n if (batchDepth === 0) {\n // Roll back to pre-batch state. suspendDepth increment in\n // applySnapshot prevents the restoration from triggering\n // its own snapshot via any events fired by schemaFromJSON.\n const entry = batchEntrySnapshot;\n batchEntrySnapshot = null;\n if (entry && !disposed) {\n applySnapshot(entry);\n }\n }\n throw err;\n }\n },\n dispose(): void {\n if (disposed) {\n return;\n }\n disposed = true;\n for (const name of TRACKED_EVENTS) {\n target.removeEventListener(name, onEvent);\n }\n undoStack.length = 0;\n redoStack.length = 0;\n batchEntrySnapshot = null;\n },\n };\n\n return handle;\n}\n\nfunction makeNoopHandle(): SchemaHistoryHandle {\n return {\n get canUndo(): boolean {\n return false;\n },\n get canRedo(): boolean {\n return false;\n },\n undo: (): boolean => false,\n redo: (): boolean => false,\n clear: (): void => {},\n batch<T>(fn: () => T): T {\n return fn();\n },\n dispose: (): void => {},\n };\n}\n","import en from '../../locales/en.json';\n\n/**\n * Every message the engine ships, keyed as in `locales/en.json`. Messages that\n * carry a `:count` appear in the two plural forms English uses, `_one` and `_other`.\n */\ninterface EnglishMessages {\n /** Accessible name of the controls panel. */\n 'controls.label'?: string;\n /** Tooltip / accessible name of the zoom-in button. */\n 'controls.zoomIn'?: string;\n /** Tooltip / accessible name of the zoom-out button. */\n 'controls.zoomOut'?: string;\n /** Tooltip / accessible name of the fit-view button. */\n 'controls.fitView'?: string;\n /** Tooltip of the interactivity toggle before its state is known. */\n 'controls.toggleInteractive'?: string;\n /** Tooltip of the interactivity toggle while the canvas is interactive (click locks it). */\n 'controls.lockInteractive'?: string;\n /** Tooltip of the interactivity toggle while the canvas is locked (click unlocks it). */\n 'controls.unlockInteractive'?: string;\n /** Tooltip / accessible name of the reset-panels button. */\n 'controls.resetPanels'?: string;\n /** Tooltip of the fullscreen toggle before its state is known. */\n 'controls.toggleFullscreen'?: string;\n /** Tooltip of the fullscreen toggle while windowed (click enters fullscreen). */\n 'controls.enterFullscreen'?: string;\n /** Tooltip of the fullscreen toggle while fullscreen (click exits). */\n 'controls.exitFullscreen'?: string;\n\n /** Default `aria-label` of the canvas container (overridden by `ariaLabel`). */\n 'canvas.label'?: string;\n /** Text shown while the canvas initialises (overridden by `loadingText`). */\n 'canvas.loading'?: string;\n /** Touch hint shown while multi-selection mode is active. */\n 'canvas.selectionMode'?: string;\n\n /** Accessible name of a node with a label. Placeholder: `:label`. */\n 'a11y.nodeLabel'?: string;\n /** Accessible name of a node without a label. Placeholder: `:id`. */\n 'a11y.nodeId'?: string;\n /** Accessible name of an edge with a label. Placeholder: `:label`. */\n 'a11y.edgeLabel'?: string;\n /** Accessible name of an edge without a label. Placeholders: `:source`, `:target`. */\n 'a11y.edgeEndpoints'?: string;\n /** Accessible name of a source handle. Placeholder: `:id`. */\n 'a11y.sourceHandle'?: string;\n /** Accessible name of a target handle. Placeholder: `:id`. */\n 'a11y.targetHandle'?: string;\n /** Tooltip on an editable edge's midpoint. */\n 'a11y.addControlPoint'?: string;\n\n /** Announced when one labelled node is added. Placeholder: `:label`. */\n 'announce.nodeAdded'?: string;\n /** Announced when several nodes are added. Placeholder: `:count` (plural, singular form). */\n 'announce.nodesAdded_one'?: string;\n /** Announced when several nodes are added. Placeholder: `:count` (plural, default form). */\n 'announce.nodesAdded_other'?: string;\n /** Announced when one labelled node is removed. Placeholder: `:label`. */\n 'announce.nodeRemoved'?: string;\n /** Announced when several nodes are removed. Placeholder: `:count` (plural, singular form). */\n 'announce.nodesRemoved_one'?: string;\n /** Announced when several nodes are removed. Placeholder: `:count` (plural, default form). */\n 'announce.nodesRemoved_other'?: string;\n /** Announced when one edge is added. Placeholders: `:source`, `:target`. */\n 'announce.connected'?: string;\n /** Announced when several edges are added. Placeholder: `:count` (plural, singular form). */\n 'announce.connectionsAdded_one'?: string;\n /** Announced when several edges are added. Placeholder: `:count` (plural, default form). */\n 'announce.connectionsAdded_other'?: string;\n /** Announced when one edge with known endpoints is removed. Placeholders: `:source`, `:target`. */\n 'announce.disconnected'?: string;\n /** Announced when edges without known endpoints are removed. Placeholder: `:count` (plural, singular form). */\n 'announce.connectionsRemoved_one'?: string;\n /** Announced when edges without known endpoints are removed. Placeholder: `:count` (plural, default form). */\n 'announce.connectionsRemoved_other'?: string;\n /** Announced when the selection becomes empty. */\n 'announce.selectionCleared'?: string;\n /** Node part of a selection announcement. Placeholder: `:count` (plural, singular form). */\n 'announce.nodesSelected_one'?: string;\n /** Node part of a selection announcement. Placeholder: `:count` (plural, default form). */\n 'announce.nodesSelected_other'?: string;\n /** Edge part of a selection announcement. Placeholder: `:count` (plural, singular form). */\n 'announce.edgesSelected_one'?: string;\n /** Edge part of a selection announcement. Placeholder: `:count` (plural, default form). */\n 'announce.edgesSelected_other'?: string;\n /** Joins the node and edge parts of a selection announcement. Placeholders: `:nodes`, `:edges`. */\n 'announce.selectionJoin'?: string;\n /** Wraps the selection summary. Placeholder: `:items`. */\n 'announce.selected'?: string;\n /** Announced when panning or zooming ends. Placeholder: `:percent`. */\n 'announce.viewportZoom'?: string;\n /** Announced after fit-view. */\n 'announce.viewFitted'?: string;\n /** Fallback name for a node without label or id in reparent announcements. */\n 'announce.node'?: string;\n /** Announced when a node is moved into a parent. Placeholders: `:name`, `:parent`. */\n 'announce.reparented'?: string;\n /** Announced when a node leaves its parent. Placeholders: `:name`, `:parent`. */\n 'announce.detached'?: string;\n\n /** Default label of a condition node without `data.label`. */\n 'workflow.condition'?: string;\n /** Shown instead of an expression when a condition uses a custom evaluator function. */\n 'workflow.customEvaluator'?: string;\n /** Default label of a wait node without `data.label`. */\n 'workflow.wait'?: string;\n\n /** Node inspector placeholder while nothing is selected. */\n 'schema.inspector.noNode'?: string;\n /** Edge inspector placeholder while nothing is selected. */\n 'schema.inspector.noEdge'?: string;\n /** Row inspector placeholder while nothing is selected. */\n 'schema.inspector.noRow'?: string;\n /** Row inspector message when the selected row was deleted. */\n 'schema.inspector.missingRow'?: string;\n /** Form label of the edge label input. */\n 'schema.inspector.label'?: string;\n /** Form label of the row name input. */\n 'schema.inspector.name'?: string;\n /** Form label and placeholder of the row type input. */\n 'schema.inspector.type'?: string;\n /** Form label of the row \"required\" checkbox. */\n 'schema.inspector.required'?: string;\n /** Button verb that removes a row. */\n 'schema.inspector.remove'?: string;\n /** Button verb that deletes the selected edge. */\n 'schema.inspector.delete'?: string;\n /** Button verb that adds a row. */\n 'schema.inspector.add'?: string;\n /** Placeholder of the new-row name input. */\n 'schema.inspector.fieldName'?: string;\n}\n\ntype PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';\n\n/** Base keys of the messages with plural forms, e.g. `announce.nodesSelected`. */\ntype PluralMessage = keyof EnglishMessages extends infer K\n ? K extends `${infer Base}_other` ? Base : never\n : never;\n\n/**\n * Plural forms other languages need besides `_one` / `_other`: Arabic uses `_zero`\n * and `_two`, Polish and Russian `_few` and `_many`. A language's categories are\n * listed by `new Intl.PluralRules(locale).resolvedOptions().pluralCategories`.\n */\ntype AdditionalPluralForms = {\n [K in `${PluralMessage}_${Exclude<PluralCategory, 'one' | 'other'>}`]?: string;\n};\n\n/**\n * UI messages of a canvas. Every key is optional; missing keys fall back to\n * English. Messages are plain text with literal `:placeholder` substitution.\n * Keys that carry a `:count` exist once per CLDR plural category (`_one`,\n * `_few`, `_other`, …) and are selected with the canvas `locale`.\n */\nexport interface FlowTranslations extends EnglishMessages, AdditionalPluralForms {}\n\ntype MessageKey = keyof FlowTranslations;\n\n/** Message keys as callers use them: plural variants collapse onto their base key. */\nexport type TranslationKey = MessageKey extends infer K\n ? K extends `${infer Base}_${PluralCategory}` ? Base : K\n : never;\n\n/** `A` when it has exactly the keys of `B`, otherwise `never`. */\ntype SameKeys<A, B> = [keyof A] extends [keyof B] ? ([keyof B] extends [keyof A] ? A : never) : never;\n\n/**\n * English defaults. The annotation fails `tsc` when `locales/en.json` and\n * {@link EnglishMessages} disagree on a key, so the interface stays the single\n * typed source and the emitted declarations carry no JSON import.\n */\nconst englishMessages: SameKeys<typeof en, Required<EnglishMessages>> = en;\n\nconst FALLBACK_LOCALE = 'en';\nconst pluralRulesCache = new Map<string, Intl.PluralRules>();\n\n/**\n * Plural rules for a locale tag. Accepts Laravel-style underscores (`pt_BR`),\n * defaults to the document language and falls back to English for invalid tags.\n */\nexport function resolvePluralRules(locale?: string): Intl.PluralRules {\n const requested = locale ?? (typeof document !== 'undefined' ? document.documentElement.lang : '');\n const tag = requested.trim().replace(/_/g, '-') || FALLBACK_LOCALE;\n let rules = pluralRulesCache.get(tag);\n if (!rules) {\n try {\n rules = new Intl.PluralRules(tag);\n } catch {\n rules = resolvePluralRules(FALLBACK_LOCALE);\n }\n pluralRulesCache.set(tag, rules);\n }\n return rules;\n}\n\n/** Translates a message key with optional placeholder values. See {@link createTranslator}. */\nexport type Translator = (key: TranslationKey, values?: Record<string, string | number>) => string;\n\ntype MessageTable = Record<string, string | undefined>;\n\n/** Only non-empty strings count as translations; anything else falls through to the next fallback. */\nfunction usable(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\nfunction pickMessage(table: MessageTable, key: string, count: number | undefined, rules: Intl.PluralRules): string | undefined {\n // Without a count, a plural-only key still yields its `_other` form rather than the raw key;\n // with a count, a message without plural forms still resolves the plain key.\n if (count === undefined) return usable(table[key]) ?? usable(table[`${key}_other`]);\n return usable(table[`${key}_${rules.select(count)}`]) ?? usable(table[`${key}_other`]) ?? usable(table[key]);\n}\n\nconst placeholderPatternCache = new Map<string, RegExp>();\n\n/**\n * Substitute `:name` placeholders with the given values, longest name first\n * (Laravel's order), so `:labelId` is not clobbered by `:label` and names may be\n * followed directly by letters or underscores. Unknown placeholders stay literal.\n */\nfunction substitute(message: string, values: Record<string, string | number>): string {\n const names = Object.keys(values).sort((a, b) => b.length - a.length);\n if (names.length === 0) return message;\n // Call sites use a handful of fixed placeholder sets, so cache the compiled pattern per set.\n const signature = names.join('\\0');\n let pattern = placeholderPatternCache.get(signature);\n if (!pattern) {\n pattern = new RegExp(`:(${names.map((name) => name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')).join('|')})`, 'g');\n placeholderPatternCache.set(signature, pattern);\n }\n return message.replace(pattern, (_match, name: string) => String(values[name]));\n}\n\n/**\n * Build a translator for one canvas. The overrides are copied once into a plain\n * object, so later changes to the source dictionary (or Alpine reactivity on it)\n * do not affect the result; recreate the canvas to change its language.\n *\n * Lookup order: the override for the locale's plural category, the override's\n * `_other` form, then the English message selected with English plural rules.\n * Empty strings and non-string values are ignored. Placeholders (`:label`) are\n * substituted literally.\n */\nexport function createTranslator(translations?: FlowTranslations, locale?: string): Translator {\n const overrides: MessageTable = {};\n for (const [key, value] of Object.entries(translations ?? {})) {\n const text = usable(value);\n if (text !== undefined) overrides[key] = text;\n }\n const localeRules = resolvePluralRules(locale);\n const englishRules = resolvePluralRules(FALLBACK_LOCALE);\n\n return (key, values = {}) => {\n const count = typeof values.count === 'number' ? values.count : undefined;\n const message = pickMessage(overrides, key, count, localeRules)\n ?? pickMessage(englishMessages, key, count, englishRules)\n ?? key;\n return substitute(message, values);\n };\n}\n\n/** English messages with English plural rules, shared by call sites that have no canvas. */\nexport const englishTranslator: Translator = createTranslator(undefined, FALLBACK_LOCALE);\n\n/**\n * Translator for a directive's canvas scope: delegates to the canvas `t()` when\n * present, otherwise English. Lets directives and inspectors mount against a\n * plain `x-data` host (tests, custom shells) without a `flowCanvas` instance.\n */\nexport function canvasTranslator(canvas: unknown): Translator {\n const scope = canvas as { t?: unknown } | null | undefined;\n if (typeof scope?.t !== 'function') return englishTranslator;\n return (key, values) => (scope as { t: Translator }).t(key, values);\n}\n","// ============================================================================\n// Shared helpers for the three inspector directives.\n//\n// Keeps the per-scope files focused on the (scope-specific) default UI and\n// helper wiring. Selection lookup, canvas discovery, default-ui detection,\n// and stamping utilities live here.\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\n\nexport type InspectorScope = 'node' | 'row' | 'edge';\n\n/**\n * Pick the primary selection id from a reactive `Set<string>`.\n *\n * JS Sets preserve insertion order, so the most recently selected id is the\n * last element. For an empty set we return null.\n *\n * Iterating the set here also registers a reactive dependency with Alpine so\n * callers inside an `effect` re-run when the set changes.\n */\nexport function lastInSet(set: Set<string> | null | undefined): string | null {\n if (!set || set.size === 0) {\n return null;\n }\n let last: string | null = null;\n for (const id of set) {\n last = id;\n }\n return last;\n}\n\n/** Parse a row id of the form \"nodeId.fieldName\" — first dot only. */\nexport function parseRowId(\n rowId: string | null,\n): { nodeId: string; fieldName: string } | null {\n if (!rowId) {\n return null;\n }\n const dot = rowId.indexOf('.');\n if (dot < 1 || dot === rowId.length - 1) {\n return null;\n }\n return { nodeId: rowId.slice(0, dot), fieldName: rowId.slice(dot + 1) };\n}\n\n/**\n * Resolve the flow canvas Alpine scope associated with an inspector element.\n *\n * Three-step lookup:\n * 1. Nearest ancestor `.flow-container` — inspector nested inside the canvas\n * viewport (preset side-panel pattern).\n * 2. If none, and exactly one `.flow-container` exists on the page, use it —\n * supports outside-canvas placements (e.g. a page-level right sidebar\n * that's a sibling of the canvas). Single canvas = unambiguous.\n * 3. Multiple canvases without an ancestor match — log a one-shot warning\n * and bail out; the caller must nest the inspector inside the target\n * canvas (an explicit selector prop is on the v0.2.2 roadmap).\n *\n * Inspector directives currently call this once at init and close over the\n * returned scope. That works because inspectors render inside or alongside an\n * already-initialized canvas in every shipped pattern. If a future caller\n * mounts an inspector before its canvas's Alpine setup runs (e.g. portal-\n * teleported or tab-switched), the cached `Alpine.$data()` proxy can go stale\n * and method calls will throw — mirror the workflow addon's `ensureCanvas`\n * pattern (re-resolve at method-call time) before placing inspectors in such\n * positions.\n */\nexport function findCanvasScope(\n Alpine: Alpine,\n el: HTMLElement,\n): any | null {\n // 1. Closest ancestor .flow-container — inside-canvas placement.\n const ancestor = el.closest('.flow-container') as HTMLElement | null;\n if (ancestor) {\n try {\n return Alpine.$data(ancestor) ?? null;\n } catch {\n /* fall through to page-level fallbacks */\n }\n }\n\n // 2. Single .flow-container on the page — outside-canvas placement.\n const containers = document.querySelectorAll('.flow-container');\n if (containers.length === 1) {\n try {\n return Alpine.$data(containers[0] as HTMLElement) ?? null;\n } catch {\n /* fall through to warning / null */\n }\n }\n\n // 3. Multiple canvases and no ancestor — warn once, return null.\n if (\n containers.length > 1\n && !(window as any).__alpineflowSchemaMultiCanvasWarned\n ) {\n (window as any).__alpineflowSchemaMultiCanvasWarned = true;\n console.warn(\n '[alpineflow/schema] inspector directive found multiple .flow-container elements on the page; '\n + 'place inspector inside the canvas OR scope the directive expression to a specific canvas '\n + '(multi-canvas scope selector is on the v0.2.2 roadmap).',\n );\n }\n\n return null;\n}\n\n/**\n * Locate the opt-in default-UI template directly inside the directive element.\n *\n * Scoped to `:scope > template[x-schema-default-ui]` so nested inspector\n * consumers can't accidentally collide with a parent scaffold.\n */\nexport function findDefaultUiTemplate(el: HTMLElement): HTMLTemplateElement | null {\n return el.querySelector(\n ':scope > template[x-schema-default-ui]',\n ) as HTMLTemplateElement | null;\n}\n\n/**\n * Remove any previously-stamped default-UI content so the next render can\n * replace it cleanly. We mark our managed root with a data attribute and only\n * touch that — host children (siblings of the template) are never disturbed.\n */\nexport function clearStampedUi(el: HTMLElement): void {\n const existing = el.querySelector(':scope > [data-schema-default-ui-root]');\n if (existing) {\n existing.remove();\n }\n}\n\n/**\n * Append a managed root after the template and return it for content stamping.\n * The managed root carries `data-schema-default-ui-root` so we can find and\n * replace it on every re-render.\n */\nexport function createStampRoot(el: HTMLElement): HTMLElement {\n const root = document.createElement('div');\n root.setAttribute('data-schema-default-ui-root', '');\n el.appendChild(root);\n return root;\n}\n\n/**\n * Snapshot of a focused input inside a stamp root so we can re-focus the\n * equivalent element after a re-stamp. Identity is resolved via `data-field`\n * (our own marker on inspector inputs) and a tag-name match.\n */\nexport interface StampFocusSnapshot {\n field: string;\n tagName: string;\n selectionStart: number | null;\n selectionEnd: number | null;\n}\n\n/**\n * Capture the currently-focused element within a stamp root so re-stamps can\n * restore focus. Returns `null` when focus isn't within the root, or the\n * focused element has no `data-field` identity marker.\n */\nexport function captureStampFocus(\n root: HTMLElement | null | undefined,\n): StampFocusSnapshot | null {\n if (!root) {\n return null;\n }\n const active = document.activeElement;\n if (!active || !(active instanceof HTMLElement) || !root.contains(active)) {\n return null;\n }\n const field = active.getAttribute('data-field');\n if (!field) {\n return null;\n }\n let selectionStart: number | null = null;\n let selectionEnd: number | null = null;\n if (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) {\n try {\n selectionStart = active.selectionStart;\n selectionEnd = active.selectionEnd;\n } catch {\n /* Some input types (e.g. checkbox, number) throw on selection access. */\n }\n }\n return {\n field,\n tagName: active.tagName.toLowerCase(),\n selectionStart,\n selectionEnd,\n };\n}\n\n/**\n * Escape an attribute value for safe embedding in a CSS selector. Prefers\n * the native `CSS.escape` when available (all modern browsers) and falls\n * back to a minimal escaper for environments without it (e.g. older jsdom).\n */\nfunction escapeAttrValue(value: string): string {\n if (typeof (globalThis as any).CSS !== 'undefined' && typeof (globalThis as any).CSS.escape === 'function') {\n return (globalThis as any).CSS.escape(value);\n }\n return value.replace(/[\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * Restore focus after a re-stamp. Looks up the element by `data-field` within\n * the new root (requiring a matching tag name) and re-focuses it, restoring\n * the selection range when possible. Silent on failure — focus preservation\n * is best-effort and must never crash the re-stamp cycle.\n */\nexport function restoreStampFocus(\n root: HTMLElement | null | undefined,\n captured: StampFocusSnapshot | null,\n): void {\n if (!root || !captured) {\n return;\n }\n const candidate = root.querySelector<HTMLElement>(\n `[data-field=\"${escapeAttrValue(captured.field)}\"]`,\n );\n if (!candidate) {\n return;\n }\n if (candidate.tagName.toLowerCase() !== captured.tagName) {\n return;\n }\n try {\n candidate.focus({ preventScroll: true });\n if (\n (candidate instanceof HTMLInputElement || candidate instanceof HTMLTextAreaElement)\n && captured.selectionStart !== null\n && captured.selectionEnd !== null\n ) {\n candidate.setSelectionRange(captured.selectionStart, captured.selectionEnd);\n }\n } catch {\n /* silent — focus failures shouldn't crash the re-stamp */\n }\n}\n","// ============================================================================\n// x-schema-node-inspector Directive\n//\n// Attach to any container (e.g. `<aside x-schema-node-inspector>`) to expose\n// the currently-selected node + schema helpers to the subtree. Optionally\n// stamps a minimal default field-list UI when a child\n// `<template x-schema-default-ui>` is present.\n//\n// Exposed scope (via `Alpine.addScopeToNode`):\n// selectedNode — reactive FlowNode | null\n// inspector.addField(f) — append field to selected node\n// inspector.renameField(o,n) — rename field on selected node\n// inspector.removeField(name) — remove field from selected node\n// inspector.reorderFields(names) — reorder fields on selected node\n//\n// The default UI (when opted in) is structural HTML only:\n// <div data-schema-default-ui-root>\n// <div data-schema-inspector-empty>No node selected.</div> ← empty state\n// — OR —\n// <header data-schema-inspector-label>User</header>\n// <ul data-schema-inspector-fields>\n// <li data-schema-inspector-field>\n// <span>id</span><button data-action=\"remove\">remove</button>\n// </li>\n// ...\n// </ul>\n// <form data-schema-inspector-add-field>\n// <input data-field=\"name\"><input data-field=\"type\"><button>add</button>\n// </form>\n// </div>\n//\n// Consumer themes style via CSS. This directive writes no styles of its own.\n// ============================================================================\n\nimport { canvasTranslator } from '../../core/translations';\nimport type { Alpine } from 'alpinejs';\nimport {\n lastInSet,\n findCanvasScope,\n findDefaultUiTemplate,\n clearStampedUi,\n createStampRoot,\n captureStampFocus,\n restoreStampFocus,\n} from './shared';\n\nexport function registerNodeInspectorDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-node-inspector',\n (el, _spec, { effect, cleanup }) => {\n const host = el as HTMLElement;\n const canvas = findCanvasScope(Alpine, host);\n if (!canvas) {\n return;\n }\n\n const template = findDefaultUiTemplate(host);\n\n // Build the inspector helper object. These thin wrappers close over\n // the current selection so consumers don't have to thread nodeId\n // through every call.\n const inspector = {\n addField(field: any) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection' };\n }\n return canvas.addField?.(id, field) ?? { applied: false, reason: 'no-helper' };\n },\n renameField(oldName: string, newName: string) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection', cascadedEdgeIds: [] };\n }\n return (\n canvas.renameField?.(id, oldName, newName) ?? {\n applied: false,\n reason: 'no-helper',\n cascadedEdgeIds: [],\n }\n );\n },\n removeField(fieldName: string) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection', droppedEdgeIds: [] };\n }\n return (\n canvas.removeField?.(id, fieldName) ?? {\n applied: false,\n reason: 'no-helper',\n droppedEdgeIds: [],\n }\n );\n },\n reorderFields(order: string[]) {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return { applied: false, reason: 'no-selection' };\n }\n return (\n canvas.reorderFields?.(id, order) ?? {\n applied: false,\n reason: 'no-helper',\n }\n );\n },\n };\n\n // Inject reactive scope onto the inspector element. The `get` on\n // `selectedNode` reads `canvas.selectedNodes` + `canvas.nodes`, so\n // Alpine rewires dependents whenever either changes.\n const removeScope = Alpine.addScopeToNode(host, {\n inspector,\n get selectedNode() {\n const id = lastInSet(canvas.selectedNodes);\n if (!id) {\n return null;\n }\n return canvas.nodes?.find((n: any) => n.id === id) ?? null;\n },\n });\n\n // Default-UI stamping. If no template is present, we do nothing\n // and the host's own children render through Alpine as normal.\n if (template) {\n effect(() => {\n stampNodeDefaultUi(host, canvas);\n });\n }\n\n cleanup(() => {\n clearStampedUi(host);\n removeScope?.();\n });\n },\n );\n}\n\nfunction stampNodeDefaultUi(host: HTMLElement, canvas: any): void {\n const t = canvasTranslator(canvas);\n // Capture focus on the previous managed root BEFORE tearing it down, so a\n // reactive re-stamp triggered while the user is typing doesn't blur the\n // focused input.\n const previousRoot = host.querySelector<HTMLElement>(\n ':scope > [data-schema-default-ui-root]',\n );\n const captured = captureStampFocus(previousRoot);\n\n clearStampedUi(host);\n const root = createStampRoot(host);\n\n const id = lastInSet(canvas.selectedNodes);\n const node = id ? canvas.nodes?.find((n: any) => n.id === id) : null;\n\n if (!node) {\n const empty = document.createElement('div');\n empty.setAttribute('data-schema-inspector-empty', '');\n empty.textContent = t('schema.inspector.noNode');\n root.appendChild(empty);\n restoreStampFocus(root, captured);\n return;\n }\n\n const header = document.createElement('header');\n header.setAttribute('data-schema-inspector-label', '');\n header.textContent = String(node.data?.label ?? node.id);\n root.appendChild(header);\n\n const list = document.createElement('ul');\n list.setAttribute('data-schema-inspector-fields', '');\n const fields: any[] = Array.isArray(node.data?.fields) ? node.data.fields : [];\n for (const f of fields) {\n const li = document.createElement('li');\n li.setAttribute('data-schema-inspector-field', '');\n li.dataset.fieldName = String(f?.name ?? '');\n\n const nameSpan = document.createElement('span');\n nameSpan.textContent = String(f?.name ?? '');\n li.appendChild(nameSpan);\n\n if (f?.type) {\n const typeSpan = document.createElement('span');\n typeSpan.setAttribute('data-field-type', '');\n typeSpan.textContent = String(f.type);\n li.appendChild(typeSpan);\n }\n\n const removeBtn = document.createElement('button');\n removeBtn.type = 'button';\n removeBtn.setAttribute('data-action', 'remove');\n removeBtn.textContent = t('schema.inspector.remove');\n removeBtn.addEventListener('click', () => {\n canvas.removeField?.(node.id, f.name);\n });\n li.appendChild(removeBtn);\n\n list.appendChild(li);\n }\n root.appendChild(list);\n\n const form = document.createElement('form');\n form.setAttribute('data-schema-inspector-add-field', '');\n\n const nameInput = document.createElement('input');\n nameInput.setAttribute('data-field', 'name');\n nameInput.placeholder = t('schema.inspector.fieldName');\n form.appendChild(nameInput);\n\n const registry = Array.isArray(canvas._config?.fieldTypeRegistry)\n ? (canvas._config.fieldTypeRegistry as string[])\n : null;\n\n let typeInput: HTMLInputElement | HTMLSelectElement;\n if (registry && registry.length > 0) {\n const select = document.createElement('select');\n select.setAttribute('data-field', 'type');\n for (const type of registry) {\n const option = document.createElement('option');\n option.value = type;\n option.textContent = type;\n select.appendChild(option);\n }\n select.value = registry[0];\n typeInput = select;\n } else {\n const input = document.createElement('input');\n input.setAttribute('data-field', 'type');\n input.placeholder = t('schema.inspector.type');\n input.value = 'text';\n typeInput = input;\n }\n form.appendChild(typeInput);\n\n const addBtn = document.createElement('button');\n addBtn.type = 'submit';\n addBtn.textContent = t('schema.inspector.add');\n form.appendChild(addBtn);\n\n form.addEventListener('submit', (e) => {\n e.preventDefault();\n const fieldName = nameInput.value.trim();\n if (!fieldName) {\n return;\n }\n const rawType = typeInput.value;\n const type = (typeof rawType === 'string' ? rawType.trim() : '') || 'text';\n const result = canvas.addField?.(node.id, { name: fieldName, type });\n if (result?.applied) {\n nameInput.value = '';\n }\n });\n\n root.appendChild(form);\n\n restoreStampFocus(root, captured);\n}\n","// ============================================================================\n// x-schema-row-inspector Directive\n//\n// Attach to any container to expose the currently-selected row\n// (`{nodeId, fieldName}`) + helpers to the subtree. Optionally stamps a\n// minimal default \"edit this field\" UI when a child\n// `<template x-schema-default-ui>` is present.\n//\n// Exposed scope:\n// selectedRow — reactive {nodeId, fieldName} | null\n// inspector.renameField(newName) — rename the selected field\n// inspector.removeField() — remove the selected field\n// inspector.updateField(patch) — mutate arbitrary field props\n// (e.g. type, required) in place\n//\n// Default UI (opt-in):\n// <div data-schema-default-ui-root>\n// <div data-schema-inspector-empty>No row selected.</div>\n// — OR —\n// <label>name <input data-field=\"name\"></label>\n// <label>type <input data-field=\"type\"></label>\n// <label>required <input type=\"checkbox\" data-field=\"required\"></label>\n// <button data-action=\"remove\">remove</button>\n// </div>\n// ============================================================================\n\nimport { canvasTranslator } from '../../core/translations';\nimport type { Alpine } from 'alpinejs';\nimport {\n lastInSet,\n parseRowId,\n findCanvasScope,\n findDefaultUiTemplate,\n clearStampedUi,\n createStampRoot,\n captureStampFocus,\n restoreStampFocus,\n} from './shared';\n\nexport function registerRowInspectorDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-row-inspector',\n (el, _spec, { effect, cleanup }) => {\n const host = el as HTMLElement;\n const canvas = findCanvasScope(Alpine, host);\n if (!canvas) {\n return;\n }\n\n const template = findDefaultUiTemplate(host);\n\n const currentRow = () => parseRowId(lastInSet(canvas.selectedRows));\n\n const currentField = () => {\n const row = currentRow();\n if (!row) {\n return null;\n }\n const node = canvas.nodes?.find((n: any) => n.id === row.nodeId);\n if (!node) {\n return null;\n }\n const fields: any[] = node.data?.fields ?? [];\n return fields.find((f: any) => f?.name === row.fieldName) ?? null;\n };\n\n const inspector = {\n renameField(newName: string) {\n const row = currentRow();\n if (!row) {\n return { applied: false, reason: 'no-selection', cascadedEdgeIds: [] };\n }\n return (\n canvas.renameField?.(row.nodeId, row.fieldName, newName) ?? {\n applied: false,\n reason: 'no-helper',\n cascadedEdgeIds: [],\n }\n );\n },\n removeField() {\n const row = currentRow();\n if (!row) {\n return { applied: false, reason: 'no-selection', droppedEdgeIds: [] };\n }\n return (\n canvas.removeField?.(row.nodeId, row.fieldName) ?? {\n applied: false,\n reason: 'no-helper',\n droppedEdgeIds: [],\n }\n );\n },\n /**\n * Patch non-name properties (type, required, …) of the selected\n * field in place. For name changes, use `renameField` so edges\n * cascade correctly.\n */\n updateField(patch: Record<string, unknown>) {\n const field = currentField();\n if (!field) {\n return { applied: false, reason: 'no-selection' };\n }\n for (const [k, v] of Object.entries(patch)) {\n if (k === 'name') {\n continue; // use renameField\n }\n field[k] = v;\n }\n return { applied: true };\n },\n };\n\n const removeScope = Alpine.addScopeToNode(host, {\n inspector,\n get selectedRow() {\n return currentRow();\n },\n });\n\n if (template) {\n effect(() => {\n stampRowDefaultUi(host, canvas, currentRow());\n });\n }\n\n cleanup(() => {\n clearStampedUi(host);\n removeScope?.();\n });\n },\n );\n}\n\nfunction stampRowDefaultUi(\n host: HTMLElement,\n canvas: any,\n row: { nodeId: string; fieldName: string } | null,\n): void {\n const t = canvasTranslator(canvas);\n // Capture focus on the previous managed root BEFORE tearing it down, so a\n // reactive re-stamp triggered while the user is typing doesn't blur the\n // focused input.\n const previousRoot = host.querySelector<HTMLElement>(\n ':scope > [data-schema-default-ui-root]',\n );\n const captured = captureStampFocus(previousRoot);\n\n clearStampedUi(host);\n const root = createStampRoot(host);\n\n if (!row) {\n const empty = document.createElement('div');\n empty.setAttribute('data-schema-inspector-empty', '');\n empty.textContent = t('schema.inspector.noRow');\n root.appendChild(empty);\n restoreStampFocus(root, captured);\n return;\n }\n\n const node = canvas.nodes?.find((n: any) => n.id === row.nodeId);\n const field = node?.data?.fields?.find((f: any) => f?.name === row.fieldName) ?? null;\n\n if (!field) {\n const missing = document.createElement('div');\n missing.setAttribute('data-schema-inspector-empty', '');\n missing.textContent = t('schema.inspector.missingRow');\n root.appendChild(missing);\n restoreStampFocus(root, captured);\n return;\n }\n\n // Name\n const nameLabel = document.createElement('label');\n nameLabel.textContent = t('schema.inspector.name') + ' ';\n const nameInput = document.createElement('input');\n nameInput.setAttribute('data-field', 'name');\n nameInput.value = String(field.name ?? '');\n nameInput.addEventListener('change', () => {\n const next = nameInput.value.trim();\n if (!next || next === field.name) {\n return;\n }\n canvas.renameField?.(row.nodeId, row.fieldName, next);\n });\n nameLabel.appendChild(nameInput);\n root.appendChild(nameLabel);\n\n // Type\n const typeLabel = document.createElement('label');\n typeLabel.textContent = t('schema.inspector.type') + ' ';\n const typeInput = document.createElement('input');\n typeInput.setAttribute('data-field', 'type');\n typeInput.value = String(field.type ?? '');\n typeInput.addEventListener('change', () => {\n field.type = typeInput.value;\n });\n typeLabel.appendChild(typeInput);\n root.appendChild(typeLabel);\n\n // Required\n const requiredLabel = document.createElement('label');\n requiredLabel.textContent = t('schema.inspector.required') + ' ';\n const requiredInput = document.createElement('input');\n requiredInput.type = 'checkbox';\n requiredInput.setAttribute('data-field', 'required');\n requiredInput.checked = Boolean(field.required);\n requiredInput.addEventListener('change', () => {\n field.required = requiredInput.checked;\n });\n requiredLabel.appendChild(requiredInput);\n root.appendChild(requiredLabel);\n\n // Remove\n const removeBtn = document.createElement('button');\n removeBtn.type = 'button';\n removeBtn.setAttribute('data-action', 'remove');\n removeBtn.textContent = t('schema.inspector.remove');\n removeBtn.addEventListener('click', () => {\n canvas.removeField?.(row.nodeId, row.fieldName);\n });\n root.appendChild(removeBtn);\n\n restoreStampFocus(root, captured);\n}\n","// ============================================================================\n// x-schema-edge-inspector Directive\n//\n// Attach to any container to expose the currently-selected edge + helpers to\n// the subtree. Optionally stamps a minimal label/delete UI when a child\n// `<template x-schema-default-ui>` is present.\n//\n// Exposed scope:\n// selectedEdge — reactive FlowEdge | null\n// inspector.updateEdge(patch) — patch arbitrary props (label, style, …) in place\n// inspector.setLabel(text) — convenience for updating the edge label\n// inspector.removeEdge() — drop the selected edge (delegates to removeEdges)\n//\n// Default UI (opt-in):\n// <div data-schema-default-ui-root>\n// <div data-schema-inspector-empty>No edge selected.</div>\n// — OR —\n// <label>label <input data-field=\"label\"></label>\n// <button data-action=\"delete\">delete</button>\n// </div>\n// ============================================================================\n\nimport { canvasTranslator } from '../../core/translations';\nimport type { Alpine } from 'alpinejs';\nimport {\n lastInSet,\n findCanvasScope,\n findDefaultUiTemplate,\n clearStampedUi,\n createStampRoot,\n captureStampFocus,\n restoreStampFocus,\n} from './shared';\n\nexport function registerEdgeInspectorDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-edge-inspector',\n (el, _spec, { effect, cleanup }) => {\n const host = el as HTMLElement;\n const canvas = findCanvasScope(Alpine, host);\n if (!canvas) {\n return;\n }\n\n const template = findDefaultUiTemplate(host);\n\n const currentEdge = () => {\n const id = lastInSet(canvas.selectedEdges);\n if (!id) {\n return null;\n }\n return canvas.edges?.find((e: any) => e.id === id) ?? null;\n };\n\n const inspector = {\n updateEdge(patch: Record<string, unknown>) {\n const edge = currentEdge();\n if (!edge) {\n return { applied: false, reason: 'no-selection' };\n }\n for (const [k, v] of Object.entries(patch)) {\n edge[k] = v;\n }\n return { applied: true };\n },\n setLabel(label: string) {\n return this.updateEdge({ label });\n },\n removeEdge() {\n const edge = currentEdge();\n if (!edge) {\n return { applied: false, reason: 'no-selection' };\n }\n if (typeof canvas.removeEdges === 'function') {\n canvas.removeEdges([edge.id]);\n return { applied: true };\n }\n // Fallback: splice out of the reactive array directly.\n const idx = canvas.edges?.findIndex((e: any) => e.id === edge.id) ?? -1;\n if (idx === -1) {\n return { applied: false, reason: 'no-helper' };\n }\n canvas.edges.splice(idx, 1);\n return { applied: true };\n },\n };\n\n const removeScope = Alpine.addScopeToNode(host, {\n inspector,\n get selectedEdge() {\n return currentEdge();\n },\n });\n\n if (template) {\n effect(() => {\n stampEdgeDefaultUi(host, canvas, currentEdge());\n });\n }\n\n cleanup(() => {\n clearStampedUi(host);\n removeScope?.();\n });\n },\n );\n}\n\nfunction stampEdgeDefaultUi(host: HTMLElement, canvas: any, edge: any | null): void {\n const t = canvasTranslator(canvas);\n // Capture focus on the previous managed root BEFORE tearing it down, so a\n // reactive re-stamp triggered while the user is typing doesn't blur the\n // focused input.\n const previousRoot = host.querySelector<HTMLElement>(\n ':scope > [data-schema-default-ui-root]',\n );\n const captured = captureStampFocus(previousRoot);\n\n clearStampedUi(host);\n const root = createStampRoot(host);\n\n if (!edge) {\n const empty = document.createElement('div');\n empty.setAttribute('data-schema-inspector-empty', '');\n empty.textContent = t('schema.inspector.noEdge');\n root.appendChild(empty);\n restoreStampFocus(root, captured);\n return;\n }\n\n const labelWrap = document.createElement('label');\n labelWrap.textContent = t('schema.inspector.label') + ' ';\n const labelInput = document.createElement('input');\n labelInput.setAttribute('data-field', 'label');\n labelInput.value = String(edge.label ?? '');\n labelInput.addEventListener('input', () => {\n edge.label = labelInput.value;\n });\n labelWrap.appendChild(labelInput);\n root.appendChild(labelWrap);\n\n const deleteBtn = document.createElement('button');\n deleteBtn.type = 'button';\n deleteBtn.setAttribute('data-action', 'delete');\n deleteBtn.textContent = t('schema.inspector.delete');\n deleteBtn.addEventListener('click', () => {\n if (typeof canvas.removeEdges === 'function') {\n canvas.removeEdges([edge.id]);\n } else {\n const idx = canvas.edges?.findIndex((e: any) => e.id === edge.id) ?? -1;\n if (idx !== -1) {\n canvas.edges.splice(idx, 1);\n }\n }\n });\n root.appendChild(deleteBtn);\n\n restoreStampFocus(root, captured);\n}\n","// ============================================================================\n// x-schema-reorderable Directive\n//\n// Makes a `.flow-schema-row` draggable within its parent `.flow-schema-body`\n// to reorder fields. On drop, commits via `canvas.reorderFields(nodeId,\n// newOrder)`.\n//\n// Opt-in: auto-stamped on rows by `x-flow-schema` when\n// `canvas.rowsReorderable: true`, or manually stamped by consumers writing\n// custom node templates.\n//\n// Conflict with row-select: both directives listen for pointerdown-derived\n// events. This directive only COMMITS a reorder when the cursor moves more\n// than `DRAG_THRESHOLD_PX` vertically; below that it behaves as a click and\n// row-select wins. On a successful drag, the following click event is\n// swallowed (capture-phase listener) so the row isn't selected.\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\n\n/** Pixels of vertical movement before we consider the interaction a drag. */\nconst DRAG_THRESHOLD_PX = 4;\n\nexport function registerSchemaReorderableDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-reorderable',\n (el, _spec, { cleanup }) => {\n const row = el as HTMLElement;\n row.classList.add('flow-schema-reorderable');\n // Prevent browsers from stealing the pointer stream for scroll/zoom\n // gestures during a drag.\n row.style.touchAction = 'none';\n\n // Live drag state — kept in closure so listeners share state.\n let dragging = false;\n let dragged = false;\n let startY = 0;\n let startIndex = 0;\n let currentDropIndex = 0;\n let activePointerId: number | null = null;\n\n /** All sibling rows that participate in the reorder (includes self). */\n const siblingRows = (): HTMLElement[] => {\n const parent = row.parentElement;\n if (!parent) return [];\n return Array.from(\n parent.querySelectorAll(':scope > .flow-schema-row'),\n ) as HTMLElement[];\n };\n\n /** Remove all drop-target classes from sibling rows. */\n const clearDropTargets = (): void => {\n for (const r of siblingRows()) {\n r.classList.remove('flow-schema-row-drop-target');\n }\n };\n\n /**\n * Determine the drop-target index given the current pointer Y.\n *\n * Semantics: the returned index is an insertion index in the\n * \"already-removed\" array — i.e. after splicing the dragging row\n * out of the field list, `newOrder.splice(dropIndex, 0, moved)`\n * yields the final order. It equals the number of OTHER rows\n * whose midline sits above the cursor.\n *\n * This produces intuitive no-op behaviour: a small nudge within\n * the dragging row's original bounds leaves dropIndex equal to\n * startIndex.\n */\n const computeDropIndex = (clientY: number): number => {\n const parent = row.parentElement;\n if (!parent) return startIndex;\n const others = Array.from(\n parent.querySelectorAll(':scope > .flow-schema-row'),\n ).filter((r) => r !== row) as HTMLElement[];\n if (others.length === 0) return startIndex;\n\n let aboveCount = 0;\n for (const sib of others) {\n const rect = sib.getBoundingClientRect();\n const mid = rect.top + rect.height / 2;\n if (mid < clientY) aboveCount++;\n }\n return aboveCount;\n };\n\n const updateDropTargetClass = (dropIndex: number): void => {\n clearDropTargets();\n const all = siblingRows();\n // Visual hint: highlight the neighbour the dragging row\n // would swap with at the current drop slot. We map the\n // remove-then-insert index back to the nearest sibling.\n let targetIdx = dropIndex;\n if (dropIndex >= startIndex) targetIdx = dropIndex + 1;\n const target = all[targetIdx] ?? all[dropIndex];\n if (target && target !== row) {\n target.classList.add('flow-schema-row-drop-target');\n }\n };\n\n const resetRow = (): void => {\n row.style.transform = '';\n row.classList.remove('flow-schema-row-dragging');\n clearDropTargets();\n };\n\n const onPointerDown = (e: PointerEvent): void => {\n if (dragging) return;\n // Only primary button / pen / touch.\n if (e.button !== undefined && e.button !== 0) return;\n\n dragging = true;\n dragged = false;\n startY = e.clientY;\n activePointerId = e.pointerId ?? null;\n\n const all = siblingRows();\n startIndex = all.indexOf(row);\n currentDropIndex = startIndex;\n\n row.classList.add('flow-schema-row-dragging');\n\n // Try to capture the pointer so subsequent pointermove/up fire\n // on the row even if the cursor leaves it. In jsdom this may\n // not be supported — fall back to document-level listeners in\n // that case.\n try {\n if (activePointerId !== null && typeof row.setPointerCapture === 'function') {\n row.setPointerCapture(activePointerId);\n }\n } catch {\n /* capture not supported — rely on document listeners */\n }\n\n document.addEventListener('pointermove', onPointerMove);\n document.addEventListener('pointerup', onPointerUp);\n document.addEventListener('pointercancel', onPointerUp);\n };\n\n const onPointerMove = (e: PointerEvent): void => {\n if (!dragging) return;\n const deltaY = e.clientY - startY;\n\n if (!dragged && Math.abs(deltaY) > DRAG_THRESHOLD_PX) {\n dragged = true;\n }\n\n row.style.transform = `translateY(${deltaY}px)`;\n\n if (dragged) {\n currentDropIndex = computeDropIndex(e.clientY);\n updateDropTargetClass(currentDropIndex);\n }\n };\n\n const onPointerUp = (e: PointerEvent): void => {\n if (!dragging) return;\n const wasDragged = dragged;\n const dropIndex = currentDropIndex;\n const startIdx = startIndex;\n\n // Release pointer capture if we took it.\n try {\n if (\n activePointerId !== null\n && typeof row.releasePointerCapture === 'function'\n && typeof row.hasPointerCapture === 'function'\n && row.hasPointerCapture(activePointerId)\n ) {\n row.releasePointerCapture(activePointerId);\n }\n } catch {\n /* ignore */\n }\n\n document.removeEventListener('pointermove', onPointerMove);\n document.removeEventListener('pointerup', onPointerUp);\n document.removeEventListener('pointercancel', onPointerUp);\n\n dragging = false;\n activePointerId = null;\n resetRow();\n\n if (!wasDragged) {\n // A click — let row-select handle it.\n return;\n }\n\n // Suppress the click that browsers fire after pointerup. We\n // add a capture-phase listener that swallows the next click\n // event on this row (or its descendants). Self-removes after\n // one tick in case no click arrives.\n const suppressClick = (ev: Event): void => {\n ev.stopImmediatePropagation();\n ev.stopPropagation();\n ev.preventDefault();\n };\n row.addEventListener('click', suppressClick, { capture: true, once: true });\n // Belt-and-suspenders cleanup in case no click fires.\n setTimeout(() => {\n row.removeEventListener('click', suppressClick, { capture: true } as any);\n }, 0);\n\n // Resolve nodeId + canvas from the DOM tree.\n const nodeEl = row.closest('[data-flow-node-id]') as HTMLElement | null;\n const nodeId = nodeEl?.getAttribute('data-flow-node-id') ?? null;\n if (!nodeId) return;\n\n const canvasEl = row.closest('.flow-container') as HTMLElement | null;\n if (!canvasEl) return;\n\n let canvas: any;\n try {\n canvas = Alpine.$data(canvasEl);\n } catch {\n return;\n }\n if (!canvas || typeof canvas.reorderFields !== 'function') return;\n\n // Read the current field order off the canvas node.\n const node = (canvas.nodes ?? []).find((n: any) => n?.id === nodeId);\n const fields: any[] = node?.data?.fields ?? [];\n if (!Array.isArray(fields) || fields.length < 2) return;\n\n const names = fields.map((f: any) => f.name);\n if (startIdx < 0 || startIdx >= names.length) return;\n\n const [moved] = names.splice(startIdx, 1);\n // Clamp dropIndex into the post-removal array's valid range.\n const target = Math.max(0, Math.min(dropIndex, names.length));\n names.splice(target, 0, moved);\n\n // If the order is unchanged, skip the commit — lets\n // canvas.reorderFields stay a pure \"real change\" event.\n const unchanged = names.every(\n (name, i) => fields[i]?.name === name,\n );\n if (unchanged) return;\n\n canvas.reorderFields(nodeId, names);\n\n // `e` (pointerup) isn't a click; we've already installed a\n // capture-phase one-shot click listener above to swallow the\n // synthetic click that browsers fire after pointerup.\n void e;\n };\n\n row.addEventListener('pointerdown', onPointerDown);\n\n cleanup(() => {\n try {\n row.removeEventListener('pointerdown', onPointerDown);\n if (typeof document !== 'undefined') {\n document.removeEventListener('pointermove', onPointerMove);\n document.removeEventListener('pointerup', onPointerUp);\n document.removeEventListener('pointercancel', onPointerUp);\n }\n row.classList.remove('flow-schema-reorderable');\n row.classList.remove('flow-schema-row-dragging');\n clearDropTargets();\n row.style.transform = '';\n row.style.touchAction = '';\n } catch {\n /* environment may be torn down (jsdom) */\n }\n });\n },\n );\n}\n","// ============================================================================\n// x-schema-keyboard-nav Directive\n//\n// Makes a `.flow-schema-row` focusable and keyboard-navigable:\n// - Arrow Up / Down : move focus to previous / next row within the same node\n// - Tab / Shift+Tab : move focus to the first / last row of the next /\n// previous node. When at the outermost row with no\n// neighbor, default tab behaviour is preserved so focus\n// can exit the canvas naturally.\n// - Enter / Space : trigger row selection (reuses the row's own click\n// handler so `x-flow-row-select` remains the single\n// authoritative selection path).\n// - Escape : blur the focused row.\n//\n// The directive also stamps `tabindex=\"0\"`, `role=\"row\"`, and a reactive\n// `aria-label` so screen readers can announce the field name and type.\n//\n// Opt-in: auto-stamped on rows by `x-flow-schema` when\n// `canvas._config.keyboardConnect: true`. The keyboard-connect flag is reused\n// intentionally — consumers that opt into keyboard-driven connect almost\n// always also want keyboard-driven field focus, so bundling them keeps the\n// opt-in surface small.\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\n\n/**\n * Sibling rows within the same `.flow-schema-body` — used for ArrowUp /\n * ArrowDown. Uses `:scope > .flow-schema-row` so nested schema tables (a\n * future-proofing concern) do not leak their rows into the iteration.\n */\nfunction siblingRowsOf(row: HTMLElement): HTMLElement[] {\n const body = row.parentElement;\n if (!body) return [];\n return Array.from(\n body.querySelectorAll(':scope > .flow-schema-row'),\n ) as HTMLElement[];\n}\n\n/**\n * Move focus to the row `direction` slots away (±1) within the same node.\n * No-op when the target slot is out of range — we deliberately do not wrap\n * so the focus indicator stays predictable during rapid arrow presses.\n */\nfunction moveWithinNode(row: HTMLElement, direction: 1 | -1): void {\n const rows = siblingRowsOf(row);\n const idx = rows.indexOf(row);\n if (idx === -1) return;\n const next = rows[idx + direction];\n if (next) next.focus();\n}\n\n/**\n * Move focus to the first (direction=1) or last (direction=-1) row of the\n * sibling node. Returns true when focus moved — the caller then calls\n * preventDefault on the Tab event. When false, we let the browser handle Tab\n * naturally so focus can leave the canvas.\n *\n * Node discovery walks up to the closest `.flow-container` (the canvas root)\n * and collects every `[data-flow-node-id]` descendant in document order. This\n * mirrors the selector used by `x-schema-reorderable` for nodeId resolution.\n */\nfunction moveBetweenNodes(row: HTMLElement, direction: 1 | -1): boolean {\n const currentNode = row.closest('[data-flow-node-id]') as HTMLElement | null;\n if (!currentNode) return false;\n const container = row.closest('.flow-container') as HTMLElement | null;\n if (!container) return false;\n const allNodes = Array.from(\n container.querySelectorAll('[data-flow-node-id]'),\n ) as HTMLElement[];\n const idx = allNodes.indexOf(currentNode);\n if (idx === -1) return false;\n const next = allNodes[idx + direction];\n if (!next) return false;\n const targetRow = (\n direction === 1\n ? next.querySelector('.flow-schema-row')\n : (() => {\n const rows = next.querySelectorAll('.flow-schema-row');\n return rows.length > 0 ? rows[rows.length - 1] : null;\n })()\n ) as HTMLElement | null;\n if (!targetRow) return false;\n targetRow.focus();\n return true;\n}\n\n/**\n * Trigger selection by dispatching a click on the row. `x-flow-row-select`\n * already listens for clicks and encapsulates single-vs-shift selection logic\n * — reusing its handler keeps this directive a thin a11y shell with no\n * duplicate selection logic to drift out of sync.\n */\nfunction selectRow(row: HTMLElement): void {\n row.click();\n}\n\nexport function registerSchemaKeyboardNavDirective(Alpine: Alpine): void {\n Alpine.directive(\n 'schema-keyboard-nav',\n (el, _spec, { effect, cleanup }) => {\n const row = el as HTMLElement;\n row.setAttribute('tabindex', '0');\n row.setAttribute('role', 'row');\n\n // Reactive aria-label. We read the field name from the row's\n // data-flow-schema-field attribute (stamped by x-flow-schema) and\n // the type from the rendered `.flow-schema-row-type` span. Running\n // this inside `effect` means Alpine re-invokes it on any reactive\n // mutation that touched these reads — but since these are DOM\n // reads, not reactive state reads, the effect fires once at init.\n // That's fine: x-flow-schema owns the row contents and re-stamps\n // them on field changes, which re-binds this directive and gives\n // us a fresh aria-label read.\n effect(() => {\n const fieldName = row.dataset.flowSchemaField ?? '';\n const typeEl = row.querySelector('.flow-schema-row-type');\n const fieldType = typeEl?.textContent ?? '';\n row.setAttribute(\n 'aria-label',\n `${fieldName}${fieldType ? ' (' + fieldType + ')' : ''}`,\n );\n });\n\n const onKey = (e: KeyboardEvent): void => {\n const key = e.key;\n if (key === 'ArrowDown' || key === 'ArrowUp') {\n e.preventDefault();\n e.stopPropagation();\n moveWithinNode(row, key === 'ArrowDown' ? 1 : -1);\n return;\n }\n if (key === 'Tab') {\n // Intercept Tab so focus jumps between sibling schema\n // nodes instead of walking through every focusable child\n // (handles, inputs, etc.). preventDefault only when we\n // actually moved focus — otherwise the browser's default\n // tab-out lets the user escape the canvas.\n if (moveBetweenNodes(row, e.shiftKey ? -1 : 1)) {\n e.preventDefault();\n }\n return;\n }\n if (key === 'Enter' || key === ' ') {\n e.preventDefault();\n selectRow(row);\n return;\n }\n if (key === 'Escape') {\n row.blur();\n return;\n }\n };\n\n row.addEventListener('keydown', onKey);\n\n cleanup(() => {\n try {\n row.removeEventListener('keydown', onKey);\n row.removeAttribute('tabindex');\n row.removeAttribute('role');\n row.removeAttribute('aria-label');\n } catch {\n /* environment may be torn down (jsdom) */\n }\n });\n },\n );\n}\n","// ============================================================================\n// alpineflow/schema — Subpath Addon\n//\n// Import: `import Schema from '@getartisanflow/alpineflow/schema'`\n// Register: `Alpine.plugin(Schema)`\n//\n// Capabilities are added in Tasks 9–12:\n// - Field CRUD with edge cascade (Task 9) ← landed\n// - inferReferences() (Task 10)\n// - schemaToJSON / schemaFromJSON (Task 11)\n// - Three-scope inspector scaffold (Task 12)\n// ============================================================================\n\nimport type { Alpine } from 'alpinejs';\nimport { registerAddon } from '../core/registry';\nimport { addField, renameField, removeField, reorderFields } from './field-ops';\nimport type {\n AddFieldResult,\n RenameFieldOpResult,\n RemoveFieldOpResult,\n ReorderFieldsOpResult,\n} from './field-ops';\nimport { inferReferences } from './references';\nimport { schemaToJSON, schemaFromJSON } from './serialization';\nimport { validateSchema } from './validate';\nimport { diffSchemas } from './diff';\nimport { toDot } from './dot';\nimport { schemaLayout } from './layout';\nimport { attachSchemaHistory } from './history';\nimport { registerNodeInspectorDirective } from './inspector/node-inspector';\nimport { registerRowInspectorDirective } from './inspector/row-inspector';\nimport { registerEdgeInspectorDirective } from './inspector/edge-inspector';\nimport { registerSchemaReorderableDirective } from './reorderable';\nimport { registerSchemaKeyboardNavDirective } from './keyboard-nav';\nimport type {\n DotExportOptions,\n SchemaLayoutOptions,\n SchemaGraphJSON,\n SchemaValidationResult,\n SchemaDiff,\n DiffOptions,\n ReferenceSuggestion,\n} from './types';\nimport type { FlowSchemaField } from '../core/types';\n\nexport * from './types';\nexport * from './validate';\nexport * from './diff';\nexport * from './dot';\nexport * from './layout';\nexport * from './history';\nexport { addField, renameField, removeField, reorderFields, inferReferences, schemaToJSON, schemaFromJSON, validateSchema, diffSchemas, toDot, schemaLayout, attachSchemaHistory };\nexport { registerNodeInspectorDirective, registerRowInspectorDirective, registerEdgeInspectorDirective, registerSchemaReorderableDirective, registerSchemaKeyboardNavDirective };\nexport type { AddFieldResult, RenameFieldOpResult, RemoveFieldOpResult, ReorderFieldsOpResult } from './field-ops';\n\nexport default function registerSchemaAddon(Alpine: Alpine): void {\n // Register the three-scope inspector directives. Guarded so stub calls in\n // tests (passing `{}` as Alpine) don't throw — only wire up when a real\n // Alpine.directive hook is available.\n if (Alpine && typeof Alpine.directive === 'function') {\n registerNodeInspectorDirective(Alpine);\n registerRowInspectorDirective(Alpine);\n registerEdgeInspectorDirective(Alpine);\n registerSchemaReorderableDirective(Alpine);\n registerSchemaKeyboardNavDirective(Alpine);\n }\n\n registerAddon('schema', {\n setup(canvas: any) {\n // Use the canvas container as the DOM event target so listeners\n // bound via @schema-* attributes on the container fire naturally.\n if (!canvas.el && canvas._container) {\n canvas.el = canvas._container;\n }\n\n canvas.addField = function (nodeId: string, field: any) {\n return addField(this, nodeId, field);\n };\n canvas.renameField = function (nodeId: string, oldName: string, newName: string) {\n return renameField(this, nodeId, oldName, newName);\n };\n canvas.removeField = function (nodeId: string, fieldName: string) {\n return removeField(this, nodeId, fieldName);\n };\n canvas.reorderFields = function (nodeId: string, order: string[]) {\n return reorderFields(this, nodeId, order);\n };\n canvas.inferReferences = function () {\n return inferReferences(this.nodes ?? []);\n };\n canvas.schemaToJSON = function () {\n return schemaToJSON(this);\n };\n canvas.schemaFromJSON = function (json: any) {\n return schemaFromJSON(this, json);\n };\n canvas.validateSchema = function () {\n return validateSchema(this);\n };\n canvas.diffSchemas = function (before: any, after: any, opts?: any) {\n return diffSchemas(before, after, opts);\n };\n canvas.toDot = function (opts?: DotExportOptions) {\n return toDot(this, opts);\n };\n canvas.schemaLayout = function (opts?: SchemaLayoutOptions) {\n return schemaLayout(this, opts);\n };\n },\n });\n}\n\n// ============================================================================\n// Type augmentation — declare the methods `setup()` attaches at runtime on the\n// shared `CanvasContext` interface, so consumers get typed access without\n// importing the standalone `addField(canvas, …)` helpers and casting.\n//\n// Scoped to this entry's emitted types: the augmentation only reaches a program\n// that imports `@getartisanflow/alpineflow/schema`. Purely type-level — erased\n// from the JS bundle. Signatures mirror the wrapped standalone functions above.\n// ============================================================================\ndeclare module '../plugin/data/canvas-context' {\n interface CanvasContext {\n /** Append a field to a schema node. Rejects invalid/duplicate names silently. _(schema addon)_ */\n addField(nodeId: string, field: FlowSchemaField): AddFieldResult;\n /** Rename a field, cascading the change onto edges that reference it. _(schema addon)_ */\n renameField(nodeId: string, oldName: string, newName: string): RenameFieldOpResult;\n /** Remove a field, dropping edges that referenced it. _(schema addon)_ */\n removeField(nodeId: string, fieldName: string): RemoveFieldOpResult;\n /** Reorder a node's fields to match `order` (a list of field names). _(schema addon)_ */\n reorderFields(nodeId: string, order: string[]): ReorderFieldsOpResult;\n /** Suggest reference edges inferred from `<stem>_id` field-name conventions. _(schema addon)_ */\n inferReferences(): ReferenceSuggestion[];\n /** Serialize the schema graph to a stable, versioned JSON shape. _(schema addon)_ */\n schemaToJSON(): SchemaGraphJSON;\n /** Merge a schema-graph JSON into the live canvas nodes/edges. _(schema addon)_ */\n schemaFromJSON(json: SchemaGraphJSON): void;\n /** Validate the schema graph (dangling edges, duplicate fields, cycles, …). _(schema addon)_ */\n validateSchema(): SchemaValidationResult;\n /** Compute a structured delta between two schema snapshots. _(schema addon)_ */\n diffSchemas(before: SchemaGraphJSON, after: SchemaGraphJSON, opts?: DiffOptions): SchemaDiff;\n /** Render the schema graph as a graphviz DOT string. _(schema addon)_ */\n toDot(opts?: DotExportOptions): string;\n /** Lay out schema nodes by their reference graph. _(schema addon)_ */\n schemaLayout(opts?: SchemaLayoutOptions): Promise<void>;\n }\n}\n"],"names":["REGISTRY_KEY","getRegistry","registerAddon","name","value","cascadeEdgesOnRename","edges","nodeId","oldName","newName","cascadedIds","e","next","cascadeEdgesOnRemove","fieldName","droppedIds","touches","FIELD_NAME_RE","MAX_FIELD_NAME_LENGTH","isValidFieldName","dispatchSchema","canvas","type","detail","el","captured","win","onError","event","err","findNode","n","addField","field","node","f","renameField","fields","target","currentEdges","updatedEdges","updatedById","edge","upd","removeField","idx","dropSet","i","reorderFields","order","existingNames","orderNames","byName","reordered","inferReferences","nodes","byId","suggestions","stem","targetFields","toFieldName","jsonEqual","a","b","mergeEntitiesById","existing","incoming","opts","deleteMissing","existingById","merged","inc","cur","key","schemaToJSON","schemaFromJSON","json","incomingNodes","incomingEdges","mergedNodes","mergedEdges","hasCycle","adj","ensure","id","list","WHITE","GRAY","BLACK","color","start","stack","frame","neighbors","c","validateSchema","issues","nodeIds","dupNodeIds","seen","dup","edgeId","touched","safeNodes","snap","safeEdges","fieldsByName","map","diffSchemas","before","after","beforeNodes","afterNodes","beforeEdges","afterEdges","beforeNodeMap","afterNodeMap","rawAddedNodes","rawRemovedNodes","renamedNodes","consumedAddedNodes","consumedRemovedNodes","sigFor","removedId","removedNode","sig","candidates","addedId","addedNode","toId","addedNodes","removedNodes","pairs","r","fieldRenamesByAfterNodeId","hint","renameFromToTo","mapped","renamedFields","addedFields","removedFields","changedFieldTypes","beforeId","afterId","beforeNode","afterNode","beforeFields","afterFields","hints","consumedBefore","consumedAfter","oldField","newField","oldType","newType","beforeField","afterField","beforeEdgeIds","afterEdgeIds","addedEdges","removedEdges","fieldKey","k","DEFAULTS","escapeHTML","s","escapeQuoted","renderNode","o","label","colSpan","rows","cells","marker","renderEdge","source","sourcePort","targetPort","toDot","lines","DEFAULT_ORDER","schemaLayout","direction","nodeSpacing","rankSpacing","preferred","resolvePreferredOrder","swap","prepareEdgeSwap","algo","tryDagre","tryTree","applyGridLayout","pinned","original","inferred","suggestion","index","count","cols","cellWidth","cellHeight","col","row","x","y","TRACKED_EVENTS","attachSchemaHistory","limit","undoStack","redoStack","suspendDepth","batchDepth","batchEntrySnapshot","disposed","makeNoopHandle","evictOldest","pushDeduped","top","pushSnapshot","onEvent","applySnapshot","current","prev","fn","result","entry","englishMessages","en","FALLBACK_LOCALE","pluralRulesCache","resolvePluralRules","locale","tag","rules","usable","pickMessage","table","placeholderPatternCache","substitute","message","values","names","signature","pattern","_match","createTranslator","translations","overrides","text","localeRules","englishRules","englishTranslator","canvasTranslator","scope","lastInSet","set","last","parseRowId","rowId","dot","findCanvasScope","Alpine","ancestor","containers","findDefaultUiTemplate","clearStampedUi","createStampRoot","root","captureStampFocus","active","selectionStart","selectionEnd","escapeAttrValue","restoreStampFocus","candidate","registerNodeInspectorDirective","_spec","effect","cleanup","host","template","inspector","removeScope","stampNodeDefaultUi","t","previousRoot","empty","header","li","nameSpan","typeSpan","removeBtn","form","nameInput","registry","typeInput","select","option","input","addBtn","rawType","registerRowInspectorDirective","currentRow","currentField","patch","v","stampRowDefaultUi","missing","nameLabel","typeLabel","requiredLabel","requiredInput","registerEdgeInspectorDirective","currentEdge","stampEdgeDefaultUi","labelWrap","labelInput","deleteBtn","DRAG_THRESHOLD_PX","registerSchemaReorderableDirective","dragging","dragged","startY","startIndex","currentDropIndex","activePointerId","siblingRows","parent","clearDropTargets","computeDropIndex","clientY","others","aboveCount","sib","rect","updateDropTargetClass","dropIndex","all","targetIdx","resetRow","onPointerDown","onPointerMove","onPointerUp","deltaY","wasDragged","startIdx","suppressClick","ev","canvasEl","moved","siblingRowsOf","body","moveWithinNode","moveBetweenNodes","currentNode","container","allNodes","targetRow","selectRow","registerSchemaKeyboardNavDirective","fieldType","onKey","registerSchemaAddon"],"mappings":"AAaA,MAAMA,IAAe;AAEd,SAASC,KAAgC;AAC9C,SAAI,OAAO,aAAe,OAClB,WAAmBD,CAAY,MAClC,WAAmBA,CAAY,IAAI,oBAAI,IAAA,IAElC,WAAmBA,CAAY,yBAG9B,IAAA;AACb;AAEO,SAASE,GAAcC,GAAcC,GAAkB;AAC5D,EAAAH,KAAc,IAAIE,GAAMC,CAAK;AAC/B;ACCO,SAASC,GACZC,GACAC,GACAC,GACAC,GACsB;AACtB,QAAMC,IAAwB,CAAA;AAc9B,SAAO,EAAE,OAbOJ,EAAM,IAAI,CAACK,MAAM;AAC7B,QAAIC,IAAUD;AACd,WAAIA,EAAE,WAAWJ,KAAUI,EAAE,iBAAiBH,MAC1CI,IAAO,EAAE,GAAGA,GAAM,cAAcH,EAAA,IAEhCE,EAAE,WAAWJ,KAAUI,EAAE,iBAAiBH,MAC1CI,IAAO,EAAE,GAAGA,GAAM,cAAcH,EAAA,IAEhCG,MAASD,KACTD,EAAY,KAAKC,EAAE,EAAE,GAElBC;AAAA,EACX,CAAC,GACwB,aAAAF,EAAA;AAC7B;AAMO,SAASG,GACZP,GACAC,GACAO,GACsB;AACtB,QAAMC,IAAuB,CAAA;AAU7B,SAAO,EAAE,OATIT,EAAM,OAAO,CAACK,MAAM;AAC7B,UAAMK,IACDL,EAAE,WAAWJ,KAAUI,EAAE,iBAAiBG,KAC1CH,EAAE,WAAWJ,KAAUI,EAAE,iBAAiBG;AAC/C,WAAIE,KACAD,EAAW,KAAKJ,EAAE,EAAE,GAEjB,CAACK;AAAA,EACZ,CAAC,GACqB,YAAAD,EAAA;AAC1B;ACvDA,MAAME,KAAgB,qBAChBC,KAAwB;AAE9B,SAASC,GAAiBhB,GAAuB;AAC7C,SAAO,OAAOA,KAAS,YAAYA,EAAK,UAAUe,MAAyBD,GAA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