@tangle-network/agent-app 0.45.31 → 0.45.33
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.
- package/dist/{DesignCanvas-RSWQCXM3.js → DesignCanvas-EODMDQMT.js} +2 -2
- package/dist/{DesignCanvasEditor-XZMGIST7.js → DesignCanvasEditor-DRRZ6ZD3.js} +4 -4
- package/dist/{InvitationsPanel-CJ7DR4F7.js → InvitationsPanel-BATXZHY4.js} +2 -2
- package/dist/{MembersPanel-BB4OD2KB.js → MembersPanel-XNLF3SA4.js} +2 -2
- package/dist/assistant/index.js +11 -10
- package/dist/assistant/index.js.map +1 -1
- package/dist/chat-react/index.js +1 -1
- package/dist/{chunk-YIQHOAHN.js → chunk-3UBAO3N5.js} +3 -3
- package/dist/{chunk-YIQHOAHN.js.map → chunk-3UBAO3N5.js.map} +1 -1
- package/dist/{chunk-PURHUAOR.js → chunk-556RB3XI.js} +5 -5
- package/dist/chunk-556RB3XI.js.map +1 -0
- package/dist/{chunk-NEJ7OMQS.js → chunk-5LC2VXH5.js} +102 -4
- package/dist/chunk-5LC2VXH5.js.map +1 -0
- package/dist/{chunk-HZ4WCA37.js → chunk-5MZXWPFN.js} +9 -9
- package/dist/chunk-5MZXWPFN.js.map +1 -0
- package/dist/{chunk-FNM7JYME.js → chunk-5N434BGF.js} +17 -17
- package/dist/chunk-5N434BGF.js.map +1 -0
- package/dist/{chunk-5SXS3YAB.js → chunk-7MV23XBW.js} +2 -2
- package/dist/chunk-7MV23XBW.js.map +1 -0
- package/dist/{chunk-S564OFTL.js → chunk-F4XLTVQ3.js} +3 -3
- package/dist/{chunk-S564OFTL.js.map → chunk-F4XLTVQ3.js.map} +1 -1
- package/dist/{chunk-LSQR6HM6.js → chunk-IN6LNZ7O.js} +35 -34
- package/dist/chunk-IN6LNZ7O.js.map +1 -0
- package/dist/{chunk-L7FHRORY.js → chunk-SFSR3CAH.js} +180 -40
- package/dist/chunk-SFSR3CAH.js.map +1 -0
- package/dist/{chunk-QGOU3VXH.js → chunk-UXRJAUJL.js} +3 -3
- package/dist/{chunk-IFYJDX3J.js → chunk-XHD4Y54K.js} +47 -46
- package/dist/chunk-XHD4Y54K.js.map +1 -0
- package/dist/design-canvas-react/index.js +8 -8
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/spend/cli.js +1 -1
- package/dist/spend/index.d.ts +212 -7
- package/dist/spend/index.js +5 -1
- package/dist/spend/index.js.map +1 -1
- package/dist/studio-react/index.js +27 -27
- package/dist/studio-react/index.js.map +1 -1
- package/dist/teams-react/index.js +2 -2
- package/dist/teams-react/lazy.js +2 -2
- package/dist/theme/index.js +1 -1
- package/dist/theme/tailwind-preset.d.ts +5 -1
- package/dist/theme/tailwind-preset.js +11 -2
- package/dist/theme/tailwind-preset.js.map +1 -1
- package/dist/theme/tokens.css +126 -79
- package/dist/web-react/async/index.js +1 -1
- package/dist/web-react/index.d.ts +60 -2
- package/dist/web-react/index.js +13 -3
- package/dist/work-product-react/index.js +3 -3
- package/dist/work-product-react/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5SXS3YAB.js.map +0 -1
- package/dist/chunk-FNM7JYME.js.map +0 -1
- package/dist/chunk-HZ4WCA37.js.map +0 -1
- package/dist/chunk-IFYJDX3J.js.map +0 -1
- package/dist/chunk-L7FHRORY.js.map +0 -1
- package/dist/chunk-LSQR6HM6.js.map +0 -1
- package/dist/chunk-NEJ7OMQS.js.map +0 -1
- package/dist/chunk-PURHUAOR.js.map +0 -1
- /package/dist/{DesignCanvas-RSWQCXM3.js.map → DesignCanvas-EODMDQMT.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-XZMGIST7.js.map → DesignCanvasEditor-DRRZ6ZD3.js.map} +0 -0
- /package/dist/{InvitationsPanel-CJ7DR4F7.js.map → InvitationsPanel-BATXZHY4.js.map} +0 -0
- /package/dist/{MembersPanel-BB4OD2KB.js.map → MembersPanel-XNLF3SA4.js.map} +0 -0
- /package/dist/{chunk-QGOU3VXH.js.map → chunk-UXRJAUJL.js.map} +0 -0
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
downloadDataUrl,
|
|
13
13
|
exportDocumentJson,
|
|
14
14
|
exportPageDataUrl
|
|
15
|
-
} from "../chunk-
|
|
15
|
+
} from "../chunk-556RB3XI.js";
|
|
16
16
|
import {
|
|
17
17
|
BTN,
|
|
18
18
|
BTN_ACTIVE,
|
|
@@ -41,8 +41,8 @@ import {
|
|
|
41
41
|
buildRulerTicks,
|
|
42
42
|
formatRulerLabel,
|
|
43
43
|
selectTickStep
|
|
44
|
-
} from "../chunk-
|
|
45
|
-
import "../chunk-
|
|
44
|
+
} from "../chunk-5N434BGF.js";
|
|
45
|
+
import "../chunk-IN6LNZ7O.js";
|
|
46
46
|
import "../chunk-ZN5J47UX.js";
|
|
47
47
|
import {
|
|
48
48
|
DEFAULT_INSERT_TEMPLATES,
|
|
@@ -93,7 +93,7 @@ import {
|
|
|
93
93
|
import {
|
|
94
94
|
DesignCanvasChromeLazy,
|
|
95
95
|
DesignCanvasLazy
|
|
96
|
-
} from "../chunk-
|
|
96
|
+
} from "../chunk-UXRJAUJL.js";
|
|
97
97
|
import "../chunk-F7VH4G5C.js";
|
|
98
98
|
|
|
99
99
|
// src/design-canvas-react/components/CanvasInsertPanel.tsx
|
|
@@ -156,7 +156,7 @@ function TemplatePreview({ shape }) {
|
|
|
156
156
|
return /* @__PURE__ */ jsx(
|
|
157
157
|
"span",
|
|
158
158
|
{
|
|
159
|
-
className: `block leading-none text-[var(--text-primary)] ${shape === "heading" ? "text-2xl font-
|
|
159
|
+
className: `block leading-none text-[var(--text-primary)] ${shape === "heading" ? "text-2xl font-semibold" : "text-lg"}`,
|
|
160
160
|
"aria-hidden": true,
|
|
161
161
|
children: shape === "heading" ? "T" : "\xB6"
|
|
162
162
|
}
|
|
@@ -409,7 +409,7 @@ function LayersPanel({ page, selectedElementIds, canWrite, onSetAttrs, onReorder
|
|
|
409
409
|
}
|
|
410
410
|
const visible = rows.length > LAYERS_PANEL_ROW_LIMIT ? rows.slice(0, LAYERS_PANEL_ROW_LIMIT) : rows;
|
|
411
411
|
return /* @__PURE__ */ jsxs2("div", { className: "flex h-full flex-col overflow-hidden text-[var(--text-primary)]", children: [
|
|
412
|
-
/* @__PURE__ */ jsx2("div", { className: "shrink-0 border-b border-[var(--border-default)] px-3 py-1.5 text-[11px] font-
|
|
412
|
+
/* @__PURE__ */ jsx2("div", { className: "shrink-0 border-b border-[var(--border-default)] px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--text-muted)]", children: "Layers" }),
|
|
413
413
|
/* @__PURE__ */ jsxs2("div", { className: "min-h-0 flex-1 overflow-y-auto", children: [
|
|
414
414
|
visible.length === 0 ? /* @__PURE__ */ jsx2("div", { className: "px-3 py-2 text-[11px] text-[var(--text-muted)]", children: "No layers yet" }) : null,
|
|
415
415
|
visible.map((row) => {
|
|
@@ -448,7 +448,7 @@ function LayersPanel({ page, selectedElementIds, canWrite, onSetAttrs, onReorder
|
|
|
448
448
|
setDragOverIndex(null);
|
|
449
449
|
},
|
|
450
450
|
className: [
|
|
451
|
-
"group flex items-center gap-1.5 py-1 pr-2 text-
|
|
451
|
+
"group flex items-center gap-1.5 py-1 pr-2 text-sm transition-colors",
|
|
452
452
|
isSelected ? "bg-[color-mix(in_srgb,var(--brand-primary)_15%,transparent)] text-[var(--text-primary)]" : "hover:bg-[color-mix(in_srgb,var(--border-default)_40%,transparent)] text-[var(--text-secondary)]",
|
|
453
453
|
dragOverIndex === row.ownerIndex ? "border-t border-[var(--brand-primary)]" : ""
|
|
454
454
|
].join(" "),
|
|
@@ -466,7 +466,7 @@ function LayersPanel({ page, selectedElementIds, canWrite, onSetAttrs, onReorder
|
|
|
466
466
|
if (event.key === "Escape") setRenamingId(null);
|
|
467
467
|
event.stopPropagation();
|
|
468
468
|
},
|
|
469
|
-
className: "min-w-0 flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-1 py-0 text-
|
|
469
|
+
className: "min-w-0 flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-1 py-0 text-sm text-[var(--text-primary)] focus:border-[var(--brand-primary)]"
|
|
470
470
|
}
|
|
471
471
|
) : (
|
|
472
472
|
// Selection is a real button (sibling of the eye/lock buttons) so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/design-canvas-react/components/CanvasInsertPanel.tsx","../../src/design-canvas-react/components/LayersPanel.tsx","../../src/design-canvas-react/components/layer-tree.ts"],"sourcesContent":["/**\n * The human \"add element to the canvas\" side panel — a reusable left rail any\n * canvas consumer can mount so a person (not just the agent) can put images,\n * shapes, and text on the canvas. Designed for the `renderSidePanel` slot of\n * {@link DesignCanvasProps}; pass `renderSidePanel={(ctx) => <CanvasInsertPanel … />}`.\n *\n * Endpoints are per-app, so every I/O path is a callback — no product route is\n * hardcoded:\n * - `onUploadImage(file) => Promise<url>` — optional. When provided, the host\n * stores the file and returns the src to insert. The url MUST be http(s) or\n * a rooted `/api/` path (enforced by `assertSceneMediaSrc` before insertion);\n * a `data:` url is rejected, matching the scene model's media boundary.\n * - `loadGenerations?()` — optional provider for \"already generated in this\n * workspace\" images; omit to hide the tab.\n * - `templates?` — optional template set; defaults to {@link DEFAULT_INSERT_TEMPLATES}.\n *\n * Insertion goes through `onInsert`, which the host wires to its\n * `onApplyOperations` pipeline (server-validated, undoable) — the same path\n * every other edit takes.\n *\n * Tokens/icons follow the canvas convention: CSS-var design tokens and inline\n * SVG glyphs, no icon-library or Tailwind-semantic-token dependency.\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { SceneOperation } from '../../design-canvas/operations'\nimport { assertSceneMediaSrc } from '../../design-canvas/model'\nimport {\n DEFAULT_INSERT_TEMPLATES,\n buildInsertImageOp,\n type InsertPageGeometry,\n type InsertTemplate,\n} from '../insert-builders'\nimport { ImageGlyph, ShapesGlyph } from './glyphs'\n\n/** An already-generated image the panel can offer for one-click insertion. */\nexport interface InsertGeneration {\n id: string\n /** The image url to insert. Must satisfy the scene media boundary\n * (http(s) or rooted `/api/`); rejected otherwise at insert time. */\n url: string\n /** Optional prompt/label shown as the tile's title. */\n label?: string\n}\n\nexport interface CanvasInsertPanelProps {\n canWrite: boolean\n /** The active page new elements are added to. */\n page: InsertPageGeometry\n /** Submit operations through the host's apply pipeline. */\n onInsert(operations: SceneOperation[]): Promise<unknown>\n /** Store an uploaded file and return its src (http(s) or rooted `/api/`). */\n onUploadImage?(file: File): Promise<string>\n /** Optional provider for the Generations tab; omit to hide it. */\n loadGenerations?(): Promise<InsertGeneration[]>\n /** Drop-in templates; defaults to the built-in starter set. */\n templates?: readonly InsertTemplate[]\n /** Accepted upload mime types. Default: PNG/JPEG/GIF/WebP. */\n accept?: string\n className?: string\n}\n\ntype Tab = 'uploads' | 'templates' | 'generations'\n\nconst DEFAULT_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp'\n\n/** Read an image url's natural dimensions in the browser; resolves `{0,0}` when\n * Image is unavailable (SSR/tests), the load fails, or the probe times out —\n * builders fall back to the size cap, so a failed probe still inserts a sensibly\n * sized element rather than blocking insertion. */\nconst PROBE_TIMEOUT_MS = 4000\n\nfunction probeImageSize(url: string): Promise<{ width: number; height: number }> {\n return new Promise((resolve) => {\n if (typeof Image === 'undefined') return resolve({ width: 0, height: 0 })\n let settled = false\n const finish = (size: { width: number; height: number }) => {\n if (settled) return\n settled = true\n resolve(size)\n }\n const img = new Image()\n img.onload = () => finish({ width: img.naturalWidth, height: img.naturalHeight })\n img.onerror = () => finish({ width: 0, height: 0 })\n // A URL that never loads (or an environment that never fires load/error)\n // must not hang the insert forever.\n setTimeout(() => finish({ width: 0, height: 0 }), PROBE_TIMEOUT_MS)\n img.src = url\n })\n}\n\nfunction UploadGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 9l5-5 5 5M12 4v12\" />\n </svg>\n )\n}\n\nfunction SparkleGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 3v3m0 12v3M3 12h3m12 0h3M5.6 5.6l2.1 2.1m8.6 8.6 2.1 2.1m0-12.8-2.1 2.1M7.7 16.3l-2.1 2.1\" />\n </svg>\n )\n}\n\nfunction SpinnerGlyph({ className }: { className?: string }) {\n return (\n <svg className={`${className ?? ''} animate-spin`} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" aria-hidden>\n <path d=\"M21 12a9 9 0 1 1-6.2-8.6\" strokeLinecap=\"round\" />\n </svg>\n )\n}\n\n/** Probe-page geometry for deriving a template's primary element kind. The\n * result drives only the tile preview, so the exact dimensions don't matter. */\nconst PREVIEW_PROBE_PAGE: InsertPageGeometry = { pageId: 'preview', width: 1000, height: 1000 }\n\n/** The visual a template tile shows. Derived from the first element the\n * template's (pure) `build` produces, so custom templates render correctly\n * too — not just the built-in set. */\ntype TemplateShape = 'heading' | 'body' | 'rect' | 'ellipse' | 'other'\n\n/** A text element is treated as a heading (shown as \"T\") when it reads as a\n * title — bold or set in a large face; otherwise body copy (shown as \"¶\"). */\nconst HEADING_FONT_SIZE = 32\n\nfunction templateShape(tpl: InsertTemplate): TemplateShape {\n try {\n const ops = tpl.build(PREVIEW_PROBE_PAGE)\n const added = ops.find((op) => op.type === 'add_element')\n if (!added || added.type !== 'add_element') return 'other'\n const el = added.element\n if (el.kind === 'rect') return 'rect'\n if (el.kind === 'ellipse') return 'ellipse'\n if (el.kind === 'text') {\n const isHeading = el.fontStyle.includes('bold') || el.fontSize >= HEADING_FONT_SIZE\n return isHeading ? 'heading' : 'body'\n }\n return 'other'\n } catch {\n // A throwing build can't preview; fall through to the neutral shape glyph.\n return 'other'\n }\n}\n\n/** A small visual standing in for what the template inserts, so tiles are\n * distinguishable at a glance instead of four identical text chips. */\nfunction TemplatePreview({ shape }: { shape: TemplateShape }) {\n if (shape === 'rect') {\n return <span className=\"block h-6 w-9 rounded-sm bg-[var(--brand-primary)]\" aria-hidden />\n }\n if (shape === 'ellipse') {\n return <span className=\"block h-7 w-7 rounded-full bg-[var(--brand-primary)]\" aria-hidden />\n }\n // Text tiles show a glyph: a bold \"T\" for a heading, a paragraph mark \"¶\"\n // for body copy.\n if (shape === 'heading' || shape === 'body') {\n return (\n <span\n className={`block leading-none text-[var(--text-primary)] ${\n shape === 'heading' ? 'text-2xl font-bold' : 'text-lg'\n }`}\n aria-hidden\n >\n {shape === 'heading' ? 'T' : '¶'}\n </span>\n )\n }\n return <ShapesGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n}\n\nexport function CanvasInsertPanel({\n canWrite,\n page,\n onInsert,\n onUploadImage,\n loadGenerations,\n templates = DEFAULT_INSERT_TEMPLATES,\n accept = DEFAULT_ACCEPT,\n className,\n}: CanvasInsertPanelProps) {\n const [tab, setTab] = useState<Tab>(() => (templates.length > 0 ? 'templates' : 'uploads'))\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState('')\n const [dragOver, setDragOver] = useState(false)\n const [generations, setGenerations] = useState<InsertGeneration[]>([])\n const [generationsLoaded, setGenerationsLoaded] = useState(false)\n const fileInputRef = useRef<HTMLInputElement | null>(null)\n\n useEffect(() => {\n if (tab === 'uploads' && !onUploadImage) {\n setTab(templates.length > 0 ? 'templates' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'templates' && templates.length === 0) {\n setTab(onUploadImage ? 'uploads' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'generations' && !loadGenerations) {\n setTab(templates.length > 0 ? 'templates' : onUploadImage ? 'uploads' : 'templates')\n }\n }, [tab, templates.length, onUploadImage, loadGenerations])\n\n useEffect(() => {\n if (tab !== 'generations' || generationsLoaded || !loadGenerations) return\n let cancelled = false\n void (async () => {\n try {\n const rows = await loadGenerations()\n if (!cancelled) setGenerations(rows.filter((g) => g.url))\n } catch (err) {\n if (!cancelled) setError(err instanceof Error ? err.message : 'Could not load generations')\n } finally {\n if (!cancelled) setGenerationsLoaded(true)\n }\n })()\n return () => {\n cancelled = true\n }\n }, [tab, generationsLoaded, loadGenerations])\n\n async function insertImageFromUrl(url: string) {\n // Validate the media boundary BEFORE probing — a data: or sandbox-local url\n // throws here (surfaced as an inline error) without a wasted image load.\n assertSceneMediaSrc(url, 'image src')\n const natural = await probeImageSize(url)\n await onInsert([buildInsertImageOp(url, natural, page)])\n }\n\n async function handleFiles(files: FileList | File[]) {\n if (!canWrite || busy) return\n if (!onUploadImage) return\n const list = Array.from(files).filter((f) => f.type.startsWith('image/'))\n if (list.length === 0) {\n setError('Only image files can be added to the canvas')\n return\n }\n setBusy(true)\n setError('')\n try {\n for (const file of list) {\n const url = await onUploadImage(file)\n await insertImageFromUrl(url)\n }\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Upload failed')\n } finally {\n setBusy(false)\n }\n }\n\n async function runInsert(build: () => SceneOperation[] | Promise<SceneOperation[]>) {\n if (!canWrite || busy) return\n setBusy(true)\n setError('')\n try {\n await onInsert(await build())\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Insert failed')\n } finally {\n setBusy(false)\n }\n }\n\n const tabs: Array<{ id: Tab; label: string; icon: (p: { className?: string }) => ReactElement; show: boolean }> = [\n { id: 'uploads', label: 'Uploads', icon: ImageGlyph, show: !!onUploadImage },\n { id: 'templates', label: 'Templates', icon: ShapesGlyph, show: templates.length > 0 },\n { id: 'generations', label: 'Generations', icon: SparkleGlyph, show: !!loadGenerations },\n ]\n const visibleTabs = tabs.filter((t) => t.show)\n\n return (\n <div className={`flex h-full min-h-0 flex-col bg-[var(--bg-input)] text-[var(--text-primary)] ${className ?? ''}`}>\n <div className=\"flex shrink-0 border-b border-[var(--border-default)]\">\n {visibleTabs.map(({ id, label, icon: Icon }) => (\n <button\n key={id}\n type=\"button\"\n onClick={() => setTab(id)}\n // These tabs sit flush against the top and side edges of a panel\n // that clips its overflow, so the floor's outward ring is cut off on\n // three sides and reads as a stray underline. The negative offset\n // draws the same ring inside the tab; width and colour still come\n // from the tokens.\n className={`flex flex-1 items-center justify-center gap-1.5 px-2 py-2.5 text-xs font-medium transition-colors focus-visible:[outline-offset:-2px] ${\n tab === id\n ? 'border-b-2 border-[var(--brand-primary)] text-[var(--text-primary)]'\n : 'text-[var(--text-muted)] hover:text-[var(--text-primary)]'\n }`}\n >\n <Icon className=\"h-3.5 w-3.5\" />\n {label}\n </button>\n ))}\n </div>\n\n {!canWrite ? (\n <div className=\"flex flex-1 items-center justify-center p-4 text-center text-sm text-[var(--text-muted)]\">\n You have view-only access to this design.\n </div>\n ) : (\n <div className=\"min-h-0 flex-1 overflow-y-auto p-3\">\n {tab === 'uploads' && (\n <div className=\"flex flex-col gap-3\">\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => fileInputRef.current?.click()}\n onDragOver={(e) => {\n e.preventDefault()\n setDragOver(true)\n }}\n onDragLeave={() => setDragOver(false)}\n onDrop={(e) => {\n e.preventDefault()\n setDragOver(false)\n if (e.dataTransfer?.files?.length) void handleFiles(e.dataTransfer.files)\n }}\n className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-4 py-8 text-center transition-colors disabled:opacity-50 ${\n dragOver\n ? 'border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_5%,transparent)]'\n : 'border-[var(--border-default)] hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)]'\n }`}\n >\n {busy ? (\n <SpinnerGlyph className=\"h-6 w-6 text-[var(--brand-primary)]\" />\n ) : (\n <UploadGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n )}\n <span className=\"text-sm font-medium text-[var(--text-primary)]\">\n {busy ? 'Uploading…' : 'Drop an image or click to upload'}\n </span>\n <span className=\"text-xs text-[var(--text-muted)]\">PNG, JPEG, GIF, or WebP</span>\n </button>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept={accept}\n multiple\n className=\"hidden\"\n onChange={(e) => {\n if (e.target.files?.length) void handleFiles(e.target.files)\n e.target.value = ''\n }}\n />\n </div>\n )}\n\n {tab === 'templates' && (\n <div className=\"grid grid-cols-2 gap-2\">\n {templates.map((tpl) => (\n <button\n key={tpl.id}\n type=\"button\"\n disabled={busy}\n onClick={() => void runInsert(() => tpl.build(page))}\n className=\"flex h-20 flex-col items-center justify-center gap-1.5 rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] text-xs font-medium text-[var(--text-primary)] transition-colors hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)] disabled:opacity-50\"\n >\n <span className=\"flex h-7 items-center justify-center\">\n <TemplatePreview shape={templateShape(tpl)} />\n </span>\n <span>{tpl.label}</span>\n </button>\n ))}\n </div>\n )}\n\n {tab === 'generations' && (\n <div className=\"flex flex-col gap-2\">\n {!generationsLoaded ? (\n <div className=\"flex items-center justify-center py-8 text-[var(--text-muted)]\">\n <SpinnerGlyph className=\"h-5 w-5\" />\n </div>\n ) : generations.length === 0 ? (\n <p className=\"px-1 py-6 text-center text-sm text-[var(--text-muted)]\">\n No generated images yet. Ask the agent to generate one.\n </p>\n ) : (\n <div className=\"grid grid-cols-2 gap-2\">\n {generations.map((gen) => (\n <button\n key={gen.id}\n type=\"button\"\n disabled={busy}\n onClick={() => {\n if (busy || !canWrite) return\n setBusy(true)\n setError('')\n insertImageFromUrl(gen.url)\n .catch((err) => setError(err instanceof Error ? err.message : 'Insert failed'))\n .finally(() => setBusy(false))\n }}\n title={gen.label}\n className=\"group relative aspect-square overflow-hidden rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] transition-colors hover:border-[var(--brand-primary)] disabled:opacity-50\"\n >\n {/* eslint-disable-next-line jsx-a11y/img-redundant-alt */}\n <img src={gen.url} alt={gen.label || 'Generated image'} className=\"h-full w-full object-cover\" />\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n\n {error ? <p className=\"mt-3 text-xs leading-5 text-[var(--text-danger,#dc2626)]\">{error}</p> : null}\n </div>\n )}\n </div>\n )\n}\n","/**\n * Layers panel — reverse-z list of the active page's elements. Highest z-index\n * is at the top. Groups show their children indented beneath them. Clicking\n * selects an element; meta-click adds to selection. Double-clicking the name\n * opens an inline rename input. Eye and lock icons toggle visibility/locked.\n * Rows can be drag-reordered within the list (siblings only; cross-group reorder\n * is a pending integrator concern). Capped at LAYERS_PANEL_ROW_LIMIT rows.\n */\n\nimport { useCallback, useMemo, useRef, useState } from 'react'\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\nimport { flattenLayerTree, LAYERS_PANEL_ROW_LIMIT } from './layer-tree'\nimport {\n EllipseGlyph,\n EyeGlyph,\n EyeOffGlyph,\n GroupGlyph,\n ImageGlyph,\n LineGlyph,\n LockGlyph,\n RectGlyph,\n SlotGlyph,\n TextGlyph,\n UnlockGlyph,\n VideoGlyph,\n} from './glyphs'\nimport type { SceneElementKind } from '../../design-canvas/model'\n\nfunction KindIcon({ kind, className }: { kind: SceneElementKind; className?: string }) {\n switch (kind) {\n case 'rect': return <RectGlyph className={className} />\n case 'ellipse': return <EllipseGlyph className={className} />\n case 'line': return <LineGlyph className={className} />\n case 'text': return <TextGlyph className={className} />\n case 'image': return <ImageGlyph className={className} />\n case 'video': return <VideoGlyph className={className} />\n case 'group': return <GroupGlyph className={className} />\n }\n}\n\nexport interface LayersPanelProps {\n page: ScenePage\n selectedElementIds: string[]\n canWrite: boolean\n /** Emit a set_attrs command for the given element. */\n onSetAttrs(elementId: string, attrs: Partial<Pick<SceneElement, 'name' | 'visible' | 'locked'>>): void\n /** Emit a reorder_element command. */\n onReorder(elementId: string, toIndex: number): void\n onSelect(elementId: string, additive: boolean): void\n}\n\nconst INDENT_PX = 16\n\nexport function LayersPanel({ page, selectedElementIds, canWrite, onSetAttrs, onReorder, onSelect }: LayersPanelProps) {\n const rows = useMemo(() => flattenLayerTree(page), [page])\n const [renamingId, setRenamingId] = useState<string | null>(null)\n const [renameValue, setRenameValue] = useState('')\n\n // Drag-reorder state: we track the dragged row's ownerIndex and the target\n // index within the SAME owner. Cross-owner reorder is not supported here.\n const dragRowRef = useRef<{ elementId: string; ownerIndex: number; ownerLength: number } | null>(null)\n const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)\n\n function startRename(element: SceneElement) {\n setRenamingId(element.id)\n setRenameValue(element.name)\n }\n\n function commitRename(elementId: string) {\n const name = renameValue.trim()\n if (name.length > 0) onSetAttrs(elementId, { name })\n setRenamingId(null)\n }\n\n const visible = rows.length > LAYERS_PANEL_ROW_LIMIT ? rows.slice(0, LAYERS_PANEL_ROW_LIMIT) : rows\n\n return (\n <div className=\"flex h-full flex-col overflow-hidden text-[var(--text-primary)]\">\n <div className=\"shrink-0 border-b border-[var(--border-default)] px-3 py-1.5 text-[11px] font-medium uppercase tracking-wide text-[var(--text-muted)]\">\n Layers\n </div>\n\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {visible.length === 0 ? (\n <div className=\"px-3 py-2 text-[11px] text-[var(--text-muted)]\">No layers yet</div>\n ) : null}\n {visible.map((row) => {\n const { element } = row\n const isSelected = selectedElementIds.includes(element.id)\n const isRenaming = renamingId === element.id\n\n return (\n <div\n key={element.id}\n data-layer-row={element.id}\n draggable={canWrite}\n onDragStart={() => {\n dragRowRef.current = {\n elementId: element.id,\n ownerIndex: row.ownerIndex,\n ownerLength: row.ownerLength,\n }\n }}\n onDragOver={(event) => {\n if (!dragRowRef.current) return\n // Only allow reorder within the same owner (same parentGroupId + depth)\n event.preventDefault()\n setDragOverIndex(row.ownerIndex)\n }}\n onDragLeave={() => setDragOverIndex(null)}\n onDrop={() => {\n const drag = dragRowRef.current\n if (!drag) return\n if (drag.elementId !== element.id) {\n onReorder(drag.elementId, row.ownerIndex)\n }\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n onDragEnd={() => {\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n className={[\n 'group flex items-center gap-1.5 py-1 pr-2 text-[13px] transition-colors',\n isSelected ? 'bg-[color-mix(in_srgb,var(--brand-primary)_15%,transparent)] text-[var(--text-primary)]' : 'hover:bg-[color-mix(in_srgb,var(--border-default)_40%,transparent)] text-[var(--text-secondary)]',\n dragOverIndex === row.ownerIndex ? 'border-t border-[var(--brand-primary)]' : '',\n ].join(' ')}\n style={{ paddingLeft: 8 + row.depth * INDENT_PX }}\n >\n {isRenaming ? (\n <input\n autoFocus\n value={renameValue}\n onChange={(event) => setRenameValue(event.target.value)}\n onBlur={() => commitRename(element.id)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') commitRename(element.id)\n if (event.key === 'Escape') setRenamingId(null)\n event.stopPropagation()\n }}\n className=\"min-w-0 flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-1 py-0 text-[13px] text-[var(--text-primary)] focus:border-[var(--brand-primary)]\"\n />\n ) : (\n // Selection is a real button (sibling of the eye/lock buttons) so\n // the row is not an interactive control nesting interactive\n // controls (axe: nested-interactive).\n <button\n type=\"button\"\n onClick={(event) => onSelect(element.id, event.metaKey || event.ctrlKey)}\n onDoubleClick={() => {\n if (canWrite) startRename(element)\n }}\n title={element.name}\n className=\"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5 bg-transparent text-left\"\n >\n <KindIcon kind={element.kind} className=\"h-3.5 w-3.5 shrink-0 opacity-60\" />\n {element.slot ? <SlotGlyph className=\"h-3 w-3 shrink-0 text-[var(--brand-primary)]\" /> : null}\n <span className=\"min-w-0 flex-1 truncate\">{element.name}</span>\n </button>\n )}\n\n {/* Visibility toggle */}\n <button\n type=\"button\"\n aria-label={element.visible ? 'Hide element' : 'Show element'}\n aria-pressed={!element.visible}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { visible: !element.visible })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.visible ? 'opacity-0' : 'opacity-100',\n ].join(' ')}\n >\n {element.visible\n ? <EyeGlyph className=\"h-3.5 w-3.5\" />\n : <EyeOffGlyph className=\"h-3.5 w-3.5 text-[var(--text-muted)]\" />}\n </button>\n\n {/* Lock toggle */}\n <button\n type=\"button\"\n aria-label={element.locked ? 'Unlock element' : 'Lock element'}\n aria-pressed={!!element.locked}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { locked: !element.locked })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.locked ? 'opacity-100' : 'opacity-0',\n ].join(' ')}\n >\n {element.locked\n ? <LockGlyph className=\"h-3.5 w-3.5 text-[var(--text-warning)]\" />\n : <UnlockGlyph className=\"h-3.5 w-3.5\" />}\n </button>\n </div>\n )\n })}\n\n {rows.length > LAYERS_PANEL_ROW_LIMIT ? (\n <div className=\"px-3 py-2 text-[11px] text-[var(--text-muted)]\">\n +{rows.length - LAYERS_PANEL_ROW_LIMIT} more elements — select a group to scope the list\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n","/**\n * Pure layer-tree helpers: flatten a page's element array into an ordered list\n * for the LayersPanel, preserving group nesting. Extracted so render order,\n * depth, and selection math can be unit-tested independently of React.\n */\n\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\n\n/** Describe a layer row with its element, depth, grouping, ownership, and parent group details */\nexport interface LayerRow {\n element: SceneElement\n depth: number\n /** True when this row is a group whose children follow it in the list. */\n isGroup: boolean\n /** Index within its owner (page.elements or group.children). */\n ownerIndex: number\n /** Length of the owner array — needed for z-order bound math. */\n ownerLength: number\n /** Id of the containing group, or null for page-root elements. */\n parentGroupId: string | null\n}\n\n/**\n * Flatten `page.elements` into display order for the layers panel.\n *\n * Z-order is bottom→top in the element array; the layers panel shows\n * top→bottom (highest z-index first). A group row precedes its children\n * (the group is \"above\" its children in the panel, reflecting that the group\n * node itself paints last in Konva when empty; children paint inside it).\n *\n * Depth increases by 1 for each group level, starting at 0 for page-root\n * elements. Groups are expanded; collapsed state is a view concern the caller\n * tracks separately.\n */\nexport function flattenLayerTree(page: ScenePage): LayerRow[] {\n const rows: LayerRow[] = []\n\n function visit(elements: SceneElement[], depth: number, parentGroupId: string | null) {\n // Reverse so highest z-index appears at the top of the panel.\n for (let i = elements.length - 1; i >= 0; i -= 1) {\n const element = elements[i]!\n rows.push({\n element,\n depth,\n isGroup: element.kind === 'group',\n ownerIndex: i,\n ownerLength: elements.length,\n parentGroupId,\n })\n if (element.kind === 'group') {\n visit(element.children, depth + 1, element.id)\n }\n }\n }\n\n visit(page.elements, 0, null)\n return rows\n}\n\n/** The maximum number of rows the layers panel renders before truncating. */\nexport const LAYERS_PANEL_ROW_LIMIT = 500\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,WAAW,QAAQ,gBAAmC;AAsEzD,cAqLI,YArLJ;AA9BN,IAAM,iBAAiB;AAMvB,IAAM,mBAAmB;AAEzB,SAAS,eAAe,KAAyD;AAC/E,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,OAAO,UAAU,YAAa,QAAO,QAAQ,EAAE,OAAO,GAAG,QAAQ,EAAE,CAAC;AACxE,QAAI,UAAU;AACd,UAAM,SAAS,CAAC,SAA4C;AAC1D,UAAI,QAAS;AACb,gBAAU;AACV,cAAQ,IAAI;AAAA,IACd;AACA,UAAM,MAAM,IAAI,MAAM;AACtB,QAAI,SAAS,MAAM,OAAO,EAAE,OAAO,IAAI,cAAc,QAAQ,IAAI,cAAc,CAAC;AAChF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AAU;AAClB,0BAAM,gBAAgB;AACtB,wBAAI,SAAU,YAAW,QAAQ,IAAI,EAAE,SAAS,CAAC,QAAQ,QAAQ,CAAC;AAAA,kBACpE;AAAA,kBACA,UAAU,CAAC;AAAA,kBACX,WAAW;AAAA,oBACT;AAAA,oBACA,QAAQ,UAAU,cAAc;AAAA,kBAClC,EAAE,KAAK,GAAG;AAAA,kBAET,kBAAQ,UACL,gBAAAA,KAAC,YAAS,WAAU,eAAc,IAClC,gBAAAA,KAAC,eAAY,WAAU,wCAAuC;AAAA;AAAA,cACpE;AAAA,cAGA,gBAAAA;AAAA,gBAAC;AAAA;AAAA,kBACC,MAAK;AAAA,kBACL,cAAY,QAAQ,SAAS,mBAAmB;AAAA,kBAChD,gBAAc,CAAC,CAAC,QAAQ;AAAA,kBACxB,SAAS,CAAC,UAAU;AAClB,0BAAM,gBAAgB;AACtB,wBAAI,SAAU,YAAW,QAAQ,IAAI,EAAE,QAAQ,CAAC,QAAQ,OAAO,CAAC;AAAA,kBAClE;AAAA,kBACA,UAAU,CAAC;AAAA,kBACX,WAAW;AAAA,oBACT;AAAA,oBACA,QAAQ,SAAS,gBAAgB;AAAA,kBACnC,EAAE,KAAK,GAAG;AAAA,kBAET,kBAAQ,SACL,gBAAAA,KAAC,aAAU,WAAU,0CAAyC,IAC9D,gBAAAA,KAAC,eAAY,WAAU,eAAc;AAAA;AAAA,cAC3C;AAAA;AAAA;AAAA,UA3GK,QAAQ;AAAA,QA4Gf;AAAA,MAEJ,CAAC;AAAA,MAEA,KAAK,SAAS,yBACb,gBAAAC,MAAC,SAAI,WAAU,kDAAiD;AAAA;AAAA,QAC5D,KAAK,SAAS;AAAA,QAAuB;AAAA,SACzC,IACE;AAAA,OACN;AAAA,KACF;AAEJ;","names":["useRef","useState","jsx","jsxs","useState","useRef"]}
|
|
1
|
+
{"version":3,"sources":["../../src/design-canvas-react/components/CanvasInsertPanel.tsx","../../src/design-canvas-react/components/LayersPanel.tsx","../../src/design-canvas-react/components/layer-tree.ts"],"sourcesContent":["/**\n * The human \"add element to the canvas\" side panel — a reusable left rail any\n * canvas consumer can mount so a person (not just the agent) can put images,\n * shapes, and text on the canvas. Designed for the `renderSidePanel` slot of\n * {@link DesignCanvasProps}; pass `renderSidePanel={(ctx) => <CanvasInsertPanel … />}`.\n *\n * Endpoints are per-app, so every I/O path is a callback — no product route is\n * hardcoded:\n * - `onUploadImage(file) => Promise<url>` — optional. When provided, the host\n * stores the file and returns the src to insert. The url MUST be http(s) or\n * a rooted `/api/` path (enforced by `assertSceneMediaSrc` before insertion);\n * a `data:` url is rejected, matching the scene model's media boundary.\n * - `loadGenerations?()` — optional provider for \"already generated in this\n * workspace\" images; omit to hide the tab.\n * - `templates?` — optional template set; defaults to {@link DEFAULT_INSERT_TEMPLATES}.\n *\n * Insertion goes through `onInsert`, which the host wires to its\n * `onApplyOperations` pipeline (server-validated, undoable) — the same path\n * every other edit takes.\n *\n * Tokens/icons follow the canvas convention: CSS-var design tokens and inline\n * SVG glyphs, no icon-library or Tailwind-semantic-token dependency.\n */\n\nimport { useEffect, useRef, useState, type ReactElement } from 'react'\nimport type { SceneOperation } from '../../design-canvas/operations'\nimport { assertSceneMediaSrc } from '../../design-canvas/model'\nimport {\n DEFAULT_INSERT_TEMPLATES,\n buildInsertImageOp,\n type InsertPageGeometry,\n type InsertTemplate,\n} from '../insert-builders'\nimport { ImageGlyph, ShapesGlyph } from './glyphs'\n\n/** An already-generated image the panel can offer for one-click insertion. */\nexport interface InsertGeneration {\n id: string\n /** The image url to insert. Must satisfy the scene media boundary\n * (http(s) or rooted `/api/`); rejected otherwise at insert time. */\n url: string\n /** Optional prompt/label shown as the tile's title. */\n label?: string\n}\n\nexport interface CanvasInsertPanelProps {\n canWrite: boolean\n /** The active page new elements are added to. */\n page: InsertPageGeometry\n /** Submit operations through the host's apply pipeline. */\n onInsert(operations: SceneOperation[]): Promise<unknown>\n /** Store an uploaded file and return its src (http(s) or rooted `/api/`). */\n onUploadImage?(file: File): Promise<string>\n /** Optional provider for the Generations tab; omit to hide it. */\n loadGenerations?(): Promise<InsertGeneration[]>\n /** Drop-in templates; defaults to the built-in starter set. */\n templates?: readonly InsertTemplate[]\n /** Accepted upload mime types. Default: PNG/JPEG/GIF/WebP. */\n accept?: string\n className?: string\n}\n\ntype Tab = 'uploads' | 'templates' | 'generations'\n\nconst DEFAULT_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp'\n\n/** Read an image url's natural dimensions in the browser; resolves `{0,0}` when\n * Image is unavailable (SSR/tests), the load fails, or the probe times out —\n * builders fall back to the size cap, so a failed probe still inserts a sensibly\n * sized element rather than blocking insertion. */\nconst PROBE_TIMEOUT_MS = 4000\n\nfunction probeImageSize(url: string): Promise<{ width: number; height: number }> {\n return new Promise((resolve) => {\n if (typeof Image === 'undefined') return resolve({ width: 0, height: 0 })\n let settled = false\n const finish = (size: { width: number; height: number }) => {\n if (settled) return\n settled = true\n resolve(size)\n }\n const img = new Image()\n img.onload = () => finish({ width: img.naturalWidth, height: img.naturalHeight })\n img.onerror = () => finish({ width: 0, height: 0 })\n // A URL that never loads (or an environment that never fires load/error)\n // must not hang the insert forever.\n setTimeout(() => finish({ width: 0, height: 0 }), PROBE_TIMEOUT_MS)\n img.src = url\n })\n}\n\nfunction UploadGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 9l5-5 5 5M12 4v12\" />\n </svg>\n )\n}\n\nfunction SparkleGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 3v3m0 12v3M3 12h3m12 0h3M5.6 5.6l2.1 2.1m8.6 8.6 2.1 2.1m0-12.8-2.1 2.1M7.7 16.3l-2.1 2.1\" />\n </svg>\n )\n}\n\nfunction SpinnerGlyph({ className }: { className?: string }) {\n return (\n <svg className={`${className ?? ''} animate-spin`} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" aria-hidden>\n <path d=\"M21 12a9 9 0 1 1-6.2-8.6\" strokeLinecap=\"round\" />\n </svg>\n )\n}\n\n/** Probe-page geometry for deriving a template's primary element kind. The\n * result drives only the tile preview, so the exact dimensions don't matter. */\nconst PREVIEW_PROBE_PAGE: InsertPageGeometry = { pageId: 'preview', width: 1000, height: 1000 }\n\n/** The visual a template tile shows. Derived from the first element the\n * template's (pure) `build` produces, so custom templates render correctly\n * too — not just the built-in set. */\ntype TemplateShape = 'heading' | 'body' | 'rect' | 'ellipse' | 'other'\n\n/** A text element is treated as a heading (shown as \"T\") when it reads as a\n * title — bold or set in a large face; otherwise body copy (shown as \"¶\"). */\nconst HEADING_FONT_SIZE = 32\n\nfunction templateShape(tpl: InsertTemplate): TemplateShape {\n try {\n const ops = tpl.build(PREVIEW_PROBE_PAGE)\n const added = ops.find((op) => op.type === 'add_element')\n if (!added || added.type !== 'add_element') return 'other'\n const el = added.element\n if (el.kind === 'rect') return 'rect'\n if (el.kind === 'ellipse') return 'ellipse'\n if (el.kind === 'text') {\n const isHeading = el.fontStyle.includes('bold') || el.fontSize >= HEADING_FONT_SIZE\n return isHeading ? 'heading' : 'body'\n }\n return 'other'\n } catch {\n // A throwing build can't preview; fall through to the neutral shape glyph.\n return 'other'\n }\n}\n\n/** A small visual standing in for what the template inserts, so tiles are\n * distinguishable at a glance instead of four identical text chips. */\nfunction TemplatePreview({ shape }: { shape: TemplateShape }) {\n if (shape === 'rect') {\n return <span className=\"block h-6 w-9 rounded-sm bg-[var(--brand-primary)]\" aria-hidden />\n }\n if (shape === 'ellipse') {\n return <span className=\"block h-7 w-7 rounded-full bg-[var(--brand-primary)]\" aria-hidden />\n }\n // Text tiles show a glyph: a semibold \"T\" for a heading, a paragraph mark\n // \"¶\" for body copy.\n if (shape === 'heading' || shape === 'body') {\n return (\n <span\n className={`block leading-none text-[var(--text-primary)] ${\n shape === 'heading' ? 'text-2xl font-semibold' : 'text-lg'\n }`}\n aria-hidden\n >\n {shape === 'heading' ? 'T' : '¶'}\n </span>\n )\n }\n return <ShapesGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n}\n\nexport function CanvasInsertPanel({\n canWrite,\n page,\n onInsert,\n onUploadImage,\n loadGenerations,\n templates = DEFAULT_INSERT_TEMPLATES,\n accept = DEFAULT_ACCEPT,\n className,\n}: CanvasInsertPanelProps) {\n const [tab, setTab] = useState<Tab>(() => (templates.length > 0 ? 'templates' : 'uploads'))\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState('')\n const [dragOver, setDragOver] = useState(false)\n const [generations, setGenerations] = useState<InsertGeneration[]>([])\n const [generationsLoaded, setGenerationsLoaded] = useState(false)\n const fileInputRef = useRef<HTMLInputElement | null>(null)\n\n useEffect(() => {\n if (tab === 'uploads' && !onUploadImage) {\n setTab(templates.length > 0 ? 'templates' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'templates' && templates.length === 0) {\n setTab(onUploadImage ? 'uploads' : loadGenerations ? 'generations' : 'uploads')\n }\n if (tab === 'generations' && !loadGenerations) {\n setTab(templates.length > 0 ? 'templates' : onUploadImage ? 'uploads' : 'templates')\n }\n }, [tab, templates.length, onUploadImage, loadGenerations])\n\n useEffect(() => {\n if (tab !== 'generations' || generationsLoaded || !loadGenerations) return\n let cancelled = false\n void (async () => {\n try {\n const rows = await loadGenerations()\n if (!cancelled) setGenerations(rows.filter((g) => g.url))\n } catch (err) {\n if (!cancelled) setError(err instanceof Error ? err.message : 'Could not load generations')\n } finally {\n if (!cancelled) setGenerationsLoaded(true)\n }\n })()\n return () => {\n cancelled = true\n }\n }, [tab, generationsLoaded, loadGenerations])\n\n async function insertImageFromUrl(url: string) {\n // Validate the media boundary BEFORE probing — a data: or sandbox-local url\n // throws here (surfaced as an inline error) without a wasted image load.\n assertSceneMediaSrc(url, 'image src')\n const natural = await probeImageSize(url)\n await onInsert([buildInsertImageOp(url, natural, page)])\n }\n\n async function handleFiles(files: FileList | File[]) {\n if (!canWrite || busy) return\n if (!onUploadImage) return\n const list = Array.from(files).filter((f) => f.type.startsWith('image/'))\n if (list.length === 0) {\n setError('Only image files can be added to the canvas')\n return\n }\n setBusy(true)\n setError('')\n try {\n for (const file of list) {\n const url = await onUploadImage(file)\n await insertImageFromUrl(url)\n }\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Upload failed')\n } finally {\n setBusy(false)\n }\n }\n\n async function runInsert(build: () => SceneOperation[] | Promise<SceneOperation[]>) {\n if (!canWrite || busy) return\n setBusy(true)\n setError('')\n try {\n await onInsert(await build())\n } catch (err) {\n setError(err instanceof Error ? err.message : 'Insert failed')\n } finally {\n setBusy(false)\n }\n }\n\n const tabs: Array<{ id: Tab; label: string; icon: (p: { className?: string }) => ReactElement; show: boolean }> = [\n { id: 'uploads', label: 'Uploads', icon: ImageGlyph, show: !!onUploadImage },\n { id: 'templates', label: 'Templates', icon: ShapesGlyph, show: templates.length > 0 },\n { id: 'generations', label: 'Generations', icon: SparkleGlyph, show: !!loadGenerations },\n ]\n const visibleTabs = tabs.filter((t) => t.show)\n\n return (\n <div className={`flex h-full min-h-0 flex-col bg-[var(--bg-input)] text-[var(--text-primary)] ${className ?? ''}`}>\n <div className=\"flex shrink-0 border-b border-[var(--border-default)]\">\n {visibleTabs.map(({ id, label, icon: Icon }) => (\n <button\n key={id}\n type=\"button\"\n onClick={() => setTab(id)}\n // These tabs sit flush against the top and side edges of a panel\n // that clips its overflow, so the floor's outward ring is cut off on\n // three sides and reads as a stray underline. The negative offset\n // draws the same ring inside the tab; width and colour still come\n // from the tokens.\n className={`flex flex-1 items-center justify-center gap-1.5 px-2 py-2.5 text-xs font-medium transition-colors focus-visible:[outline-offset:-2px] ${\n tab === id\n ? 'border-b-2 border-[var(--brand-primary)] text-[var(--text-primary)]'\n : 'text-[var(--text-muted)] hover:text-[var(--text-primary)]'\n }`}\n >\n <Icon className=\"h-3.5 w-3.5\" />\n {label}\n </button>\n ))}\n </div>\n\n {!canWrite ? (\n <div className=\"flex flex-1 items-center justify-center p-4 text-center text-sm text-[var(--text-muted)]\">\n You have view-only access to this design.\n </div>\n ) : (\n <div className=\"min-h-0 flex-1 overflow-y-auto p-3\">\n {tab === 'uploads' && (\n <div className=\"flex flex-col gap-3\">\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => fileInputRef.current?.click()}\n onDragOver={(e) => {\n e.preventDefault()\n setDragOver(true)\n }}\n onDragLeave={() => setDragOver(false)}\n onDrop={(e) => {\n e.preventDefault()\n setDragOver(false)\n if (e.dataTransfer?.files?.length) void handleFiles(e.dataTransfer.files)\n }}\n className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-4 py-8 text-center transition-colors disabled:opacity-50 ${\n dragOver\n ? 'border-[var(--brand-primary)] bg-[color-mix(in_srgb,var(--brand-primary)_5%,transparent)]'\n : 'border-[var(--border-default)] hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)]'\n }`}\n >\n {busy ? (\n <SpinnerGlyph className=\"h-6 w-6 text-[var(--brand-primary)]\" />\n ) : (\n <UploadGlyph className=\"h-6 w-6 text-[var(--text-muted)]\" />\n )}\n <span className=\"text-sm font-medium text-[var(--text-primary)]\">\n {busy ? 'Uploading…' : 'Drop an image or click to upload'}\n </span>\n <span className=\"text-xs text-[var(--text-muted)]\">PNG, JPEG, GIF, or WebP</span>\n </button>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept={accept}\n multiple\n className=\"hidden\"\n onChange={(e) => {\n if (e.target.files?.length) void handleFiles(e.target.files)\n e.target.value = ''\n }}\n />\n </div>\n )}\n\n {tab === 'templates' && (\n <div className=\"grid grid-cols-2 gap-2\">\n {templates.map((tpl) => (\n <button\n key={tpl.id}\n type=\"button\"\n disabled={busy}\n onClick={() => void runInsert(() => tpl.build(page))}\n className=\"flex h-20 flex-col items-center justify-center gap-1.5 rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] text-xs font-medium text-[var(--text-primary)] transition-colors hover:border-[color-mix(in_srgb,var(--brand-primary)_40%,transparent)] disabled:opacity-50\"\n >\n <span className=\"flex h-7 items-center justify-center\">\n <TemplatePreview shape={templateShape(tpl)} />\n </span>\n <span>{tpl.label}</span>\n </button>\n ))}\n </div>\n )}\n\n {tab === 'generations' && (\n <div className=\"flex flex-col gap-2\">\n {!generationsLoaded ? (\n <div className=\"flex items-center justify-center py-8 text-[var(--text-muted)]\">\n <SpinnerGlyph className=\"h-5 w-5\" />\n </div>\n ) : generations.length === 0 ? (\n <p className=\"px-1 py-6 text-center text-sm text-[var(--text-muted)]\">\n No generated images yet. Ask the agent to generate one.\n </p>\n ) : (\n <div className=\"grid grid-cols-2 gap-2\">\n {generations.map((gen) => (\n <button\n key={gen.id}\n type=\"button\"\n disabled={busy}\n onClick={() => {\n if (busy || !canWrite) return\n setBusy(true)\n setError('')\n insertImageFromUrl(gen.url)\n .catch((err) => setError(err instanceof Error ? err.message : 'Insert failed'))\n .finally(() => setBusy(false))\n }}\n title={gen.label}\n className=\"group relative aspect-square overflow-hidden rounded-md border border-[var(--border-default)] bg-[var(--bg-input)] transition-colors hover:border-[var(--brand-primary)] disabled:opacity-50\"\n >\n {/* eslint-disable-next-line jsx-a11y/img-redundant-alt */}\n <img src={gen.url} alt={gen.label || 'Generated image'} className=\"h-full w-full object-cover\" />\n </button>\n ))}\n </div>\n )}\n </div>\n )}\n\n {error ? <p className=\"mt-3 text-xs leading-5 text-[var(--text-danger,#dc2626)]\">{error}</p> : null}\n </div>\n )}\n </div>\n )\n}\n","/**\n * Layers panel — reverse-z list of the active page's elements. Highest z-index\n * is at the top. Groups show their children indented beneath them. Clicking\n * selects an element; meta-click adds to selection. Double-clicking the name\n * opens an inline rename input. Eye and lock icons toggle visibility/locked.\n * Rows can be drag-reordered within the list (siblings only; cross-group reorder\n * is a pending integrator concern). Capped at LAYERS_PANEL_ROW_LIMIT rows.\n */\n\nimport { useCallback, useMemo, useRef, useState } from 'react'\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\nimport { flattenLayerTree, LAYERS_PANEL_ROW_LIMIT } from './layer-tree'\nimport {\n EllipseGlyph,\n EyeGlyph,\n EyeOffGlyph,\n GroupGlyph,\n ImageGlyph,\n LineGlyph,\n LockGlyph,\n RectGlyph,\n SlotGlyph,\n TextGlyph,\n UnlockGlyph,\n VideoGlyph,\n} from './glyphs'\nimport type { SceneElementKind } from '../../design-canvas/model'\n\nfunction KindIcon({ kind, className }: { kind: SceneElementKind; className?: string }) {\n switch (kind) {\n case 'rect': return <RectGlyph className={className} />\n case 'ellipse': return <EllipseGlyph className={className} />\n case 'line': return <LineGlyph className={className} />\n case 'text': return <TextGlyph className={className} />\n case 'image': return <ImageGlyph className={className} />\n case 'video': return <VideoGlyph className={className} />\n case 'group': return <GroupGlyph className={className} />\n }\n}\n\nexport interface LayersPanelProps {\n page: ScenePage\n selectedElementIds: string[]\n canWrite: boolean\n /** Emit a set_attrs command for the given element. */\n onSetAttrs(elementId: string, attrs: Partial<Pick<SceneElement, 'name' | 'visible' | 'locked'>>): void\n /** Emit a reorder_element command. */\n onReorder(elementId: string, toIndex: number): void\n onSelect(elementId: string, additive: boolean): void\n}\n\nconst INDENT_PX = 16\n\nexport function LayersPanel({ page, selectedElementIds, canWrite, onSetAttrs, onReorder, onSelect }: LayersPanelProps) {\n const rows = useMemo(() => flattenLayerTree(page), [page])\n const [renamingId, setRenamingId] = useState<string | null>(null)\n const [renameValue, setRenameValue] = useState('')\n\n // Drag-reorder state: we track the dragged row's ownerIndex and the target\n // index within the SAME owner. Cross-owner reorder is not supported here.\n const dragRowRef = useRef<{ elementId: string; ownerIndex: number; ownerLength: number } | null>(null)\n const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)\n\n function startRename(element: SceneElement) {\n setRenamingId(element.id)\n setRenameValue(element.name)\n }\n\n function commitRename(elementId: string) {\n const name = renameValue.trim()\n if (name.length > 0) onSetAttrs(elementId, { name })\n setRenamingId(null)\n }\n\n const visible = rows.length > LAYERS_PANEL_ROW_LIMIT ? rows.slice(0, LAYERS_PANEL_ROW_LIMIT) : rows\n\n return (\n <div className=\"flex h-full flex-col overflow-hidden text-[var(--text-primary)]\">\n <div className=\"shrink-0 border-b border-[var(--border-default)] px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.05em] text-[var(--text-muted)]\">\n Layers\n </div>\n\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {visible.length === 0 ? (\n <div className=\"px-3 py-2 text-[11px] text-[var(--text-muted)]\">No layers yet</div>\n ) : null}\n {visible.map((row) => {\n const { element } = row\n const isSelected = selectedElementIds.includes(element.id)\n const isRenaming = renamingId === element.id\n\n return (\n <div\n key={element.id}\n data-layer-row={element.id}\n draggable={canWrite}\n onDragStart={() => {\n dragRowRef.current = {\n elementId: element.id,\n ownerIndex: row.ownerIndex,\n ownerLength: row.ownerLength,\n }\n }}\n onDragOver={(event) => {\n if (!dragRowRef.current) return\n // Only allow reorder within the same owner (same parentGroupId + depth)\n event.preventDefault()\n setDragOverIndex(row.ownerIndex)\n }}\n onDragLeave={() => setDragOverIndex(null)}\n onDrop={() => {\n const drag = dragRowRef.current\n if (!drag) return\n if (drag.elementId !== element.id) {\n onReorder(drag.elementId, row.ownerIndex)\n }\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n onDragEnd={() => {\n dragRowRef.current = null\n setDragOverIndex(null)\n }}\n className={[\n 'group flex items-center gap-1.5 py-1 pr-2 text-sm transition-colors',\n isSelected ? 'bg-[color-mix(in_srgb,var(--brand-primary)_15%,transparent)] text-[var(--text-primary)]' : 'hover:bg-[color-mix(in_srgb,var(--border-default)_40%,transparent)] text-[var(--text-secondary)]',\n dragOverIndex === row.ownerIndex ? 'border-t border-[var(--brand-primary)]' : '',\n ].join(' ')}\n style={{ paddingLeft: 8 + row.depth * INDENT_PX }}\n >\n {isRenaming ? (\n <input\n autoFocus\n value={renameValue}\n onChange={(event) => setRenameValue(event.target.value)}\n onBlur={() => commitRename(element.id)}\n onKeyDown={(event) => {\n if (event.key === 'Enter') commitRename(element.id)\n if (event.key === 'Escape') setRenamingId(null)\n event.stopPropagation()\n }}\n className=\"min-w-0 flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-input)] px-1 py-0 text-sm text-[var(--text-primary)] focus:border-[var(--brand-primary)]\"\n />\n ) : (\n // Selection is a real button (sibling of the eye/lock buttons) so\n // the row is not an interactive control nesting interactive\n // controls (axe: nested-interactive).\n <button\n type=\"button\"\n onClick={(event) => onSelect(element.id, event.metaKey || event.ctrlKey)}\n onDoubleClick={() => {\n if (canWrite) startRename(element)\n }}\n title={element.name}\n className=\"flex min-w-0 flex-1 cursor-pointer items-center gap-1.5 bg-transparent text-left\"\n >\n <KindIcon kind={element.kind} className=\"h-3.5 w-3.5 shrink-0 opacity-60\" />\n {element.slot ? <SlotGlyph className=\"h-3 w-3 shrink-0 text-[var(--brand-primary)]\" /> : null}\n <span className=\"min-w-0 flex-1 truncate\">{element.name}</span>\n </button>\n )}\n\n {/* Visibility toggle */}\n <button\n type=\"button\"\n aria-label={element.visible ? 'Hide element' : 'Show element'}\n aria-pressed={!element.visible}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { visible: !element.visible })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.visible ? 'opacity-0' : 'opacity-100',\n ].join(' ')}\n >\n {element.visible\n ? <EyeGlyph className=\"h-3.5 w-3.5\" />\n : <EyeOffGlyph className=\"h-3.5 w-3.5 text-[var(--text-muted)]\" />}\n </button>\n\n {/* Lock toggle */}\n <button\n type=\"button\"\n aria-label={element.locked ? 'Unlock element' : 'Lock element'}\n aria-pressed={!!element.locked}\n onClick={(event) => {\n event.stopPropagation()\n if (canWrite) onSetAttrs(element.id, { locked: !element.locked })\n }}\n disabled={!canWrite}\n className={[\n 'shrink-0 rounded p-0.5 transition-opacity group-hover:opacity-100 hover:opacity-100 focus-visible:opacity-100',\n element.locked ? 'opacity-100' : 'opacity-0',\n ].join(' ')}\n >\n {element.locked\n ? <LockGlyph className=\"h-3.5 w-3.5 text-[var(--text-warning)]\" />\n : <UnlockGlyph className=\"h-3.5 w-3.5\" />}\n </button>\n </div>\n )\n })}\n\n {rows.length > LAYERS_PANEL_ROW_LIMIT ? (\n <div className=\"px-3 py-2 text-[11px] text-[var(--text-muted)]\">\n +{rows.length - LAYERS_PANEL_ROW_LIMIT} more elements — select a group to scope the list\n </div>\n ) : null}\n </div>\n </div>\n )\n}\n","/**\n * Pure layer-tree helpers: flatten a page's element array into an ordered list\n * for the LayersPanel, preserving group nesting. Extracted so render order,\n * depth, and selection math can be unit-tested independently of React.\n */\n\nimport type { SceneElement, ScenePage } from '../../design-canvas/model'\n\n/** Describe a layer row with its element, depth, grouping, ownership, and parent group details */\nexport interface LayerRow {\n element: SceneElement\n depth: number\n /** True when this row is a group whose children follow it in the list. */\n isGroup: boolean\n /** Index within its owner (page.elements or group.children). */\n ownerIndex: number\n /** Length of the owner array — needed for z-order bound math. */\n ownerLength: number\n /** Id of the containing group, or null for page-root elements. */\n parentGroupId: string | null\n}\n\n/**\n * Flatten `page.elements` into display order for the layers panel.\n *\n * Z-order is bottom→top in the element array; the layers panel shows\n * top→bottom (highest z-index first). A group row precedes its children\n * (the group is \"above\" its children in the panel, reflecting that the group\n * node itself paints last in Konva when empty; children paint inside it).\n *\n * Depth increases by 1 for each group level, starting at 0 for page-root\n * elements. Groups are expanded; collapsed state is a view concern the caller\n * tracks separately.\n */\nexport function flattenLayerTree(page: ScenePage): LayerRow[] {\n const rows: LayerRow[] = []\n\n function visit(elements: SceneElement[], depth: number, parentGroupId: string | null) {\n // Reverse so highest z-index appears at the top of the panel.\n for (let i = elements.length - 1; i >= 0; i -= 1) {\n const element = elements[i]!\n rows.push({\n element,\n depth,\n isGroup: element.kind === 'group',\n ownerIndex: i,\n ownerLength: elements.length,\n parentGroupId,\n })\n if (element.kind === 'group') {\n visit(element.children, depth + 1, element.id)\n }\n }\n }\n\n visit(page.elements, 0, null)\n return rows\n}\n\n/** The maximum number of rows the layers panel renders before truncating. */\nexport const LAYERS_PANEL_ROW_LIMIT = 500\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,WAAW,QAAQ,gBAAmC;AAsEzD,cAqLI,YArLJ;AA9BN,IAAM,iBAAiB;AAMvB,IAAM,mBAAmB;AAEzB,SAAS,eAAe,KAAyD;AAC/E,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,OAAO,UAAU,YAAa,QAAO,QAAQ,EAAE,OAAO,GAAG,QAAQ,EAAE,CAAC;AACxE,QAAI,UAAU;AACd,UAAM,SAAS,CAAC,SAA4C;AAC1D,UAAI,QAAS;AACb,gBAAU;AACV,cAAQ,IAAI;AAAA,IACd;AACA,UAAM,MAAM,IAAI,MAAM;AACtB,QAAI,SAAS,MAAM,OAAO,EAAE,OAAO,IAAI,cAAc,QAAQ,IAAI,cAAc,CAAC;AAChF,QAAI,UAAU,MAAM,OAAO,EAAE,OAAO,GAAG,QAAQ,EAAE,CAAC;AAGlD,eAAW,MAAM,OAAO,EAAE,OAAO,GAAG,QAAQ,EAAE,CAAC,GAAG,gBAAgB;AAClE,QAAI,MAAM;AAAA,EACZ,CAAC;AACH;AAEA,SAAS,YAAY,EAAE,UAAU,GAA2B;AAC1D,SACE,oBAAC,SAAI,WAAsB,SAAQ,aAAY,MAAK,QAAO,QAAO,gBAAe,aAAY,KAAI,eAAc,SAAQ,gBAAe,SAAQ,eAAW,MACvJ,8BAAC,UA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A,cAGA,gBAAAA;AAAA,gBAAC;AAAA;AAAA,kBACC,MAAK;AAAA,kBACL,cAAY,QAAQ,SAAS,mBAAmB;AAAA,kBAChD,gBAAc,CAAC,CAAC,QAAQ;AAAA,kBACxB,SAAS,CAAC,UAAU;AAClB,0BAAM,gBAAgB;AACtB,wBAAI,SAAU,YAAW,QAAQ,IAAI,EAAE,QAAQ,CAAC,QAAQ,OAAO,CAAC;AAAA,kBAClE;AAAA,kBACA,UAAU,CAAC;AAAA,kBACX,WAAW;AAAA,oBACT;AAAA,oBACA,QAAQ,SAAS,gBAAgB;AAAA,kBACnC,EAAE,KAAK,GAAG;AAAA,kBAET,kBAAQ,SACL,gBAAAA,KAAC,aAAU,WAAU,0CAAyC,IAC9D,gBAAAA,KAAC,eAAY,WAAU,eAAc;AAAA;AAAA,cAC3C;AAAA;AAAA;AAAA,UA3GK,QAAQ;AAAA,QA4Gf;AAAA,MAEJ,CAAC;AAAA,MAEA,KAAK,SAAS,yBACb,gBAAAC,MAAC,SAAI,WAAU,kDAAiD;AAAA;AAAA,QAC5D,KAAK,SAAS;AAAA,QAAuB;AAAA,SACzC,IACE;AAAA,OACN;AAAA,KACF;AAEJ;","names":["useRef","useState","jsx","jsxs","useState","useRef"]}
|
package/dist/spend/cli.js
CHANGED
package/dist/spend/index.d.ts
CHANGED
|
@@ -119,9 +119,11 @@ interface ExpectedCeiling {
|
|
|
119
119
|
* reaches for them, because the ledger is the counterparty's record and reading
|
|
120
120
|
* it is the product's authenticated business.
|
|
121
121
|
*
|
|
122
|
-
* The product
|
|
123
|
-
*
|
|
124
|
-
*
|
|
122
|
+
* The rows a product can fetch are scoped to the BILLING OWNER, not to the
|
|
123
|
+
* product: `product: 'sandbox'` is the platform's service taxonomy and every
|
|
124
|
+
* consumer app's compute wears it. So a wallet running two of our products
|
|
125
|
+
* returns both products' settlements, and telling them apart is
|
|
126
|
+
* {@link SpendOwnershipRule}'s job.
|
|
125
127
|
*/
|
|
126
128
|
interface SettlementRow {
|
|
127
129
|
/** The ledger row id, for the dispute. */
|
|
@@ -152,6 +154,103 @@ interface SettlementRow {
|
|
|
152
154
|
* Null is the common case: the platform does not store duration on the row.
|
|
153
155
|
*/
|
|
154
156
|
readonly billedMs: number | null;
|
|
157
|
+
/**
|
|
158
|
+
* The platform API key the charge was triggered by — `credit_transactions.key_id`,
|
|
159
|
+
* stamped from the box's own creation metadata at settlement time and exposed
|
|
160
|
+
* by `/v1/billing/transactions` (which also filters on it).
|
|
161
|
+
*
|
|
162
|
+
* This is the ONLY field on a settlement row that can be attributed back to a
|
|
163
|
+
* PRODUCT rather than to a wallet or to the platform's service taxonomy, which
|
|
164
|
+
* is why {@link SpendOwnershipRule}'s shipped constructor is built on it. The
|
|
165
|
+
* sandbox id cannot do the job: the platform mints it as `sandbox-<12 hex>`
|
|
166
|
+
* from a hash of (owner, idempotency key), so a product's own box naming never
|
|
167
|
+
* reaches the ledger row.
|
|
168
|
+
*
|
|
169
|
+
* Optional, and `null` is a real answer: the platform leaves it null on legacy
|
|
170
|
+
* rows and an export may not carry the column at all. A missing key is
|
|
171
|
+
* `undecidable`, never `foreign` — see {@link SpendOwnershipVerdict}.
|
|
172
|
+
*/
|
|
173
|
+
readonly keyId?: string | null;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* What one settlement is attributable to, from inside ONE product.
|
|
177
|
+
*
|
|
178
|
+
* The distinction this type exists for: a sibling product's box and a charge
|
|
179
|
+
* that is not ours at all look identical from inside a single product, because
|
|
180
|
+
* both arrive as a settlement naming a sandbox this product's expectation ledger
|
|
181
|
+
* has never heard of. Dropping both loses the check's whole purpose; reporting
|
|
182
|
+
* both makes it noise. Only a platform-stamped attribution field separates them.
|
|
183
|
+
*/
|
|
184
|
+
type SpendOwnershipVerdict =
|
|
185
|
+
/** Attributable to THIS product. An unrecorded one is a phantom-charge candidate. */
|
|
186
|
+
'mine'
|
|
187
|
+
/** Attributable to a DIFFERENT product on the same wallet. Reported, never a finding. */
|
|
188
|
+
| 'foreign'
|
|
189
|
+
/**
|
|
190
|
+
* The row carries nothing that decides it. Counted as `mine` — FAIL CLOSED.
|
|
191
|
+
* An unattributable charge on a shared wallet is precisely the shape of the
|
|
192
|
+
* thing this module exists to catch, so the ambiguous case costs a human five
|
|
193
|
+
* minutes rather than costing the product the detection.
|
|
194
|
+
*/
|
|
195
|
+
| 'undecidable';
|
|
196
|
+
/** One settlement, presented to an ownership rule. */
|
|
197
|
+
interface SpendOwnershipCandidate {
|
|
198
|
+
readonly row: SettlementRow;
|
|
199
|
+
/** The sandbox the row is attributable to, or null for a row naming none. */
|
|
200
|
+
readonly sandboxId: string | null;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The product's declaration of which settlements are its own.
|
|
204
|
+
*
|
|
205
|
+
* The one hard constraint on `decide`: it must answer from PROPERTIES OF THE
|
|
206
|
+
* ROW. A rule that answers by looking the sandbox up in the product's own
|
|
207
|
+
* expectation ledger deletes `unknown-box` entirely — every unrecorded box would
|
|
208
|
+
* be `foreign` by construction, and "we were billed for a box we never asked
|
|
209
|
+
* for" would become unrepresentable. The ledger already decides recorded-ness;
|
|
210
|
+
* this decides ATTRIBUTION, and the two must stay independent.
|
|
211
|
+
*
|
|
212
|
+
* `decide` must not throw. If it does, the throw propagates and the whole pass
|
|
213
|
+
* fails — a reconciliation whose ownership rule is broken has no verdict worth
|
|
214
|
+
* printing, and swallowing it would turn a broken rule into a clean bill.
|
|
215
|
+
*/
|
|
216
|
+
interface SpendOwnershipRule {
|
|
217
|
+
/** Named in the report and on every finding, so a reader knows what was excluded. */
|
|
218
|
+
readonly label: string;
|
|
219
|
+
decide(candidate: SpendOwnershipCandidate): SpendOwnershipVerdict;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* What this pass scoped itself to — present on every report, including a clean
|
|
223
|
+
* one, because "nothing fired" and "nothing was looked at" are different
|
|
224
|
+
* answers and a report that cannot tell them apart is the failure this closes.
|
|
225
|
+
*/
|
|
226
|
+
interface SpendOwnershipSummary {
|
|
227
|
+
/**
|
|
228
|
+
* False when the caller declared no rule. The pass then treats every box as
|
|
229
|
+
* its own — today's behaviour, which over-reports rather than under-reports —
|
|
230
|
+
* and every `unknown-box` finding says on its face that a sibling product's
|
|
231
|
+
* box is indistinguishable from a charge that is not ours.
|
|
232
|
+
*/
|
|
233
|
+
readonly declared: boolean;
|
|
234
|
+
/** The rule's label, or null when none was declared. */
|
|
235
|
+
readonly label: string | null;
|
|
236
|
+
/** Boxes this pass treated as this product's, and what they were charged. */
|
|
237
|
+
readonly ownedBoxes: number;
|
|
238
|
+
readonly ownedNanoUsd: number;
|
|
239
|
+
/**
|
|
240
|
+
* Of those, the boxes no rule could decide. Counted as owned (fail-closed) and
|
|
241
|
+
* reported separately so a product can see how much of its own verdict rests
|
|
242
|
+
* on rows that carried no attribution.
|
|
243
|
+
*/
|
|
244
|
+
readonly undecidableBoxes: number;
|
|
245
|
+
/** Boxes attributed to another product on the same wallet. Never findings. */
|
|
246
|
+
readonly foreignBoxes: number;
|
|
247
|
+
readonly foreignNanoUsd: number;
|
|
248
|
+
/**
|
|
249
|
+
* Their ids, in full — an exclusion a reader cannot audit is an exclusion
|
|
250
|
+
* they have to trust, and this module's whole posture is that nothing about
|
|
251
|
+
* money is taken on trust.
|
|
252
|
+
*/
|
|
253
|
+
readonly foreignSandboxIds: readonly string[];
|
|
155
254
|
}
|
|
156
255
|
/** The parts of a settlement reference id, once parsed. */
|
|
157
256
|
interface SettlementReference {
|
|
@@ -236,10 +335,99 @@ interface SpendReport {
|
|
|
236
335
|
readonly settledNanoUsd: number;
|
|
237
336
|
/** Total credited back across every examined row, unsigned nanodollars. */
|
|
238
337
|
readonly creditedNanoUsd: number;
|
|
338
|
+
/** What this pass claimed as its own, and what it excluded as another product's. */
|
|
339
|
+
readonly ownership: SpendOwnershipSummary;
|
|
239
340
|
/** The instant the pass treated as "now". */
|
|
240
341
|
readonly asOf: number;
|
|
241
342
|
}
|
|
242
343
|
|
|
344
|
+
/**
|
|
345
|
+
* Which settlements belong to the product running the reconciliation.
|
|
346
|
+
*
|
|
347
|
+
* ## The problem this module is the answer to
|
|
348
|
+
*
|
|
349
|
+
* A product fetches its settled rows from `/v1/billing/transactions`, scoped to
|
|
350
|
+
* the BILLING OWNER — the wallet whose key paid. `product: 'sandbox'` narrows
|
|
351
|
+
* that to compute, but `sandbox` is the PLATFORM's service taxonomy: every
|
|
352
|
+
* consumer app's box compute wears it. So a Tangle account running two of our
|
|
353
|
+
* products hands each product's reconciliation the other product's boxes, and
|
|
354
|
+
* `unknown-box` — correctly, by its own rule — reports one finding per sibling
|
|
355
|
+
* box. Two products on one wallet make each other's spend check useless.
|
|
356
|
+
*
|
|
357
|
+
* ## Why the obvious fix is the wrong fix
|
|
358
|
+
*
|
|
359
|
+
* The obvious fix is to reconcile only the boxes already in the product's
|
|
360
|
+
* expectation ledger. That removes the false findings and removes the check:
|
|
361
|
+
* `unknown-box` exists to catch "we were billed for a box we never asked for",
|
|
362
|
+
* which is the 2026-08-05 incident's day-one signature and the ONLY thing a
|
|
363
|
+
* product with no lifecycle bookkeeping can catch at all. Filtering to the
|
|
364
|
+
* ledger makes a phantom charge unrepresentable — the ledger's own contents
|
|
365
|
+
* would define the answer.
|
|
366
|
+
*
|
|
367
|
+
* So the residue — settlements against boxes with no ledger record — has to be
|
|
368
|
+
* SPLIT, not dropped. A sibling's box and a phantom charge are indistinguishable
|
|
369
|
+
* unless something outside the product's own bookkeeping tells them apart.
|
|
370
|
+
*
|
|
371
|
+
* ## What can tell them apart
|
|
372
|
+
*
|
|
373
|
+
* Exactly one field on a settlement row, and it is not the sandbox id. The
|
|
374
|
+
* platform mints that id as `sandbox-<12 hex>` — a hash of (owner, idempotency
|
|
375
|
+
* key) — so a product's own box naming never reaches the ledger row, and the
|
|
376
|
+
* charge's `description` carries only the resource spec. What does survive is
|
|
377
|
+
* `credit_transactions.key_id`: the platform API key the box was created under,
|
|
378
|
+
* stamped from the box's own creation metadata at settlement and filterable on
|
|
379
|
+
* the transactions endpoint. Each product deploys with its own key, so the key
|
|
380
|
+
* is the product's billing identity as the PLATFORM recorded it — not as the
|
|
381
|
+
* product asserts it after the fact.
|
|
382
|
+
*
|
|
383
|
+
* That asymmetry is what makes the split safe. A product cannot widen its own
|
|
384
|
+
* claim by claiming; it can only recognise a stamp the platform already wrote.
|
|
385
|
+
*
|
|
386
|
+
* ## The three rules that keep the detection intact
|
|
387
|
+
*
|
|
388
|
+
* 1. **A recorded box is never excluded.** Ownership is consulted only for
|
|
389
|
+
* boxes with no ledger record. A rule that is wrong or over-narrow therefore
|
|
390
|
+
* cannot hide an `over-ceiling` finding on a box the product recorded — the
|
|
391
|
+
* incident's own 23 findings survive any rule at all.
|
|
392
|
+
* 2. **Undecidable fails closed.** A row with no key attribution is `mine`, so
|
|
393
|
+
* an unattributable charge on a shared wallet is reported. Silence is never
|
|
394
|
+
* the answer to "I don't know."
|
|
395
|
+
* 3. **A box is claimed if ANY of its rows claims it.** The fold is
|
|
396
|
+
* `mine > undecidable > foreign`, which is the module's standing asymmetry:
|
|
397
|
+
* every derivation error pushes toward a false alarm, never toward a missed
|
|
398
|
+
* charge.
|
|
399
|
+
*/
|
|
400
|
+
/**
|
|
401
|
+
* Claim every settlement the platform stamped with one of these API keys.
|
|
402
|
+
*
|
|
403
|
+
* The shipped rule, because it is the only one built on a field the PLATFORM
|
|
404
|
+
* writes. Give each product its own platform key and this separates them
|
|
405
|
+
* exactly; give two products the same key and no consumer-side rule can tell
|
|
406
|
+
* them apart, because after settlement there is nothing left that differs — the
|
|
407
|
+
* fix then is a second key, not a cleverer predicate.
|
|
408
|
+
*
|
|
409
|
+
* A row with no `keyId` (a legacy row, or an export that drops the column) is
|
|
410
|
+
* `undecidable`, never `foreign`: the absence of an attribution is not evidence
|
|
411
|
+
* that the charge is someone else's.
|
|
412
|
+
*
|
|
413
|
+
* @param keyIds The product's own platform API key ids. Must be non-empty — a
|
|
414
|
+
* rule that owns nothing would classify every settlement as another product's
|
|
415
|
+
* and report a clean bill for an account nobody is checking.
|
|
416
|
+
*/
|
|
417
|
+
declare function ownedByBillingKeys(keyIds: readonly string[]): SpendOwnershipRule;
|
|
418
|
+
/**
|
|
419
|
+
* One box's verdict, folded over every row that settled against it.
|
|
420
|
+
*
|
|
421
|
+
* `mine` wins over `undecidable`, which wins over `foreign`: it takes one row
|
|
422
|
+
* attributable to this product to make the box this product's problem, and one
|
|
423
|
+
* unattributable row to stop the box being excluded. Both directions push
|
|
424
|
+
* toward reporting, which is the only direction that cannot lose money.
|
|
425
|
+
*
|
|
426
|
+
* Exported because a product auditing its own scoping wants the same answer the
|
|
427
|
+
* reconciler reached, not a re-derivation of it.
|
|
428
|
+
*/
|
|
429
|
+
declare function decideBoxOwnership(rule: SpendOwnershipRule, sandboxId: string, rows: readonly SettlementRow[]): SpendOwnershipVerdict;
|
|
430
|
+
|
|
243
431
|
/**
|
|
244
432
|
* Persistence seam for the expectation ledger — the product implements it over
|
|
245
433
|
* its own tables.
|
|
@@ -471,13 +659,30 @@ interface ReconcileSpendOptions {
|
|
|
471
659
|
/**
|
|
472
660
|
* Settled ledger rows, supplied by the product's own authenticated fetch.
|
|
473
661
|
*
|
|
474
|
-
*
|
|
475
|
-
*
|
|
476
|
-
*
|
|
662
|
+
* The fetch can only scope to a WALLET — `product: 'sandbox'` is the
|
|
663
|
+
* platform's service taxonomy, not this product's — so on an account running
|
|
664
|
+
* more than one of our products these rows carry the siblings' boxes too.
|
|
665
|
+
* {@link ReconcileSpendOptions.ownership} is what separates them.
|
|
477
666
|
*/
|
|
478
667
|
readonly rows: readonly SettlementRow[];
|
|
479
668
|
/** The product's expectation ledger. */
|
|
480
669
|
readonly store: SpendLedgerStorePort;
|
|
670
|
+
/**
|
|
671
|
+
* Which of those rows are THIS product's — see {@link SpendOwnershipRule} and
|
|
672
|
+
* the shipped `ownedByBillingKeys`.
|
|
673
|
+
*
|
|
674
|
+
* Omitting it is safe and changes nothing: the pass claims every box, which is
|
|
675
|
+
* the behaviour that shipped, and the direction that over-reports rather than
|
|
676
|
+
* under-reports. It is not silent about it — `report.ownership.declared` is
|
|
677
|
+
* `false`, `formatSpendReport` says so above the findings, and every
|
|
678
|
+
* `unknown-box` finding states on its face that a sibling product's box is
|
|
679
|
+
* indistinguishable from a charge that is not ours.
|
|
680
|
+
*
|
|
681
|
+
* Declaring it never weakens the ledger-backed checks: ownership is consulted
|
|
682
|
+
* ONLY for boxes with no expectation record, so `over-ceiling` on a recorded
|
|
683
|
+
* box fires whatever the rule says.
|
|
684
|
+
*/
|
|
685
|
+
readonly ownership?: SpendOwnershipRule;
|
|
481
686
|
/** Treated as "now". Default `Date.now()`. */
|
|
482
687
|
readonly asOf?: number;
|
|
483
688
|
/** Ceiling slack. Default {@link DEFAULT_CEILING_TOLERANCE_MS}. */
|
|
@@ -637,4 +842,4 @@ declare function formatSpendReport(report: SpendReport): string;
|
|
|
637
842
|
/** The report as a plain JSON value, for an alerting pipeline. */
|
|
638
843
|
declare function spendReportToJson(report: SpendReport): string;
|
|
639
844
|
|
|
640
|
-
export { type BilledDurationBasis, type BoxRateResolver, type CeilingBasis, type ComputeBudget, ComputeBudgetExceededError, type ComputeBudgetRefusal, type ComputeExpectedCeilingOptions, DEFAULT_CEILING_TOLERANCE_MS, type ExpectedCeiling, type InMemorySpendLedgerStore, type ObserveSandboxInput, type ObservedBalance, type ReconcileSpendOptions, SPEND_CHECKS, type SandboxSpendHooksOptions, type SandboxSpendSeam, type SettlementReference, type SettlementRow, type SpendBoxPatch, type SpendBoxRecord, type SpendCheckId, type SpendFinding, type SpendLedger, type SpendLedgerOptions, type SpendLedgerStorePort, type SpendProvisionObservation, type SpendReport, type VelocityOptions, assertComputeBudget, chargeNanoUsd, computeExpectedCeiling, createInMemorySpendLedgerStore, createSandboxSpendHooks, createSpendLedger, foldSpendBoxRecord, formatSpendReport, isCharge, parseSandboxGroupKey, parseSettlementReference, reconcileSpend, settlementSandboxId, spendReportToJson };
|
|
845
|
+
export { type BilledDurationBasis, type BoxRateResolver, type CeilingBasis, type ComputeBudget, ComputeBudgetExceededError, type ComputeBudgetRefusal, type ComputeExpectedCeilingOptions, DEFAULT_CEILING_TOLERANCE_MS, type ExpectedCeiling, type InMemorySpendLedgerStore, type ObserveSandboxInput, type ObservedBalance, type ReconcileSpendOptions, SPEND_CHECKS, type SandboxSpendHooksOptions, type SandboxSpendSeam, type SettlementReference, type SettlementRow, type SpendBoxPatch, type SpendBoxRecord, type SpendCheckId, type SpendFinding, type SpendLedger, type SpendLedgerOptions, type SpendLedgerStorePort, type SpendOwnershipCandidate, type SpendOwnershipRule, type SpendOwnershipSummary, type SpendOwnershipVerdict, type SpendProvisionObservation, type SpendReport, type VelocityOptions, assertComputeBudget, chargeNanoUsd, computeExpectedCeiling, createInMemorySpendLedgerStore, createSandboxSpendHooks, createSpendLedger, decideBoxOwnership, foldSpendBoxRecord, formatSpendReport, isCharge, ownedByBillingKeys, parseSandboxGroupKey, parseSettlementReference, reconcileSpend, settlementSandboxId, spendReportToJson };
|
package/dist/spend/index.js
CHANGED
|
@@ -3,14 +3,16 @@ import {
|
|
|
3
3
|
SPEND_CHECKS,
|
|
4
4
|
chargeNanoUsd,
|
|
5
5
|
computeExpectedCeiling,
|
|
6
|
+
decideBoxOwnership,
|
|
6
7
|
formatSpendReport,
|
|
7
8
|
isCharge,
|
|
9
|
+
ownedByBillingKeys,
|
|
8
10
|
parseSandboxGroupKey,
|
|
9
11
|
parseSettlementReference,
|
|
10
12
|
reconcileSpend,
|
|
11
13
|
settlementSandboxId,
|
|
12
14
|
spendReportToJson
|
|
13
|
-
} from "../chunk-
|
|
15
|
+
} from "../chunk-5LC2VXH5.js";
|
|
14
16
|
|
|
15
17
|
// src/spend/store.ts
|
|
16
18
|
function foldSpendBoxRecord(record, patch) {
|
|
@@ -184,9 +186,11 @@ export {
|
|
|
184
186
|
createInMemorySpendLedgerStore,
|
|
185
187
|
createSandboxSpendHooks,
|
|
186
188
|
createSpendLedger,
|
|
189
|
+
decideBoxOwnership,
|
|
187
190
|
foldSpendBoxRecord,
|
|
188
191
|
formatSpendReport,
|
|
189
192
|
isCharge,
|
|
193
|
+
ownedByBillingKeys,
|
|
190
194
|
parseSandboxGroupKey,
|
|
191
195
|
parseSettlementReference,
|
|
192
196
|
reconcileSpend,
|