@ai-matrx/code-runtime 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/scope/build.ts","../src/gate-lists.json","../src/scope/entries.ts","../src/scope/modules.ts","../src/scope/stand-in.ts"],"sourcesContent":["/**\n * Building a compile's scope: the flat values passed as function parameters\n * (so bodies that use `useState` or an icon without importing it keep\n * working) and the per-path module views `require` hands out.\n *\n * Behavior ported from matrx-frontend `allowed-imports.ts`\n * (`buildComponentScope`, `bindImportedIdentifiers`, the safe proxy) and\n * `toolRendererScope.ts` (namespace entries), collapsed into one builder.\n */\nimport * as ReactModule from \"react\";\n\nimport lists from \"../gate-lists.json\";\nimport type { ScopeSpec, UnresolvedImport } from \"../types\";\nimport { getScopeEntry, type ScopeEntryDeclaration } from \"./entries\";\nimport { announceFailedModule, readScopeModule } from \"./modules\";\nimport { createUnresolvedImportStandIn, readUnresolvedImportMark } from \"./stand-in\";\n\ntype AnyRecord = Record<string, unknown>;\n\nexport interface ScopeState {\n /** Flat scope: name → value (the function parameters). */\n values: AnyRecord;\n /** path → the module object `require(path)` returns. */\n modules: Map<string, AnyRecord>;\n /** Paths whose missing PascalCase names resolve to stand-ins. */\n safeProxyPaths: Map<string, { proxy: AnyRecord; keys: Set<string> }>;\n unresolved: UnresolvedImport[];\n /** Entries whose async module is not loaded yet (`prepareScope` first). */\n pending: string[];\n}\n\nexport function recordUnresolved(state: Pick<ScopeState, \"unresolved\">, entry: UnresolvedImport): void {\n if (!state.unresolved.some((e) => e.identifier === entry.identifier && e.importPath === entry.importPath)) {\n state.unresolved.push(entry);\n }\n}\n\nfunction asRecord(value: unknown): AnyRecord {\n return value && (typeof value === \"object\" || typeof value === \"function\") ? (value as AnyRecord) : {};\n}\n\nfunction ownKeys(mod: AnyRecord): string[] {\n try {\n return Object.keys(mod);\n } catch {\n return [];\n }\n}\n\n/** Missing PascalCase keys → a visible stand-in (icon sets). */\nfunction createSafeModuleProxy(importPath: string, moduleExports: AnyRecord, state: Pick<ScopeState, \"unresolved\">): AnyRecord {\n const target: AnyRecord = { ...moduleExports, __esModule: true };\n return new Proxy(target, {\n get(t, prop) {\n if (typeof prop !== \"string\") return Reflect.get(t, prop);\n if (prop in t) return t[prop];\n if (prop.startsWith(\"_\") || prop === \"default\" || prop === \"then\") return undefined;\n if (/^[A-Z]/.test(prop)) {\n const fallback = createUnresolvedImportStandIn(prop, importPath);\n t[prop] = fallback;\n recordUnresolved(state, { identifier: prop, importPath });\n return fallback;\n }\n return undefined;\n },\n has(t, prop) {\n if (typeof prop === \"string\" && /^[A-Z]/.test(prop)) return true;\n return prop in t;\n },\n });\n}\n\n/** The module object `require(path)` answers for one loaded entry. */\nfunction moduleView(entry: ScopeEntryDeclaration, mod: AnyRecord, state: Pick<ScopeState, \"unresolved\">): AnyRecord {\n if (entry.strategy === \"namespace\") {\n const ns = asRecord(mod.default ?? mod);\n return { ...ns, default: ns, __esModule: true };\n }\n if (entry.safeProxy) return createSafeModuleProxy(entry.path, mod, state);\n const view: AnyRecord = { ...mod, __esModule: true };\n for (const [moduleKey, scopeKey] of Object.entries(entry.exportMap ?? {})) {\n const value = moduleKey === \"default\" ? (mod.default ?? mod) : mod[moduleKey];\n view[scopeKey] = value;\n if (moduleKey === \"default\") view.default = value;\n }\n // A module with no default export has no default: `import X from` it is\n // reported and stands in (link time), never silently the module object.\n if (!(\"default\" in view)) view.default = mod.default;\n return view;\n}\n\nfunction applyToFlatScope(entry: ScopeEntryDeclaration, mod: AnyRecord, values: AnyRecord): void {\n if (entry.strategy === \"namespace\") {\n if (entry.namespaceName) values[entry.namespaceName] = mod.default ?? mod;\n return;\n }\n if (entry.strategy === \"spread\") {\n for (const key of ownKeys(mod)) {\n if (key === \"default\" || key === \"__esModule\") continue;\n values[key] = mod[key];\n }\n return;\n }\n for (const name of entry.exports ?? []) values[name] = mod[name];\n for (const [moduleKey, scopeKey] of Object.entries(entry.exportMap ?? {})) {\n values[scopeKey] = moduleKey === \"default\" ? (mod.default ?? mod) : mod[moduleKey];\n }\n}\n\n/**\n * Throwing stubs for the globals stored code may not use. Named error, never\n * silence: the reader's error boundary shows which global it reached for.\n * BACKSTOP, not a sandbox — bare identifiers only; `window.fetch` still\n * resolves. The write-time gate refuses `window.fetch`; the sandbox frame is\n * the real boundary.\n */\nexport function buildDangerousGlobalStubs(): AnyRecord {\n const stubs: AnyRecord = {};\n for (const name of [...lists.bannedGlobals, ...lists.bannedCallables]) {\n stubs[name] = function bannedGlobal(): never {\n throw new Error(\n `This component tried to use \"${name}\". Components stored in the ` +\n \"database run inside the signed-in page and may not reach the \" +\n \"network, browser storage, or the JavaScript evaluator. Render what \" +\n \"the Shape hands you in props.data, and use a Shape action for \" +\n \"anything you need from the server.\",\n );\n };\n }\n return stubs;\n}\n\n/** Build the full scope state for a spec. Never throws. */\nexport function buildScopeState(spec: ScopeSpec): ScopeState {\n const state: ScopeState = { values: {}, modules: new Map(), safeProxyPaths: new Map(), unresolved: [], pending: [] };\n const R = ReactModule as unknown as AnyRecord;\n // React core is always present (classic JSX needs `React`).\n state.values.React = R;\n for (const hook of [\"useState\", \"useEffect\", \"useMemo\", \"useCallback\", \"useRef\"]) state.values[hook] = R[hook];\n state.modules.set(\"react\", { ...R, default: R, __esModule: true });\n\n for (const path of spec.entries ?? []) {\n const entry = getScopeEntry(path);\n if (!entry) {\n recordUnresolved(state, { identifier: \"*\", importPath: path });\n continue;\n }\n const read = readScopeModule(path);\n if (read.state === \"pending\") {\n state.pending.push(path);\n continue;\n }\n if (read.state === \"missing\") {\n // A host-owned entry this host did not supply: nothing to report until\n // code reaches for it (an import of it, or a bare name, is recorded then).\n continue;\n }\n if (read.state === \"failed\") {\n // Announced once per page (loud), and a gap only for code that reaches\n // for it — an import of it, or a bare name, is recorded at link time.\n announceFailedModule(path, read.message);\n continue;\n }\n const mod = asRecord(read.module);\n const view = moduleView(entry, mod, state);\n state.modules.set(path, view);\n if (entry.safeProxy) {\n state.safeProxyPaths.set(path, { proxy: view, keys: new Set(ownKeys(mod)) });\n }\n applyToFlatScope(entry, mod, state.values);\n }\n\n if (state.values.MarkdownStream && !state.values.Markdown) state.values.Markdown = state.values.MarkdownStream;\n if (!state.values.DynamicIcon) {\n const icons = readScopeModule(\"@ai-matrx/icons\");\n if (icons.state === \"ready\") {\n const m = asRecord(icons.module);\n state.values.DynamicIcon = m.DynamicIcon;\n state.values.renderIcon = m.renderIcon;\n state.values.getIconComponent = m.getIconComponent;\n }\n }\n const overrides = spec.overrides ?? {};\n Object.assign(state.values, overrides);\n // An override replaces the NAME everywhere code can reach it — the flat\n // scope and every module view that exports it (named, or as its mapped\n // default), so `import Md from \"@/components/MarkdownStream\"` gets the\n // host's runtime-aware renderer too.\n if (Object.keys(overrides).length > 0) {\n for (const [path, view] of state.modules) {\n const entry = getScopeEntry(path);\n for (const [moduleKey, scopeKey] of Object.entries(entry?.exportMap ?? {})) {\n if (!(scopeKey in overrides)) continue;\n view[scopeKey] = overrides[scopeKey];\n if (moduleKey === \"default\") view.default = overrides[scopeKey];\n else view[moduleKey] = overrides[scopeKey];\n }\n for (const name of entry?.exports ?? []) {\n if (name in overrides) view[name] = overrides[name];\n }\n }\n }\n if (spec.shadowDangerousGlobals) Object.assign(state.values, buildDangerousGlobalStubs());\n return state;\n}\n\n/**\n * `buildScope` (CONTRACTS §7): the named, documented values a spec puts in\n * scope. Async entries not yet prepared are absent (see `prepareScope`).\n */\nexport function buildScope(spec: ScopeSpec): Record<string, unknown> {\n return { ...buildScopeState(spec).values };\n}\n\n/**\n * A stand-in for every bare JSX reference no scope value, module export or\n * author declaration supplies. Each is recorded.\n */\nexport function patchMissingJsx(\n identifiers: Iterable<string>,\n state: ScopeState,\n declared: ReadonlySet<string>,\n skip: ReadonlySet<string>,\n): void {\n for (const identifier of identifiers) {\n if (skip.has(identifier) || identifier in state.values || declared.has(identifier)) continue;\n let provided = false;\n for (const [, { proxy, keys }] of state.safeProxyPaths) {\n if (!keys.has(identifier)) continue;\n const value = proxy[identifier];\n if (value !== undefined) {\n state.values[identifier] = value;\n const mark = readUnresolvedImportMark(value);\n if (mark) recordUnresolved(state, mark);\n provided = true;\n break;\n }\n }\n if (provided) continue;\n state.values[identifier] = createUnresolvedImportStandIn(identifier);\n recordUnresolved(state, { identifier, importPath: null });\n }\n}\n","{\n \"_comment\": [\n \"CANONICAL, MACHINE-READABLE source-gate lists for stored code compiled by @ai-matrx/code-runtime.\",\n \"ONE list per rule, sorted, byte-comparable across runtimes. Three guards keep the copies honest:\",\n \" - src/gate.test.ts asserts allowedImports equals listScopeEntryPaths() sorted\",\n \" (the documented scope registry is the truth);\",\n \" - aidream packages/matrx-ai/tests/test_component_source_gate_parity.py asserts the Python\",\n \" twins in kind_shared.py equal these arrays;\",\n \" - the database trigger's parity test asserts the trigger names every entry of every\",\n \" security list below.\"\n ],\n \"allowedImports\": [\n \"@/applets\",\n \"@/components/Markdown\",\n \"@/components/MarkdownStream\",\n \"@/components/agent-copy/CopyButtons\",\n \"@/components/agent-copy/CopyForAiButton\",\n \"@/components/kind-kit/KindHeaderBar\",\n \"@/components/kind-kit/KindPanel\",\n \"@/components/kind-kit/KindPanelGrid\",\n \"@/components/kind-kit/SortableList\",\n \"@/components/kind-kit/StreamingSkeleton\",\n \"@/components/kind-kit/TagList\",\n \"@/components/mardown\",\n \"@/components/markdown\",\n \"@/components/official/icons/IconResolver\",\n \"@/components/ui/accordion\",\n \"@/components/ui/alert\",\n \"@/components/ui/avatar\",\n \"@/components/ui/badge\",\n \"@/components/ui/button\",\n \"@/components/ui/card\",\n \"@/components/ui/checkbox\",\n \"@/components/ui/collapsible\",\n \"@/components/ui/dialog\",\n \"@/components/ui/dropdown-menu\",\n \"@/components/ui/input\",\n \"@/components/ui/label\",\n \"@/components/ui/popover\",\n \"@/components/ui/progress\",\n \"@/components/ui/radio-group\",\n \"@/components/ui/scroll-area\",\n \"@/components/ui/select\",\n \"@/components/ui/separator\",\n \"@/components/ui/sheet\",\n \"@/components/ui/skeleton\",\n \"@/components/ui/slider\",\n \"@/components/ui/switch\",\n \"@/components/ui/table\",\n \"@/components/ui/tabs\",\n \"@/components/ui/textarea\",\n \"@/components/ui/tooltip\",\n \"@/lib/utils\",\n \"@ai-matrx/applets/react\",\n \"@ai-matrx/design-system\",\n \"@ai-matrx/design-system/controls\",\n \"@ai-matrx/icons\",\n \"@react-three/fiber\",\n \"date-fns\",\n \"lodash\",\n \"lucide-react\",\n \"motion/react\",\n \"react\",\n \"react-katex\",\n \"react-pdf\",\n \"recharts\",\n \"three\",\n \"xlsx\"\n ],\n \"bannedGlobals\": [\n \"EventSource\",\n \"WebSocket\",\n \"XMLHttpRequest\",\n \"fetch\",\n \"importScripts\",\n \"localStorage\",\n \"sessionStorage\"\n ],\n \"bannedCallables\": [\n \"Function\",\n \"eval\"\n ],\n \"bannedMemberAccess\": [\n \"EventSource\",\n \"Function\",\n \"WebSocket\",\n \"XMLHttpRequest\",\n \"cookie\",\n \"eval\",\n \"fetch\",\n \"importScripts\",\n \"sendBeacon\"\n ],\n \"bannedMemberCalls\": [\n \"constructor\"\n ],\n \"bannedComputedAccess\": [\n \"globalThis\",\n \"self\",\n \"window\"\n ],\n \"bannedSyntax\": [\n \"dynamicImport\"\n ]\n}\n","/**\n * THE ONE DOCUMENTED SCOPE REGISTRY — every import path stored code may name.\n *\n * Merged from matrx-frontend's two registries (`agent-apps/utils/\n * allowed-imports.ts` and `dynamic-react/toolRendererScope.ts`), which\n * disagreed on strategies, lists and loading. Rules that hold:\n * - every entry is EXPLICITLY named and documented; no wildcard;\n * - nothing here reaches data: no database client, no fetch wrapper, no\n * store — data reach belongs to the host (CONTRACTS §1);\n * - an entry is `package`-owned (this package ships its module, so a plain\n * Vite page gets it) or `host`-owned (declared and documented here, the\n * module supplied by the host through `provideScopeModules`); a host entry\n * no host supplied renders named stand-ins and is reported, never crashes;\n * - `@/components/ui/*` are LEGACY ALIASES kept while stored code uses them\n * (census 2026-10-06: 67 kind components, 78 apps). Each names the same\n * design-system export the frontend file re-exports; new code imports\n * `@ai-matrx/design-system/controls` (the primary UI set).\n *\n * Pure data: no React, no module loads — `gate.ts` and servers read it.\n * `gate-lists.json#allowedImports` must equal `listScopeEntryPaths()` sorted\n * (guard: `scope-registry.test.ts`).\n */\n\nexport type ScopeStrategy = \"named\" | \"spread\" | \"namespace\";\n\nexport interface ScopeEntryDeclaration {\n /** The import path stored code writes. */\n path: string;\n /** `named`: listed exports; `spread`: every export; `namespace`: the module under `namespaceName`. */\n strategy: ScopeStrategy;\n exports?: readonly string[];\n /** moduleKey → scope name (`{ default: \"MarkdownStream\" }`). */\n exportMap?: Readonly<Record<string, string>>;\n namespaceName?: string;\n /** Missing PascalCase names resolve to a visible stand-in (icon sets). */\n safeProxy?: boolean;\n /** Always present for chat code blocks (cheap, already in shared chunks). */\n core?: boolean;\n /** Identifiers whose bare use implies this entry (heavy-lib demand detection). */\n provides?: readonly string[];\n owner: \"package\" | \"host\";\n description: string;\n}\n\nconst REACT_EXPORTS = [\n \"useState\", \"useEffect\", \"useMemo\", \"useCallback\", \"useRef\", \"useReducer\", \"useContext\",\n \"useId\", \"useTransition\", \"useDeferredValue\", \"useLayoutEffect\", \"Fragment\",\n] as const;\n\nfunction ui(\n name: string,\n exports: readonly string[],\n description: string,\n): ScopeEntryDeclaration {\n return { path: `@/components/ui/${name}`, strategy: \"named\", exports, core: true, owner: \"package\", description };\n}\n\nfunction markdownAlias(path: string, description: string): ScopeEntryDeclaration {\n return { path, strategy: \"named\", exportMap: { default: \"MarkdownStream\" }, core: true, owner: \"host\", description };\n}\n\nfunction kindKit(name: string, exports: readonly string[], description: string): ScopeEntryDeclaration {\n return { path: `@/components/kind-kit/${name}`, strategy: \"named\", exports, owner: \"host\", description };\n}\n\nexport const SCOPE_ENTRIES: readonly ScopeEntryDeclaration[] = [\n // ── Core ─────────────────────────────────────────────────────────────────\n { path: \"react\", strategy: \"named\", exports: REACT_EXPORTS, exportMap: { default: \"React\" }, core: true, owner: \"package\", description: \"React core (hooks, Fragment)\" },\n { path: \"lucide-react\", strategy: \"spread\", safeProxy: true, core: true, owner: \"package\", description: \"Lucide icons; a missing name renders a marked placeholder\" },\n { path: \"@ai-matrx/icons\", strategy: \"named\", exports: [\"DynamicIcon\", \"renderIcon\", \"getIconComponent\"], core: true, owner: \"package\", description: \"DynamicIcon: any icon by string name\" },\n { path: \"@/components/official/icons/IconResolver\", strategy: \"named\", exports: [\"DynamicIcon\", \"renderIcon\", \"getIconComponent\"], core: true, owner: \"package\", description: \"Legacy alias of @ai-matrx/icons\" },\n { path: \"@/lib/utils\", strategy: \"named\", exports: [\"cn\"], core: true, owner: \"package\", description: \"cn(): className merge\" },\n\n // ── The primary UI set ───────────────────────────────────────────────────\n { path: \"@ai-matrx/design-system/controls\", strategy: \"spread\", core: true, owner: \"package\", description: \"THE controls: Button, Field, SearchField, Select, SegmentedControl, Tabs, Badge, Switch, Textarea, EmptyState…\" },\n { path: \"@ai-matrx/design-system\", strategy: \"spread\", owner: \"package\", description: \"Design-system surfaces: Card, Dialog, Popover, Tooltip, Table, Accordion…\" },\n\n // ── Copy actions ─────────────────────────────────────────────────────────\n { path: \"@/components/agent-copy/CopyButtons\", strategy: \"named\", exports: [\"CopyButtons\"], owner: \"host\", description: \"Copy / Copy-for-AI / JSON / Export bar from caller-supplied builders\" },\n { path: \"@/components/agent-copy/CopyForAiButton\", strategy: \"named\", exports: [\"CopyForAiButton\"], owner: \"host\", description: \"Single Copy-for-AI action\" },\n\n // ── kind-kit ─────────────────────────────────────────────────────────────\n kindKit(\"SortableList\", [\"SortableList\"], \"Drag-to-reorder list with arrow fallback and onRemove\"),\n kindKit(\"KindPanelGrid\", [\"KindPanelGrid\"], \"Content-aware auto-fit grid of equal-height panels\"),\n kindKit(\"KindPanel\", [\"KindPanel\"], \"Compact panel: header + overflow menu, subline, body, footer\"),\n kindKit(\"KindHeaderBar\", [\"KindHeaderBar\"], \"Kind title + stats + copy bar\"),\n kindKit(\"StreamingSkeleton\", [\"StreamingSkeleton\", \"useStreamingValue\", \"streamList\", \"streamText\"], \"Streaming skeletons + tolerant partial-value reads\"),\n kindKit(\"TagList\", [\"KeywordChip\", \"TagList\"], \"Wrapping chips with select, remove, inline edit, add\"),\n\n // ── Markdown (one renderer, four spellings stored code uses) ─────────────\n markdownAlias(\"@/components/MarkdownStream\", \"MarkdownStream: the one markdown renderer\"),\n markdownAlias(\"@/components/Markdown\", \"MarkdownStream (legacy path)\"),\n markdownAlias(\"@/components/markdown\", \"MarkdownStream (lowercase path)\"),\n markdownAlias(\"@/components/mardown\", \"MarkdownStream (common misspelling)\"),\n\n // ── Legacy UI aliases (each = the design-system export the app re-exports) ─\n ui(\"button\", [\"Button\"], \"Button\"),\n ui(\"input\", [\"Input\"], \"Input\"),\n ui(\"textarea\", [\"Textarea\"], \"Textarea\"),\n ui(\"card\", [\"Card\", \"CardAction\", \"CardContent\", \"CardDescription\", \"CardFooter\", \"CardHeader\", \"CardTitle\"], \"Card family\"),\n ui(\"label\", [\"Label\"], \"Label\"),\n ui(\"select\", [\"Select\", \"SelectContent\", \"SelectGroup\", \"SelectItem\", \"SelectLabel\", \"SelectScrollDownButton\", \"SelectScrollUpButton\", \"SelectSeparator\", \"SelectValue\", \"selectTriggerVariants\", \"SelectTrigger\", \"SelectTriggerLegacy\"], \"Select family\"),\n ui(\"slider\", [\"Slider\"], \"Slider\"),\n ui(\"switch\", [\"Switch\"], \"Switch\"),\n ui(\"tabs\", [\"Tabs\", \"TabsContent\", \"TabsList\", \"TabsTrigger\", \"TabsTriggerCore\", \"TabsListLegacy\", \"TabsTriggerLegacy\", \"TabsTriggerCoreLegacy\"], \"Tabs family\"),\n ui(\"badge\", [\"Badge\"], \"Badge\"),\n ui(\"tooltip\", [\"Tooltip\", \"TooltipContent\", \"TooltipProvider\", \"TooltipTrigger\"], \"Tooltip family\"),\n ui(\"accordion\", [\"Accordion\", \"AccordionContent\", \"AccordionItem\", \"AccordionTrigger\", \"useAccordionSize\"], \"Accordion family\"),\n ui(\"collapsible\", [\"Collapsible\", \"CollapsibleContent\", \"CollapsibleTrigger\"], \"Collapsible family\"),\n ui(\"progress\", [\"Progress\"], \"Progress bar\"),\n ui(\"separator\", [\"Separator\"], \"Separator\"),\n ui(\"scroll-area\", [\"ScrollArea\", \"ScrollBar\"], \"ScrollArea\"),\n ui(\"dialog\", [\"Dialog\", \"DialogClose\", \"DialogContent\", \"DialogContentPrimitive\", \"DialogDescription\", \"DialogFooter\", \"DialogHeader\", \"DialogOverlay\", \"DialogPortal\", \"DialogTitle\", \"DialogTrigger\", \"useDialogContainer\"], \"Dialog family\"),\n ui(\"sheet\", [\"Sheet\", \"SheetPortal\", \"SheetOverlay\", \"SheetTrigger\", \"SheetClose\", \"SheetContent\", \"SheetHeader\", \"SheetFooter\", \"SheetTitle\", \"SheetDescription\"], \"Sheet family\"),\n ui(\"dropdown-menu\", [\"DropdownMenu\", \"DropdownMenuCheckboxItem\", \"DropdownMenuContent\", \"DropdownMenuGroup\", \"DropdownMenuItem\", \"DropdownMenuLabel\", \"DropdownMenuPortal\", \"DropdownMenuRadioGroup\", \"DropdownMenuRadioItem\", \"DropdownMenuSeparator\", \"DropdownMenuShortcut\", \"DropdownMenuSub\", \"DropdownMenuSubContent\", \"DropdownMenuSubTrigger\", \"DropdownMenuTrigger\"], \"Dropdown menu family\"),\n ui(\"table\", [\"Table\", \"TableBody\", \"TableCaption\", \"TableCell\", \"TableFooter\", \"TableHead\", \"TableHeader\", \"TableRow\"], \"Table family\"),\n ui(\"checkbox\", [\"Checkbox\"], \"Checkbox\"),\n ui(\"radio-group\", [\"RadioGroup\", \"RadioGroupItem\"], \"Radio group\"),\n ui(\"popover\", [\"Popover\", \"PopoverTrigger\", \"PopoverContent\", \"PopoverAnchor\"], \"Popover family\"),\n ui(\"avatar\", [\"Avatar\", \"AvatarFallback\", \"AvatarImage\"], \"Avatar family\"),\n ui(\"alert\", [\"Alert\", \"AlertDescription\", \"AlertTitle\", \"alertVariants\"], \"Alert family\"),\n ui(\"skeleton\", [\"Skeleton\"], \"Skeleton\"),\n\n // ── Applet parts ─────────────────────────────────────────────────────────\n { path: \"@/applets\", strategy: \"named\", exports: [\"DataPage\", \"Applet\"], owner: \"host\", description: \"A table-built page and a nested Applet (legacy path; becomes @ai-matrx/applets/react)\" },\n { path: \"@ai-matrx/applets/react\", strategy: \"spread\", owner: \"host\", description: \"The Applet hooks: useRows, useJob, useValue, useAction, <Kind>, <Pages>, navigate…\" },\n\n // ── Heavy libraries (loaded only when referenced) ────────────────────────\n { path: \"recharts\", strategy: \"spread\", owner: \"package\", provides: [\"ResponsiveContainer\", \"LineChart\", \"BarChart\", \"AreaChart\", \"PieChart\", \"RadarChart\", \"ScatterChart\", \"ComposedChart\", \"RadialBarChart\"], description: \"Charts (recharts)\" },\n { path: \"motion/react\", strategy: \"spread\", owner: \"host\", provides: [\"motion\", \"AnimatePresence\", \"useAnimate\", \"useInView\"], description: \"Animation (motion)\" },\n { path: \"react-katex\", strategy: \"spread\", owner: \"host\", provides: [\"BlockMath\", \"InlineMath\"], description: \"Math typesetting (KaTeX)\" },\n { path: \"react-pdf\", strategy: \"named\", exports: [\"Document\", \"Page\", \"Outline\"], owner: \"host\", provides: [\"Document\", \"Page\", \"Outline\"], description: \"PDF viewing (react-pdf)\" },\n { path: \"xlsx\", strategy: \"namespace\", namespaceName: \"XLSX\", owner: \"host\", provides: [\"XLSX\"], description: \"Workbooks (xlsx)\" },\n { path: \"@react-three/fiber\", strategy: \"spread\", owner: \"host\", provides: [\"Canvas\", \"useFrame\", \"useThree\", \"useLoader\"], description: \"3D React renderer\" },\n { path: \"three\", strategy: \"namespace\", namespaceName: \"THREE\", owner: \"host\", provides: [\"THREE\"], description: \"3D engine (three.js)\" },\n { path: \"date-fns\", strategy: \"namespace\", namespaceName: \"dateFns\", owner: \"host\", provides: [\"dateFns\"], description: \"Date utilities (date-fns)\" },\n { path: \"lodash\", strategy: \"namespace\", namespaceName: \"_\", owner: \"host\", provides: [\"_\"], description: \"Utility helpers (lodash)\" },\n];\n\nconst BY_PATH = new Map(SCOPE_ENTRIES.map((e) => [e.path, e]));\n\nexport function getScopeEntry(path: string): ScopeEntryDeclaration | undefined {\n return BY_PATH.get(path);\n}\n\n/** Every documented path, in registry order. */\nexport function listScopeEntryPaths(): string[] {\n return SCOPE_ENTRIES.map((e) => e.path);\n}\n\n/** Every documented entry with its description (for builders, agents and docs). */\nexport function listScopeEntries(): readonly ScopeEntryDeclaration[] {\n return SCOPE_ENTRIES;\n}\n\n/**\n * The default scope for stored components (kind components, tool renderers,\n * Applets): everything except the heavy optional libraries, which are added\n * by demand detection. Order is spread precedence: later entries win.\n */\nexport function defaultComponentEntries(): string[] {\n return SCOPE_ENTRIES.filter((e) => !e.provides || e.path === \"recharts\").map((e) => e.path);\n}\n\n/** Paths always loaded for chat code blocks. */\nexport function coreEntryPaths(): string[] {\n return SCOPE_ENTRIES.filter((e) => e.core).map((e) => e.path);\n}\n\n/**\n * The entries a set of files needs: the core set, every documented path it\n * imports, and every heavy library whose identifiers it uses bare.\n */\nexport function detectEntries(files: Readonly<Record<string, string>>): string[] {\n const needed = new Set(coreEntryPaths());\n const code = Object.values(files).join(\"\\n\");\n const imported = new Set<string>();\n for (const m of code.matchAll(/from\\s+['\"]([^'\"]+)['\"]/g)) if (m[1]) imported.add(m[1]);\n for (const entry of SCOPE_ENTRIES) {\n if (entry.core) continue;\n if (imported.has(entry.path)) needed.add(entry.path);\n else if (entry.provides?.some((id) => new RegExp(`(?<![\\\\w$.])${id.replace(/[$]/g, \"\\\\$\")}\\\\b`).test(code))) {\n needed.add(entry.path);\n }\n }\n return SCOPE_ENTRIES.map((e) => e.path).filter((p) => needed.has(p));\n}\n","/**\n * Where each scope entry's MODULE comes from.\n *\n * Package-owned entries load modules this package ships (so a plain Vite page\n * needs nothing else); host-owned entries are supplied by the host with\n * `provideScopeModules`. A host may also replace a package-owned module (the\n * web app hands its own `@/components/ui/*` files so stored code renders\n * exactly as the app does). Loaders may be sync or async; async ones are\n * resolved by `prepareScope` before a compile.\n *\n * State lives on `globalThis` under a `Symbol.for` key — never module state —\n * so duplicated bundles and the ESM/CJS boundary share one registry.\n */\nimport * as ReactModule from \"react\";\nimport * as LucideModule from \"lucide-react\";\nimport * as IconsModule from \"@ai-matrx/icons\";\nimport * as DesignSystem from \"@ai-matrx/design-system\";\nimport * as Controls from \"@ai-matrx/design-system/controls\";\n\nimport { getScopeEntry } from \"./entries\";\n\nexport type ScopeModuleLoader = () => unknown;\n\ninterface ModuleStore {\n announced: Set<string>;\n provided: Map<string, ScopeModuleLoader>;\n loaded: Map<string, unknown>;\n pending: Map<string, Promise<unknown>>;\n failed: Map<string, string>;\n}\n\nconst STORE_KEY = Symbol.for(\"ai-matrx.code-runtime.modules\");\n\nfunction store(): ModuleStore {\n const g = globalThis as unknown as Record<symbol, ModuleStore | undefined>;\n let s = g[STORE_KEY];\n if (!s) {\n s = { announced: new Set(), provided: new Map(), loaded: new Map(), pending: new Map(), failed: new Map() };\n g[STORE_KEY] = s;\n }\n return s;\n}\n\nconst ds = DesignSystem as unknown as Record<string, unknown>;\nconst controls = Controls as unknown as Record<string, unknown>;\n\n/**\n * The legacy `@/components/ui/*` aliases resolve to the design system the\n * same way the web app's own files do (button, textarea, switch, the select\n * trigger and the tabs bar come from `/controls`; the rest — Input included —\n * from the root).\n */\nconst LEGACY_UI_MODULE: Record<string, unknown> = {\n ...ds,\n Button: controls.Button,\n Textarea: controls.Textarea,\n Switch: controls.Switch,\n SelectTrigger: controls.SelectTrigger,\n SelectTriggerLegacy: ds.SelectTrigger,\n TabsList: controls.TabsList,\n TabsTrigger: controls.TabsTrigger,\n TabsListLegacy: ds.TabsList,\n TabsTriggerLegacy: ds.TabsTrigger,\n};\n\nfunction packageLoader(path: string): ScopeModuleLoader | null {\n if (path === \"react\") return () => ReactModule;\n if (path === \"lucide-react\") return () => LucideModule;\n if (path === \"@ai-matrx/icons\" || path === \"@/components/official/icons/IconResolver\") return () => IconsModule;\n if (path === \"@ai-matrx/design-system\") return () => DesignSystem;\n if (path === \"@ai-matrx/design-system/controls\") return () => Controls;\n if (path === \"@/lib/utils\") return () => ({ cn: ds.cn });\n if (path.startsWith(\"@/components/ui/\")) return () => LEGACY_UI_MODULE;\n if (path === \"recharts\") return () => import(\"recharts\");\n return null;\n}\n\n/**\n * Supply (or replace) the modules for scope entries. Keys must be documented\n * registry paths; an unknown key throws, because a module nobody documented\n * is exactly the reach the registry exists to prevent.\n */\nexport function provideScopeModules(map: Readonly<Record<string, ScopeModuleLoader>>): void {\n const s = store();\n for (const [path, loader] of Object.entries(map)) {\n if (!getScopeEntry(path)) {\n throw new Error(\n `[code-runtime] \"${path}\" is not a documented scope entry. Add it to the registry in @ai-matrx/code-runtime (scope/entries.ts) with a description first.`,\n );\n }\n s.provided.set(path, loader);\n s.loaded.delete(path);\n s.pending.delete(path);\n s.failed.delete(path);\n }\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return !!value && typeof (value as { then?: unknown }).then === \"function\";\n}\n\nfunction loaderFor(path: string): ScopeModuleLoader | null {\n return store().provided.get(path) ?? packageLoader(path);\n}\n\nexport type ModuleState =\n | { state: \"ready\"; module: unknown }\n | { state: \"pending\" }\n | { state: \"missing\" }\n | { state: \"failed\"; message: string };\n\n/** Synchronously read a module, starting an async load when needed. */\nexport function readScopeModule(path: string): ModuleState {\n const s = store();\n if (s.loaded.has(path)) return { state: \"ready\", module: s.loaded.get(path) };\n const failed = s.failed.get(path);\n if (failed) return { state: \"failed\", message: failed };\n if (s.pending.has(path)) return { state: \"pending\" };\n const loader = loaderFor(path);\n if (!loader) return { state: \"missing\" };\n try {\n const value = loader();\n if (isPromiseLike(value)) {\n const promise = Promise.resolve(value).then(\n (mod) => {\n s.loaded.set(path, mod);\n s.pending.delete(path);\n return mod;\n },\n (err: unknown) => {\n s.failed.set(path, err instanceof Error ? err.message : String(err));\n s.pending.delete(path);\n return undefined;\n },\n );\n s.pending.set(path, promise);\n return { state: \"pending\" };\n }\n s.loaded.set(path, value);\n return { state: \"ready\", module: value };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n s.failed.set(path, message);\n return { state: \"failed\", message };\n }\n}\n\n/** Resolve every async module the given entries need. Never rejects. */\nexport async function prepareScopeModules(paths: readonly string[]): Promise<void> {\n const s = store();\n for (const path of paths) readScopeModule(path);\n await Promise.all(paths.map((p) => s.pending.get(p)).filter((p): p is Promise<unknown> => !!p));\n}\n\n/** A scope module that failed to load — one console error per path per page, never silence. */\nexport function announceFailedModule(path: string, message: string): void {\n const s = store();\n if (s.announced.has(path)) return;\n s.announced.add(path);\n console.error(`[code-runtime] The scope entry \"${path}\" failed to load (${message}); code that imports it renders marked placeholders.`);\n}\n\n/** Test seam: forget every provided and loaded module. */\nexport function resetScopeModules(): void {\n const s = store();\n s.announced.clear();\n s.provided.clear();\n s.loaded.clear();\n s.pending.clear();\n s.failed.clear();\n}\n","/**\n * NOTHING FAILS SILENTLY. Stored code that names something the scope cannot\n * supply still renders — one bad import must not blank a whole display — but\n * the gap is SHOWN where it sits: a compact dashed chip carrying the missing\n * name (tooltip: the import path), with the element's children rendered after\n * it. Moved verbatim from matrx-frontend\n * `features/agent-apps/utils/patch-scope-identifiers.ts`; the mark symbol is\n * unchanged (`Symbol.for`) so stand-ins made by either copy are recognised.\n */\nimport * as React from \"react\";\n\nimport type { UnresolvedImport } from \"../types\";\n\nconst UNRESOLVED_IMPORT_MARK = Symbol.for(\"matrx.sandbox.unresolvedImport\");\n\n/** The stand-in's own record, or null when `value` is a real binding. */\nexport function readUnresolvedImportMark(value: unknown): UnresolvedImport | null {\n if (!value || (typeof value !== \"object\" && typeof value !== \"function\")) return null;\n const mark = (value as Record<symbol, unknown>)[UNRESOLVED_IMPORT_MARK];\n return mark && typeof mark === \"object\" ? (mark as UnresolvedImport) : null;\n}\n\nexport function createUnresolvedImportStandIn(\n identifier: string,\n importPath: string | null = null,\n): React.ForwardRefExoticComponent<{ children?: React.ReactNode } & React.RefAttributes<HTMLSpanElement>> {\n const tip = importPath ? `Not found: ${identifier} in \"${importPath}\"` : `Not found: ${identifier}`;\n const StandIn = React.forwardRef<HTMLSpanElement, { children?: React.ReactNode }>(({ children }, ref) => {\n const chip = React.createElement(\n \"span\",\n {\n ref,\n title: tip,\n \"aria-label\": tip,\n role: \"note\",\n \"data-unresolved-import\": identifier,\n \"data-import-path\": importPath ?? undefined,\n className:\n \"inline-flex items-center gap-0.5 rounded border border-dashed border-destructive/60 px-1 align-middle font-mono text-[10px] leading-4 text-destructive\",\n },\n React.createElement(\n \"svg\",\n {\n width: 10,\n height: 10,\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n strokeWidth: 2.5,\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\",\n \"aria-hidden\": true,\n },\n React.createElement(\"path\", { d: \"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" }),\n React.createElement(\"line\", { x1: 12, y1: 9, x2: 12, y2: 13 }),\n React.createElement(\"line\", { x1: 12, y1: 17, x2: 12.01, y2: 17 }),\n ),\n identifier,\n );\n return children == null ? chip : React.createElement(React.Fragment, null, chip, children);\n });\n StandIn.displayName = `UnresolvedImport(${identifier})`;\n Object.defineProperty(StandIn, UNRESOLVED_IMPORT_MARK, {\n value: { identifier, importPath } satisfies UnresolvedImport,\n enumerable: false,\n });\n return StandIn;\n}\n\n/** One readable line per unresolved name. */\nexport function describeUnresolved(entry: UnresolvedImport): string {\n if (entry.identifier === \"*\") return `\"${entry.importPath}\" (not in this scope)`;\n return entry.importPath ? `${entry.identifier} from \"${entry.importPath}\"` : entry.identifier;\n}\n\nexport function stripLiteralsForScan(code: string): string {\n return code\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, '\"\"')\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, \"''\")\n .replace(/`(?:[^`\\\\]|\\\\.)*`/gs, \"``\");\n}\n\n/** PascalCase identifiers used as JSX element types after the transform. */\nexport function extractJsxComponentIdentifiers(codeForScanning: string): Set<string> {\n const components = new Set<string>();\n const patterns = [\n // `(?![\\w$.])`: `<C.Button>` names the namespace `C`, which is an\n // import or a declaration, never a bare missing component.\n /React\\.createElement\\s*\\(\\s*([A-Z][a-zA-Z0-9]*)(?![\\w$.])/g,\n /\\.default\\.createElement\\s*\\(\\s*([A-Z][a-zA-Z0-9]*)(?![\\w$.])/g,\n /\\bjsxs?\\s*\\(\\s*([A-Z][a-zA-Z0-9]*)(?![\\w$.])/g,\n ];\n for (const pattern of patterns) {\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(codeForScanning)) !== null) {\n if (match[1]) components.add(match[1]);\n }\n }\n return components;\n}\n\n/** Globals and built-ins never patched. */\nexport const PATCH_SCOPE_SKIP_IDENTIFIERS: ReadonlySet<string> = new Set([\n \"React\", \"Object\", \"Array\", \"String\", \"Number\", \"Boolean\", \"Date\", \"Math\", \"JSON\", \"Promise\", \"Error\",\n \"TypeError\", \"RangeError\", \"RegExp\", \"Map\", \"Set\", \"WeakMap\", \"WeakSet\", \"Symbol\", \"Proxy\", \"Reflect\",\n \"Intl\", \"URL\", \"FormData\", \"Headers\", \"Request\", \"Response\", \"AbortController\", \"HTMLElement\", \"SVGElement\",\n \"Event\", \"MouseEvent\", \"KeyboardEvent\", \"HTMLInputElement\", \"HTMLTextAreaElement\", \"HTMLSelectElement\",\n \"HTMLButtonElement\", \"HTMLDivElement\", \"HTMLFormElement\", \"Node\", \"Element\", \"Document\", \"Window\",\n \"Infinity\", \"NaN\", \"Fragment\",\n]);\n"],"mappings":";;;AASA,YAAYA,kBAAiB;;;ACT7B;AAAA,EACE,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,gBAAkB;AAAA,IAChB;AAAA,I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,SAAS;AAC3B,YAAM,IAAI,SAAS,MAAM,MAAM;AAC/B,YAAM,OAAO,cAAc,EAAE;AAC7B,YAAM,OAAO,aAAa,EAAE;AAC5B,YAAM,OAAO,mBAAmB,EAAE;AAAA,IACpC;AAAA,EACF;AACA,QAAM,YAAY,KAAK,aAAa,CAAC;AACrC,SAAO,OAAO,MAAM,QAAQ,SAAS;AAKrC,MAAI,OAAO,KAAK,SAAS,EAAE,SAAS,GAAG;AACrC,eAAW,CAAC,MAAM,IAAI,KAAK,MAAM,SAAS;AACxC,YAAM,QAAQ,cAAc,IAAI;AAChC,iBAAW,CAAC,WAAW,QAAQ,KAAK,OAAO,QAAQ,OAAO,aAAa,CAAC,CAAC,GAAG;AAC1E,YAAI,EAAE,YAAY,WAAY;AAC9B,aAAK,QAAQ,IAAI,UAAU,QAAQ;AACnC,YAAI,cAAc,UAAW,MAAK,UAAU,UAAU,QAAQ;AAAA,YACzD,MAAK,SAAS,IAAI,UAAU,QAAQ;AAAA,MAC3C;AACA,iBAAW,QAAQ,OAAO,WAAW,CAAC,GAAG;AACvC,YAAI,QAAQ,UAAW,MAAK,IAAI,IAAI,UAAU,IAAI;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AACA,MAAI,KAAK,uBAAwB,QAAO,OAAO,MAAM,QAAQ,0BAA0B,CAAC;AACxF,SAAO;AACT;AAMO,SAAS,WAAW,MAA0C;AACnE,SAAO,EAAE,GAAG,gBAAgB,IAAI,EAAE,OAAO;AAC3C;","names":["ReactModule","ReactModule"]}
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/transform.ts
21
+ var transform_exports = {};
22
+ __export(transform_exports, {
23
+ transformFiles: () => transformFiles,
24
+ transformModule: () => transformModule
25
+ });
26
+ module.exports = __toCommonJS(transform_exports);
27
+
28
+ // src/transform-core.ts
29
+ var import_standalone = require("@babel/standalone");
30
+ function collectImportsPlugin(sink) {
31
+ return function collectImports() {
32
+ return {
33
+ name: "code-runtime-collect-imports",
34
+ visitor: {
35
+ ImportDeclaration(path) {
36
+ const { node } = path;
37
+ if (node.importKind === "type") return;
38
+ const source = node.source?.value ?? "";
39
+ for (const specifier of node.specifiers ?? []) {
40
+ if (specifier.importKind === "type") continue;
41
+ const local = specifier.local?.name;
42
+ if (!local) continue;
43
+ if (specifier.type === "ImportNamespaceSpecifier") sink.push({ local, source, imported: "*" });
44
+ else if (specifier.type === "ImportDefaultSpecifier") sink.push({ local, source, imported: "default" });
45
+ else sink.push({ local, source, imported: specifier.imported?.name ?? specifier.imported?.value ?? local });
46
+ }
47
+ }
48
+ }
49
+ };
50
+ };
51
+ }
52
+ function collectTopLevelPlugin(declared, candidates) {
53
+ return function collectTopLevel() {
54
+ return {
55
+ name: "code-runtime-collect-top-level",
56
+ visitor: {
57
+ Program: {
58
+ enter(path) {
59
+ for (const [name, binding] of Object.entries(path.scope.bindings)) {
60
+ const kind = binding?.kind;
61
+ if (kind === "module" || kind === "param") continue;
62
+ declared.add(name);
63
+ if (/^[A-Z]/.test(name)) candidates.push(name);
64
+ }
65
+ }
66
+ }
67
+ }
68
+ };
69
+ };
70
+ }
71
+ function languageOf(file) {
72
+ const m = /\.([a-z]+)$/i.exec(file);
73
+ const ext = (m?.[1] ?? "tsx").toLowerCase();
74
+ if (ext === "ts" || ext === "mts" || ext === "cts") return "ts";
75
+ if (ext === "tsx") return "tsx";
76
+ if (ext === "jsx") return "jsx";
77
+ if (ext === "js" || ext === "mjs" || ext === "cjs") return "js";
78
+ if (ext === "json") return "json";
79
+ return "text";
80
+ }
81
+ function transformModule(file, source) {
82
+ const lang = languageOf(file);
83
+ if (lang === "json") {
84
+ JSON.parse(source);
85
+ return { file, code: `module.exports = ${source};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };
86
+ }
87
+ if (lang === "text") {
88
+ return { file, code: `module.exports = ${JSON.stringify(source)};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };
89
+ }
90
+ const declared = /* @__PURE__ */ new Set();
91
+ const candidates = [];
92
+ const importBindings = [];
93
+ const filename = lang === "js" ? file.replace(/\.(m|c)?js$/i, ".jsx") : file;
94
+ const result = (0, import_standalone.transform)(source, {
95
+ filename: /\.[a-z]+$/i.test(filename) ? filename : `${filename}.tsx`,
96
+ presets: [["react", { runtime: "classic" }], "typescript"],
97
+ plugins: [
98
+ collectImportsPlugin(importBindings),
99
+ collectTopLevelPlugin(declared, candidates),
100
+ ["transform-modules-commonjs", { strictMode: false }]
101
+ ],
102
+ sourceType: "module",
103
+ babelrc: false,
104
+ configFile: false
105
+ });
106
+ return {
107
+ file,
108
+ code: result?.code ?? "",
109
+ declaredTopLevel: [...declared],
110
+ componentCandidates: candidates,
111
+ importBindings
112
+ };
113
+ }
114
+ function transformFiles(files, entry) {
115
+ if (!Object.prototype.hasOwnProperty.call(files, entry)) {
116
+ return {
117
+ ok: false,
118
+ error: { code: "entry_missing", message: `The entry file "${entry}" is not one of this component's files.`, retryable: false }
119
+ };
120
+ }
121
+ const modules = {};
122
+ for (const [file, source] of Object.entries(files)) {
123
+ try {
124
+ modules[file] = transformModule(file, source ?? "");
125
+ } catch (err) {
126
+ const message = err instanceof Error ? err.message : String(err);
127
+ return {
128
+ ok: false,
129
+ error: {
130
+ code: "compile_error",
131
+ message: Object.keys(files).length > 1 ? `${file}: ${message}` : message,
132
+ retryable: false,
133
+ diagnostic: file
134
+ }
135
+ };
136
+ }
137
+ }
138
+ return { ok: true, graph: { entry, modules } };
139
+ }
140
+ //# sourceMappingURL=transform.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transform.ts","../src/transform-core.ts"],"sourcesContent":["/** `@ai-matrx/code-runtime/transform` — the Babel half (parent of a sandbox frame). Pure: no React. */\nexport { transformFiles, transformModule } from \"./transform-core\";\nexport type { TransformResult, TransformedGraph, TransformedModule, ImportBinding, CodeRuntimeError } from \"./types\";\n","/**\n * The PARENT half of a compile: source files → a `TransformedGraph` (plain\n * JSON). Babel lives only here. `@babel/standalone` is pure string → string\n * and executes nothing, so a sandbox frame receives this graph and runs\n * `execute` without ever loading Babel.\n *\n * Every file: React (classic runtime — the scope supplies `React`, there is no\n * module loader for an automatic JSX runtime) + TypeScript + CommonJS modules\n * in NON-strict mode, so the sloppy-mode bodies stored before multi-file\n * compiles behave exactly as before. Two collectors ride the same pass:\n * import specifiers (THE IMPORT-BINDING CONTRACT — validated at link time so a\n * name nothing supplies becomes a visible, reported stand-in) and top-level\n * bindings (kept out of the scope parameters, so an author's own `const Card`\n * shadows the injected scope instead of colliding with it).\n */\nimport { transform } from \"@babel/standalone\";\n\nimport type { ImportBinding, TransformResult, TransformedModule } from \"./types\";\n\ninterface ImportDeclarationPathLike {\n node: {\n importKind?: string;\n source: { value: string };\n specifiers: Array<{\n type: string;\n local: { name: string };\n importKind?: string;\n imported?: { name?: string; value?: string };\n }>;\n };\n}\n\ninterface ProgramPathLike {\n scope: { bindings: Record<string, { kind?: string } | undefined> };\n}\n\nfunction collectImportsPlugin(sink: ImportBinding[]) {\n return function collectImports() {\n return {\n name: \"code-runtime-collect-imports\",\n visitor: {\n ImportDeclaration(path: ImportDeclarationPathLike) {\n const { node } = path;\n if (node.importKind === \"type\") return;\n const source = node.source?.value ?? \"\";\n for (const specifier of node.specifiers ?? []) {\n if (specifier.importKind === \"type\") continue;\n const local = specifier.local?.name;\n if (!local) continue;\n if (specifier.type === \"ImportNamespaceSpecifier\") sink.push({ local, source, imported: \"*\" });\n else if (specifier.type === \"ImportDefaultSpecifier\") sink.push({ local, source, imported: \"default\" });\n else sink.push({ local, source, imported: specifier.imported?.name ?? specifier.imported?.value ?? local });\n }\n },\n },\n };\n };\n}\n\nfunction collectTopLevelPlugin(declared: Set<string>, candidates: string[]) {\n return function collectTopLevel() {\n return {\n name: \"code-runtime-collect-top-level\",\n visitor: {\n Program: {\n enter(path: ProgramPathLike) {\n for (const [name, binding] of Object.entries(path.scope.bindings)) {\n const kind = binding?.kind;\n if (kind === \"module\" || kind === \"param\") continue;\n declared.add(name);\n if (/^[A-Z]/.test(name)) candidates.push(name);\n }\n },\n },\n },\n };\n };\n}\n\nfunction languageOf(file: string): \"ts\" | \"tsx\" | \"jsx\" | \"js\" | \"json\" | \"text\" {\n const m = /\\.([a-z]+)$/i.exec(file);\n const ext = (m?.[1] ?? \"tsx\").toLowerCase();\n if (ext === \"ts\" || ext === \"mts\" || ext === \"cts\") return \"ts\";\n if (ext === \"tsx\") return \"tsx\";\n if (ext === \"jsx\") return \"jsx\";\n if (ext === \"js\" || ext === \"mjs\" || ext === \"cjs\") return \"js\";\n if (ext === \"json\") return \"json\";\n return \"text\";\n}\n\n/** Transform one file. Throws Babel's own error (with line) on bad syntax. */\nexport function transformModule(file: string, source: string): TransformedModule {\n const lang = languageOf(file);\n if (lang === \"json\") {\n JSON.parse(source);\n return { file, code: `module.exports = ${source};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };\n }\n if (lang === \"text\") {\n return { file, code: `module.exports = ${JSON.stringify(source)};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };\n }\n const declared = new Set<string>();\n const candidates: string[] = [];\n const importBindings: ImportBinding[] = [];\n // Babel's TypeScript preset decides JSX by extension; a stored single body\n // has no real filename, so it is always treated as .tsx (as before).\n const filename = lang === \"js\" ? file.replace(/\\.(m|c)?js$/i, \".jsx\") : file;\n const result = transform(source, {\n filename: /\\.[a-z]+$/i.test(filename) ? filename : `${filename}.tsx`,\n presets: [[\"react\", { runtime: \"classic\" }], \"typescript\"],\n plugins: [\n collectImportsPlugin(importBindings),\n collectTopLevelPlugin(declared, candidates),\n [\"transform-modules-commonjs\", { strictMode: false }],\n ],\n sourceType: \"module\",\n babelrc: false,\n configFile: false,\n } as Parameters<typeof transform>[1]);\n return {\n file,\n code: result?.code ?? \"\",\n declaredTopLevel: [...declared],\n componentCandidates: candidates,\n importBindings,\n };\n}\n\n/**\n * Transform a whole file graph. Never throws: a syntax error comes back as a\n * named error that says which file failed.\n */\nexport function transformFiles(files: Readonly<Record<string, string>>, entry: string): TransformResult {\n if (!Object.prototype.hasOwnProperty.call(files, entry)) {\n return {\n ok: false,\n error: { code: \"entry_missing\", message: `The entry file \"${entry}\" is not one of this component's files.`, retryable: false },\n };\n }\n const modules: Record<string, TransformedModule> = {};\n for (const [file, source] of Object.entries(files)) {\n try {\n modules[file] = transformModule(file, source ?? \"\");\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n ok: false,\n error: {\n code: \"compile_error\",\n message: Object.keys(files).length > 1 ? `${file}: ${message}` : message,\n retryable: false,\n diagnostic: file,\n },\n };\n }\n }\n return { ok: true, graph: { entry, modules } };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeA,wBAA0B;AAqB1B,SAAS,qBAAqB,MAAuB;AACnD,SAAO,SAAS,iBAAiB;AAC/B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,QACP,kBAAkB,MAAiC;AACjD,gBAAM,EAAE,KAAK,IAAI;AACjB,cAAI,KAAK,eAAe,OAAQ;AAChC,gBAAM,SAAS,KAAK,QAAQ,SAAS;AACrC,qBAAW,aAAa,KAAK,cAAc,CAAC,GAAG;AAC7C,gBAA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AAW,MAAM;AAAA,IAC/H;AAAA,EACF;AACA,QAAM,UAA6C,CAAC;AACpD,aAAW,CAAC,MAAM,MAAM,KAAK,OAAO,QAAQ,KAAK,GAAG;AAClD,QAAI;AACF,cAAQ,IAAI,IAAI,gBAAgB,MAAM,UAAU,EAAE;AAAA,IACpD,SAAS,KAAK;AACZ,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,OAAO;AAAA,UACL,MAAM;AAAA,UACN,SAAS,OAAO,KAAK,KAAK,EAAE,SAAS,IAAI,GAAG,IAAI,KAAK,OAAO,KAAK;AAAA,UACjE,WAAW;AAAA,UACX,YAAY;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,IAAI,MAAM,OAAO,EAAE,OAAO,QAAQ,EAAE;AAC/C;","names":[]}
@@ -0,0 +1,12 @@
1
+ import { T as TransformResult, a as TransformedModule } from './types-DL6oTcV_.cjs';
2
+ export { C as CodeRuntimeError, I as ImportBinding, b as TransformedGraph } from './types-DL6oTcV_.cjs';
3
+
4
+ /** Transform one file. Throws Babel's own error (with line) on bad syntax. */
5
+ declare function transformModule(file: string, source: string): TransformedModule;
6
+ /**
7
+ * Transform a whole file graph. Never throws: a syntax error comes back as a
8
+ * named error that says which file failed.
9
+ */
10
+ declare function transformFiles(files: Readonly<Record<string, string>>, entry: string): TransformResult;
11
+
12
+ export { TransformResult, TransformedModule, transformFiles, transformModule };
@@ -0,0 +1,12 @@
1
+ import { T as TransformResult, a as TransformedModule } from './types-DL6oTcV_.js';
2
+ export { C as CodeRuntimeError, I as ImportBinding, b as TransformedGraph } from './types-DL6oTcV_.js';
3
+
4
+ /** Transform one file. Throws Babel's own error (with line) on bad syntax. */
5
+ declare function transformModule(file: string, source: string): TransformedModule;
6
+ /**
7
+ * Transform a whole file graph. Never throws: a syntax error comes back as a
8
+ * named error that says which file failed.
9
+ */
10
+ declare function transformFiles(files: Readonly<Record<string, string>>, entry: string): TransformResult;
11
+
12
+ export { TransformResult, TransformedModule, transformFiles, transformModule };
@@ -0,0 +1,117 @@
1
+ // src/transform-core.ts
2
+ import { transform } from "@babel/standalone";
3
+ function collectImportsPlugin(sink) {
4
+ return function collectImports() {
5
+ return {
6
+ name: "code-runtime-collect-imports",
7
+ visitor: {
8
+ ImportDeclaration(path) {
9
+ const { node } = path;
10
+ if (node.importKind === "type") return;
11
+ const source = node.source?.value ?? "";
12
+ for (const specifier of node.specifiers ?? []) {
13
+ if (specifier.importKind === "type") continue;
14
+ const local = specifier.local?.name;
15
+ if (!local) continue;
16
+ if (specifier.type === "ImportNamespaceSpecifier") sink.push({ local, source, imported: "*" });
17
+ else if (specifier.type === "ImportDefaultSpecifier") sink.push({ local, source, imported: "default" });
18
+ else sink.push({ local, source, imported: specifier.imported?.name ?? specifier.imported?.value ?? local });
19
+ }
20
+ }
21
+ }
22
+ };
23
+ };
24
+ }
25
+ function collectTopLevelPlugin(declared, candidates) {
26
+ return function collectTopLevel() {
27
+ return {
28
+ name: "code-runtime-collect-top-level",
29
+ visitor: {
30
+ Program: {
31
+ enter(path) {
32
+ for (const [name, binding] of Object.entries(path.scope.bindings)) {
33
+ const kind = binding?.kind;
34
+ if (kind === "module" || kind === "param") continue;
35
+ declared.add(name);
36
+ if (/^[A-Z]/.test(name)) candidates.push(name);
37
+ }
38
+ }
39
+ }
40
+ }
41
+ };
42
+ };
43
+ }
44
+ function languageOf(file) {
45
+ const m = /\.([a-z]+)$/i.exec(file);
46
+ const ext = (m?.[1] ?? "tsx").toLowerCase();
47
+ if (ext === "ts" || ext === "mts" || ext === "cts") return "ts";
48
+ if (ext === "tsx") return "tsx";
49
+ if (ext === "jsx") return "jsx";
50
+ if (ext === "js" || ext === "mjs" || ext === "cjs") return "js";
51
+ if (ext === "json") return "json";
52
+ return "text";
53
+ }
54
+ function transformModule(file, source) {
55
+ const lang = languageOf(file);
56
+ if (lang === "json") {
57
+ JSON.parse(source);
58
+ return { file, code: `module.exports = ${source};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };
59
+ }
60
+ if (lang === "text") {
61
+ return { file, code: `module.exports = ${JSON.stringify(source)};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };
62
+ }
63
+ const declared = /* @__PURE__ */ new Set();
64
+ const candidates = [];
65
+ const importBindings = [];
66
+ const filename = lang === "js" ? file.replace(/\.(m|c)?js$/i, ".jsx") : file;
67
+ const result = transform(source, {
68
+ filename: /\.[a-z]+$/i.test(filename) ? filename : `${filename}.tsx`,
69
+ presets: [["react", { runtime: "classic" }], "typescript"],
70
+ plugins: [
71
+ collectImportsPlugin(importBindings),
72
+ collectTopLevelPlugin(declared, candidates),
73
+ ["transform-modules-commonjs", { strictMode: false }]
74
+ ],
75
+ sourceType: "module",
76
+ babelrc: false,
77
+ configFile: false
78
+ });
79
+ return {
80
+ file,
81
+ code: result?.code ?? "",
82
+ declaredTopLevel: [...declared],
83
+ componentCandidates: candidates,
84
+ importBindings
85
+ };
86
+ }
87
+ function transformFiles(files, entry) {
88
+ if (!Object.prototype.hasOwnProperty.call(files, entry)) {
89
+ return {
90
+ ok: false,
91
+ error: { code: "entry_missing", message: `The entry file "${entry}" is not one of this component's files.`, retryable: false }
92
+ };
93
+ }
94
+ const modules = {};
95
+ for (const [file, source] of Object.entries(files)) {
96
+ try {
97
+ modules[file] = transformModule(file, source ?? "");
98
+ } catch (err) {
99
+ const message = err instanceof Error ? err.message : String(err);
100
+ return {
101
+ ok: false,
102
+ error: {
103
+ code: "compile_error",
104
+ message: Object.keys(files).length > 1 ? `${file}: ${message}` : message,
105
+ retryable: false,
106
+ diagnostic: file
107
+ }
108
+ };
109
+ }
110
+ }
111
+ return { ok: true, graph: { entry, modules } };
112
+ }
113
+ export {
114
+ transformFiles,
115
+ transformModule
116
+ };
117
+ //# sourceMappingURL=transform.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transform-core.ts"],"sourcesContent":["/**\n * The PARENT half of a compile: source files → a `TransformedGraph` (plain\n * JSON). Babel lives only here. `@babel/standalone` is pure string → string\n * and executes nothing, so a sandbox frame receives this graph and runs\n * `execute` without ever loading Babel.\n *\n * Every file: React (classic runtime — the scope supplies `React`, there is no\n * module loader for an automatic JSX runtime) + TypeScript + CommonJS modules\n * in NON-strict mode, so the sloppy-mode bodies stored before multi-file\n * compiles behave exactly as before. Two collectors ride the same pass:\n * import specifiers (THE IMPORT-BINDING CONTRACT — validated at link time so a\n * name nothing supplies becomes a visible, reported stand-in) and top-level\n * bindings (kept out of the scope parameters, so an author's own `const Card`\n * shadows the injected scope instead of colliding with it).\n */\nimport { transform } from \"@babel/standalone\";\n\nimport type { ImportBinding, TransformResult, TransformedModule } from \"./types\";\n\ninterface ImportDeclarationPathLike {\n node: {\n importKind?: string;\n source: { value: string };\n specifiers: Array<{\n type: string;\n local: { name: string };\n importKind?: string;\n imported?: { name?: string; value?: string };\n }>;\n };\n}\n\ninterface ProgramPathLike {\n scope: { bindings: Record<string, { kind?: string } | undefined> };\n}\n\nfunction collectImportsPlugin(sink: ImportBinding[]) {\n return function collectImports() {\n return {\n name: \"code-runtime-collect-imports\",\n visitor: {\n ImportDeclaration(path: ImportDeclarationPathLike) {\n const { node } = path;\n if (node.importKind === \"type\") return;\n const source = node.source?.value ?? \"\";\n for (const specifier of node.specifiers ?? []) {\n if (specifier.importKind === \"type\") continue;\n const local = specifier.local?.name;\n if (!local) continue;\n if (specifier.type === \"ImportNamespaceSpecifier\") sink.push({ local, source, imported: \"*\" });\n else if (specifier.type === \"ImportDefaultSpecifier\") sink.push({ local, source, imported: \"default\" });\n else sink.push({ local, source, imported: specifier.imported?.name ?? specifier.imported?.value ?? local });\n }\n },\n },\n };\n };\n}\n\nfunction collectTopLevelPlugin(declared: Set<string>, candidates: string[]) {\n return function collectTopLevel() {\n return {\n name: \"code-runtime-collect-top-level\",\n visitor: {\n Program: {\n enter(path: ProgramPathLike) {\n for (const [name, binding] of Object.entries(path.scope.bindings)) {\n const kind = binding?.kind;\n if (kind === \"module\" || kind === \"param\") continue;\n declared.add(name);\n if (/^[A-Z]/.test(name)) candidates.push(name);\n }\n },\n },\n },\n };\n };\n}\n\nfunction languageOf(file: string): \"ts\" | \"tsx\" | \"jsx\" | \"js\" | \"json\" | \"text\" {\n const m = /\\.([a-z]+)$/i.exec(file);\n const ext = (m?.[1] ?? \"tsx\").toLowerCase();\n if (ext === \"ts\" || ext === \"mts\" || ext === \"cts\") return \"ts\";\n if (ext === \"tsx\") return \"tsx\";\n if (ext === \"jsx\") return \"jsx\";\n if (ext === \"js\" || ext === \"mjs\" || ext === \"cjs\") return \"js\";\n if (ext === \"json\") return \"json\";\n return \"text\";\n}\n\n/** Transform one file. Throws Babel's own error (with line) on bad syntax. */\nexport function transformModule(file: string, source: string): TransformedModule {\n const lang = languageOf(file);\n if (lang === \"json\") {\n JSON.parse(source);\n return { file, code: `module.exports = ${source};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };\n }\n if (lang === \"text\") {\n return { file, code: `module.exports = ${JSON.stringify(source)};`, declaredTopLevel: [], componentCandidates: [], importBindings: [] };\n }\n const declared = new Set<string>();\n const candidates: string[] = [];\n const importBindings: ImportBinding[] = [];\n // Babel's TypeScript preset decides JSX by extension; a stored single body\n // has no real filename, so it is always treated as .tsx (as before).\n const filename = lang === \"js\" ? file.replace(/\\.(m|c)?js$/i, \".jsx\") : file;\n const result = transform(source, {\n filename: /\\.[a-z]+$/i.test(filename) ? filename : `${filename}.tsx`,\n presets: [[\"react\", { runtime: \"classic\" }], \"typescript\"],\n plugins: [\n collectImportsPlugin(importBindings),\n collectTopLevelPlugin(declared, candidates),\n [\"transform-modules-commonjs\", { strictMode: false }],\n ],\n sourceType: \"module\",\n babelrc: false,\n configFile: false,\n } as Parameters<typeof transform>[1]);\n return {\n file,\n code: result?.code ?? \"\",\n declaredTopLevel: [...declared],\n componentCandidates: candidates,\n importBindings,\n };\n}\n\n/**\n * Transform a whole file graph. Never throws: a syntax error comes back as a\n * named error that says which file failed.\n */\nexport function transformFiles(files: Readonly<Record<string, string>>, entry: string): TransformResult {\n if (!Object.prototype.hasOwnProperty.call(files, entry)) {\n return {\n ok: false,\n error: { code: \"entry_missing\", message: `The entry file \"${entry}\" is not one of this component's files.`, retryable: false },\n };\n }\n const modules: Record<string, TransformedModule> = {};\n for (const [file, source] of Object.entries(files)) {\n try {\n modules[file] = transformModule(file, source ?? \"\");\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return {\n ok: false,\n error: {\n code: \"compile_error\",\n message: Object.keys(files).length > 1 ? `${file}: ${message}` : message,\n retryable: false,\n diagnostic: file,\n },\n };\n }\n }\n return { ok: true, graph: { entry, modules } };\n}\n"],"mappings":";AAeA,SAAS,iBAAiB;AAqB1B,SAAS,qBAAqB,MAAuB;AACnD,SAAO,SAAS,iBAAiB;AAC/B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,QACP,kBAAkB,MAAiC;AACjD,gBAAM,EAAE,KAAK,IAAI;AACjB,cAAI,KAAK,eAAe,OAAQ;AAChC,gBAAM,SAAS,KAAK,QAAQ,SAAS;AACrC,qBAAW,aAAa,KAAK,cAAc,CAAC,GAAG;AAC7C,gBAAI,UAAU,eAAe,OAAQ;AACrC,kBAAM,QAAQ,UAAU,OAAO;AAC/B,gBAAI,CAAC,MAAO;AACZ,gBAAI,UAAU,SAAS,2BAA4B,MAAK,KAAK,EAAE,OAAO,QAAQ,UAAU,IAAI,CAAC;AAAA,qBACpF,UAAU,SAAS,yBAA0B,MAAK,KAAK,EAAE,OAAO,QAAQ,UAAU,UAAU,CAAC;AAAA,gBACjG,MAAK,KAAK,EAAE,OAAO,QAAQ,UAAU,UAAU,UAAU,QAAQ,UAAU,UAAU,SAAS,MAAM,CAAC;AAAA,UAC5G;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,sBAAsB,UAAuB,YAAsB;AAC1E,SAAO,SAAS,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ACF;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,IAAI,MAAM,OAAO,EAAE,OAAO,QAAQ,EAAE;AAC/C;","names":[]}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The error every refusal carries. Structurally identical to
3
+ * `@ai-matrx/applets`' `AppletError` (CONTRACTS §0); mirrored here because
4
+ * applets depends on this package, never the reverse.
5
+ */
6
+ interface CodeRuntimeError {
7
+ code: string;
8
+ message: string;
9
+ retryable: boolean;
10
+ diagnostic?: string;
11
+ }
12
+ /** One source-gate finding (CONTRACTS §7). */
13
+ interface Finding {
14
+ rule: string;
15
+ file: string;
16
+ line: number;
17
+ message: string;
18
+ severity: "refuse" | "warn";
19
+ }
20
+ /** One import specifier, recorded before the declaration is rewritten. */
21
+ interface ImportBinding {
22
+ local: string;
23
+ source: string;
24
+ /** Exported name, `"default"`, or `"*"` for a namespace import. */
25
+ imported: string;
26
+ }
27
+ /** One transformed file: plain JSON, so it crosses `postMessage` unchanged. */
28
+ interface TransformedModule {
29
+ file: string;
30
+ /** CommonJS-shaped JS (`require`, `module`, `exports` are supplied at run). */
31
+ code: string;
32
+ declaredTopLevel: string[];
33
+ /** Top-level PascalCase bindings in declaration order. */
34
+ componentCandidates: string[];
35
+ importBindings: ImportBinding[];
36
+ }
37
+ /** A whole transformed file graph — the parent → frame payload. */
38
+ interface TransformedGraph {
39
+ entry: string;
40
+ modules: Record<string, TransformedModule>;
41
+ }
42
+ type TransformResult = {
43
+ ok: true;
44
+ graph: TransformedGraph;
45
+ } | {
46
+ ok: false;
47
+ error: CodeRuntimeError;
48
+ };
49
+
50
+ export type { CodeRuntimeError as C, Finding as F, ImportBinding as I, TransformResult as T, TransformedModule as a, TransformedGraph as b };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The error every refusal carries. Structurally identical to
3
+ * `@ai-matrx/applets`' `AppletError` (CONTRACTS §0); mirrored here because
4
+ * applets depends on this package, never the reverse.
5
+ */
6
+ interface CodeRuntimeError {
7
+ code: string;
8
+ message: string;
9
+ retryable: boolean;
10
+ diagnostic?: string;
11
+ }
12
+ /** One source-gate finding (CONTRACTS §7). */
13
+ interface Finding {
14
+ rule: string;
15
+ file: string;
16
+ line: number;
17
+ message: string;
18
+ severity: "refuse" | "warn";
19
+ }
20
+ /** One import specifier, recorded before the declaration is rewritten. */
21
+ interface ImportBinding {
22
+ local: string;
23
+ source: string;
24
+ /** Exported name, `"default"`, or `"*"` for a namespace import. */
25
+ imported: string;
26
+ }
27
+ /** One transformed file: plain JSON, so it crosses `postMessage` unchanged. */
28
+ interface TransformedModule {
29
+ file: string;
30
+ /** CommonJS-shaped JS (`require`, `module`, `exports` are supplied at run). */
31
+ code: string;
32
+ declaredTopLevel: string[];
33
+ /** Top-level PascalCase bindings in declaration order. */
34
+ componentCandidates: string[];
35
+ importBindings: ImportBinding[];
36
+ }
37
+ /** A whole transformed file graph — the parent → frame payload. */
38
+ interface TransformedGraph {
39
+ entry: string;
40
+ modules: Record<string, TransformedModule>;
41
+ }
42
+ type TransformResult = {
43
+ ok: true;
44
+ graph: TransformedGraph;
45
+ } | {
46
+ ok: false;
47
+ error: CodeRuntimeError;
48
+ };
49
+
50
+ export type { CodeRuntimeError as C, Finding as F, ImportBinding as I, TransformResult as T, TransformedModule as a, TransformedGraph as b };