tempo-sdk 0.0.66 → 0.0.69
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/assets/index.js +24 -2
- package/dist/assets/index.js.map +1 -1
- package/dist/astro.js +80 -21
- package/dist/astro.js.map +1 -1
- package/dist/{chunk-6W6UKDSY.js → chunk-6BSLP7P3.js} +3 -3
- package/dist/{chunk-6W6UKDSY.js.map → chunk-6BSLP7P3.js.map} +1 -1
- package/dist/{chunk-DELFOKU3.js → chunk-WTQQOLXM.js} +3 -3
- package/dist/{chunk-DELFOKU3.js.map → chunk-WTQQOLXM.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/nextjs/plugin.cjs +2 -2
- package/dist/nextjs/plugin.cjs.map +1 -1
- package/dist/nextjs/plugin.js +1 -1
- package/dist/nextjs-loader.cjs +2 -2
- package/dist/nextjs-loader.cjs.map +1 -1
- package/dist/nextjs.cjs +2 -2
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.js +1 -1
- package/package.json +2 -2
package/dist/assets/index.js
CHANGED
|
@@ -7,6 +7,11 @@ import {
|
|
|
7
7
|
UNRESOLVED_VALUE
|
|
8
8
|
} from "../chunk-DI2ZFAWL.js";
|
|
9
9
|
|
|
10
|
+
// assets/controls.ts
|
|
11
|
+
function normalizeAssetControl(control) {
|
|
12
|
+
return control && (control.type === "radio" || control.type === "inline-radio") ? { ...control, type: "select" } : control;
|
|
13
|
+
}
|
|
14
|
+
|
|
10
15
|
// assets/prop-overrides.ts
|
|
11
16
|
function applyPropOverrides(props, edits) {
|
|
12
17
|
const result = { ...props };
|
|
@@ -266,7 +271,14 @@ function getAssetConfig(component) {
|
|
|
266
271
|
}
|
|
267
272
|
var TEMPO_CONTROLS_CONFIG_PROPERTY = "__tempoControlsConfig";
|
|
268
273
|
function defineControls(component, controls) {
|
|
269
|
-
const registration = {
|
|
274
|
+
const registration = {
|
|
275
|
+
controls: Object.fromEntries(
|
|
276
|
+
Object.entries(controls).map(([name, control]) => [
|
|
277
|
+
name,
|
|
278
|
+
normalizeAssetControl(control)
|
|
279
|
+
])
|
|
280
|
+
)
|
|
281
|
+
};
|
|
270
282
|
let registrations;
|
|
271
283
|
try {
|
|
272
284
|
const previous = component[TEMPO_CONTROLS_CONFIG_PROPERTY];
|
|
@@ -293,7 +305,17 @@ function getComponentControls(component) {
|
|
|
293
305
|
return {
|
|
294
306
|
error: "Keep one controls declaration for this Astro component; remove the duplicate shared declaration."
|
|
295
307
|
};
|
|
296
|
-
return
|
|
308
|
+
return {
|
|
309
|
+
...astro,
|
|
310
|
+
...astro.controls && {
|
|
311
|
+
controls: Object.fromEntries(
|
|
312
|
+
Object.entries(astro.controls).map(([name, control]) => [
|
|
313
|
+
name,
|
|
314
|
+
normalizeAssetControl(control)
|
|
315
|
+
])
|
|
316
|
+
)
|
|
317
|
+
}
|
|
318
|
+
};
|
|
297
319
|
}
|
|
298
320
|
if (!registrations?.size) return {};
|
|
299
321
|
if (registrations.size > 1)
|
package/dist/assets/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../assets/prop-overrides.ts","../../assets/live-preview.tsx","../../assets/snapshot.ts","../../assets/index.ts"],"sourcesContent":["/** Internal, JSON-safe omission marker. Never emitted as a component prop. */\nexport const OMIT_ASSET_PROP = { __tempo_omit_prop__: true } as const;\n\nexport function applyPropOverrides<T>(\n props: Readonly<Record<string, T>>,\n edits?: Readonly<Record<string, T>>,\n): Record<string, T> {\n const result = { ...props };\n for (const [name, value] of Object.entries(edits ?? {})) {\n if (\n value &&\n typeof value === \"object\" &&\n Object.keys(value).length === 1 &&\n (value as Record<string, unknown>).__tempo_omit_prop__ === true\n ) {\n delete result[name];\n } else\n Object.defineProperty(result, name, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return result;\n}\n","import { applyPropOverrides } from \"./prop-overrides\";\nimport {\n Component,\n createElement,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ComponentType,\n type ReactNode,\n} from \"react\";\nimport {\n getAssetConfig,\n type AssetDefinitionVariant,\n} from \"./index\";\nimport { getAssetConfigSnapshot } from \"./snapshot\";\nimport { captureAssetPreview } from \"./preview-snapshot\";\n\nexport const ASSET_PREVIEW_MESSAGE = \"tempo:asset-live-preview\";\n\nexport type AssetLivePreviewUpdate = {\n variant: string | null;\n edits: Record<string, unknown>;\n};\n\nclass PreviewBoundary extends Component<\n {\n children: ReactNode;\n update: AssetLivePreviewUpdate;\n },\n { error: string | null; update: AssetLivePreviewUpdate | null }\n> {\n state = {\n error: null as string | null,\n update: null as AssetLivePreviewUpdate | null,\n };\n static getDerivedStateFromProps(\n props: { update: AssetLivePreviewUpdate },\n state: { update: AssetLivePreviewUpdate | null },\n ) {\n return props.update !== state.update\n ? { update: props.update, error: null }\n : null;\n }\n static getDerivedStateFromError(error: Error) {\n return { error: error.message };\n }\n render() {\n return this.state.error ? (\n <p role=\"alert\" style={{ padding: 12, fontSize: 12 }}>\n {this.state.error}\n </p>\n ) : (\n this.props.children\n );\n }\n}\n\n/** One mounted component, driven by its editor. No file writes or captures on\n * variant/prop changes. Imports and source updates remain owned by Vite. */\nexport function AssetLivePreview({\n component,\n sessionId,\n}: {\n component: ComponentType<any>;\n sessionId: string;\n}) {\n const [update, setUpdate] = useState<AssetLivePreviewUpdate>({\n variant: null,\n edits: {},\n });\n const peer = useRef<{ origin: string } | null>(null);\n const viewport = useRef<HTMLDivElement>(null);\n const contentRoot = useRef<HTMLDivElement>(null);\n const [fit, setFit] = useState({ width: 0, height: 0, scale: 1 });\n const boundary = useRef<PreviewBoundary>(null);\n const [captureRequest, setCaptureRequest] = useState<string | null>(null);\n const lastMetadata = useRef(\"\");\n useLayoutEffect(() => {\n const frame = viewport.current!;\n const content = contentRoot.current!;\n const measure = () => {\n // Measure layout dimensions, not the transformed preview. The same\n // 16px inset and no-upscaling rule apply to its cached screenshot.\n const width = content.offsetWidth;\n const height = content.offsetHeight;\n const scale = Math.min(\n 1,\n Math.max(0, frame.clientWidth - 32) / (width || 1),\n Math.max(0, frame.clientHeight - 32) / (height || 1),\n );\n setFit((previous) =>\n previous.width === width &&\n previous.height === height &&\n previous.scale === scale\n ? previous\n : { width, height, scale },\n );\n };\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(frame);\n observer.observe(content);\n return () => observer.disconnect();\n }, []);\n const publish = () => {\n if (!peer.current) return;\n const metadata = getAssetConfigSnapshot(component);\n const serialized = JSON.stringify(metadata);\n if (lastMetadata.current === serialized) return;\n lastMetadata.current = serialized;\n window.parent.postMessage(\n {\n type: ASSET_PREVIEW_MESSAGE,\n sessionId,\n kind: \"metadata\",\n metadata,\n captureVersion: 1,\n },\n peer.current.origin,\n );\n };\n const publishRef = useRef(publish);\n publishRef.current = publish;\n useEffect(() => {\n const receive = (event: MessageEvent) => {\n if (\n event.source !== window.parent ||\n event.data?.type !== ASSET_PREVIEW_MESSAGE ||\n event.data.sessionId !== sessionId\n )\n return;\n if (event.data.kind === \"connect\") {\n peer.current = { origin: event.origin === \"null\" ? \"*\" : event.origin };\n lastMetadata.current = \"\";\n publishRef.current();\n } else if (\n (event.data.kind === \"update\" || event.data.kind === \"capture\") &&\n peer.current\n ) {\n const next = event.data.update;\n if (\n next &&\n (next.variant === null || typeof next.variant === \"string\") &&\n next.edits &&\n typeof next.edits === \"object\" &&\n !Array.isArray(next.edits)\n ) {\n setUpdate(next);\n if (\n event.data.kind === \"capture\" &&\n typeof event.data.requestId === \"string\"\n )\n setCaptureRequest(event.data.requestId);\n }\n }\n };\n window.addEventListener(\"message\", receive);\n // The parent may have received iframe.load before this lazy storyboard mounted.\n window.parent.postMessage(\n { type: ASSET_PREVIEW_MESSAGE, sessionId, kind: \"ready\" },\n \"*\",\n );\n return () => window.removeEventListener(\"message\", receive);\n }, [sessionId]);\n useLayoutEffect(() => {\n if (!captureRequest || !peer.current) return;\n // Capture after React has committed the EXACT props from the request, even\n // when Insert follows the last keystroke before its update message arrived.\n const frame = requestAnimationFrame(() => {\n let snapshot = null;\n try {\n if (contentRoot.current && !boundary.current?.state.error)\n snapshot = captureAssetPreview(contentRoot.current);\n } catch {\n // Snapshotting is an optimization; an unusual DOM must not block Add.\n }\n window.parent.postMessage(\n {\n type: ASSET_PREVIEW_MESSAGE,\n sessionId,\n kind: \"captured\",\n requestId: captureRequest,\n snapshot,\n },\n peer.current!.origin,\n );\n setCaptureRequest(null);\n });\n return () => cancelAnimationFrame(frame);\n }, [captureRequest, update, sessionId]);\n // A hot update can change metadata without changing the component identity.\n useEffect(publish);\n const config = getAssetConfig(component);\n const variant = (\n update.variant &&\n Object.prototype.hasOwnProperty.call(config?.variants ?? {}, update.variant)\n ? config?.variants?.[update.variant]\n : undefined\n ) as AssetDefinitionVariant<Record<string, unknown>> | undefined;\n const render =\n variant && \"render\" in variant ? variant.render : undefined;\n const content =\n update.variant === null\n ? null\n : render\n ? createElement(render)\n : createElement(\n component,\n applyPropOverrides(variant?.props ?? {}, update.edits),\n );\n return (\n <div\n ref={viewport}\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n width: \"100%\",\n height: \"100%\",\n padding: 16,\n boxSizing: \"border-box\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n flexShrink: 0,\n width: fit.width * fit.scale,\n height: fit.height * fit.scale,\n }}\n >\n <div\n ref={contentRoot}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"max-content\",\n height: \"max-content\",\n transform: `scale(${fit.scale})`,\n transformOrigin: \"top left\",\n }}\n >\n <PreviewBoundary ref={boundary} update={update}>\n {content}\n </PreviewBoundary>\n </div>\n </div>\n </div>\n );\n}\n","import { getAssetConfig, getComponentControls } from \"./index\";\nimport { UNRESOLVED_VALUE, type StaticValue } from \"./types\";\n\n/** Browser-side metadata transport. Unsupported values stay visible; JSON must\n * never silently drop a function, JSX child, cyclic object, or undefined prop. */\nfunction snapshot(value: unknown): StaticValue {\n function copy(value: unknown, seen: Set<object>, depth: number): StaticValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n )\n return value;\n if (typeof value === \"number\")\n return Number.isFinite(value) ? value : UNRESOLVED_VALUE;\n if (!value || typeof value !== \"object\" || depth > 16 || seen.has(value))\n return UNRESOLVED_VALUE;\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n )\n return UNRESOLVED_VALUE;\n if (\"$$typeof\" in value) return UNRESOLVED_VALUE;\n const next = new Set(seen).add(value);\n if (Array.isArray(value))\n return value.map((item) => copy(item, next, depth + 1));\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n copy(child, next, depth + 1),\n ]),\n );\n }\n return copy(value, new Set(), 0);\n}\n\nexport function getComponentControlsSnapshot(component: unknown): StaticValue {\n return snapshot(getComponentControls(component));\n}\nexport function getAssetConfigSnapshot(component: unknown): StaticValue {\n return snapshot({\n asset: getAssetConfig(component),\n ...getComponentControls(component),\n });\n}\n","/**\n * tempo-sdk/assets — runtime authoring surface for asset declarations.\n *\n * `defineAsset(Component, { ... })` marks a component (or canvas component)\n * as a design asset: library membership, usage instructions, and named prop\n * variants. `defineControls` independently describes prop editors. Tempo\n * discovers assets statically and reads explicit controls from the running\n * component. Source analysis supplies prop types and portable JSX for insertion.\n *\n * This subpath must stay browser-safe (no node imports): user component\n * files import it from app code, unlike the root entry's Vite plugin.\n * See specs/asset-libraries.md §2.\n */\nimport type { ComponentProps, ComponentType, ReactNode } from \"react\";\nimport type { AstroComponent } from \"../canvas/astro-contract\";\nimport type { AssetComponentProps, AssetControls } from \"./controls\";\nexport { AssetLivePreview } from \"./live-preview\";\nexport type {\n AssetControlDefinition,\n AssetControls,\n AssetPropControl,\n} from \"./controls\";\n\n/** Property key `defineAsset` attaches its config under. Non-enumerable so it\n * never leaks into spreads or serialization of the component value. */\nexport const TEMPO_ASSET_CONFIG_PROPERTY = \"__tempoAssetConfig\";\n\nexport type AssetVariant<P> = {\n /** Must satisfy the component's prop types. Kept required for source\n * compatibility with the original public asset-reader contract. */\n props: P;\n};\n\nexport type AssetRenderVariant = {\n props?: never;\n render: () => ReactNode;\n};\n\nexport type AssetDefinitionVariant<P> =\n | (AssetVariant<P> & { render?: never })\n | AssetRenderVariant;\n\nexport type AssetVariants<P> = Record<string, AssetVariant<P>>;\n\nexport type AssetConfigBase = {\n /** What this asset is and when to reach for it — and when not (e.g. \"form\n * submits, CTAs — not navigation (use Link)\"). Shown on the asset detail\n * page and returned by the asset MCP tools. */\n usageInstructions?: string;\n /** Library names this asset belongs to. Arbitrary non-empty strings; a\n * library exists iff some asset names it. Unset/empty = library-less\n * (still an asset, still shown in the Assets tab). */\n libraries?: string[];\n};\n\n/**\n * `variants` is required exactly when the component has required props. This\n * preserves the public reader guarantees from the first published asset API.\n * `defineAsset` also accepts metadata-only and render-only declarations through\n * its additive authoring input below.\n */\nexport type AssetConfig<C extends ComponentType<any>> = AssetConfigBase &\n ({} extends ComponentProps<C>\n ? { variants?: AssetVariants<ComponentProps<C>> }\n : { variants: AssetVariants<ComponentProps<C>> });\n\nexport type AssetDefinitionConfig<C extends ComponentType<any>> =\n AssetConfigBase & {\n variants?: Record<string, AssetDefinitionVariant<ComponentProps<C>>>;\n };\n\ntype AssetTarget = ComponentType<any> | AstroComponent<any>;\ntype AssetTargetProps<C extends AssetTarget> =\n C extends ComponentType<any>\n ? ComponentProps<C>\n : C extends AstroComponent<infer Props>\n ? Props\n : never;\n\n/**\n * Declare a component or canvas as a design asset.\n *\n * Two supported shapes, both top-level statements. Prefer a declaration in a\n * canvas that curates the component — the\n * declaring canvas becomes the component's linked canvas:\n *\n * import { Button } from \"@/components/Button\";\n *\n * defineAsset(Button, {\n * usageInstructions: \"form submits, CTAs — not navigation (use Link)\",\n * variants: { Primary: { props: { label: \"Buy now\" } } },\n * });\n *\n * A legacy shape is the same statement in the file that defines the\n * component, placed after its definition — keeps working:\n *\n * export const Button = ({ label }: ButtonProps) => <button>{label}</button>;\n *\n * defineAsset(Button, {\n * libraries: [\"core\"],\n * variants: { Primary: { props: { label: \"Buy now\" } } },\n * });\n *\n * Returns void deliberately: `export default defineAsset(App, {...})` would\n * turn the export into a call expression and break React Fast Refresh's\n * component-only export analysis, so the wrapper form is a type error.\n */\nexport function defineAsset<C extends AssetTarget>(\n component: C,\n config: AssetConfigBase & {\n variants?: Record<\n string,\n C extends AstroComponent<any>\n ? AssetVariant<AssetTargetProps<C>>\n : AssetDefinitionVariant<AssetTargetProps<C>>\n >;\n },\n): void {\n try {\n // Re-runs on every hot update, re-attaching the current config —\n // configurable so the redefinition is legal.\n Object.defineProperty(component, TEMPO_ASSET_CONFIG_PROPERTY, {\n value: config,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n } catch {\n // Frozen or exotic component values must never crash the user's app.\n }\n}\n\n/** Loosely-typed read shape: callers of getAssetConfig don't know the\n * component's prop types. */\nexport type ReadAssetConfig = AssetConfigBase & {\n variants?: AssetVariants<Record<string, unknown>>;\n};\n\n/** Read a config previously attached by `defineAsset`, if any. */\nexport function getAssetConfig(\n component: unknown,\n): ReadAssetConfig | undefined {\n if (\n (typeof component !== \"function\" && typeof component !== \"object\") ||\n component === null\n ) {\n return undefined;\n }\n const config = (component as Record<string, unknown>)[\n TEMPO_ASSET_CONFIG_PROPERTY\n ];\n return config === undefined\n ? (config as undefined)\n : (config as ReadAssetConfig);\n}\n\nexport {\n getAssetConfigSnapshot,\n getComponentControlsSnapshot,\n} from \"./snapshot\";\n\nexport type ComponentControls<P> = AssetControls<P>;\nexport type ComponentControlsTarget = {\n filePath: string;\n name: string;\n exportName?: string;\n};\nexport const TEMPO_CONTROLS_CONFIG_PROPERTY = \"__tempoControlsConfig\";\n\ntype ControlsRegistration = {\n controls: Record<string, import(\"./controls\").AssetControlDefinition>;\n};\n\n/** Describe real prop editors once, independently of assets and libraries.\n * New components keep this call in their own file. Existing components may use\n * tempo/controls.ts to avoid editing app source. Both work across every canvas.\n * Legacy canvas declarations remain supported.\n * The returned cleanup is used by Tempo's development transform during HMR.\n */\nexport function defineControls<\n C extends AssetTarget,\n const Controls extends AssetControls<AssetTargetProps<NoInfer<C>>>,\n>(\n component: C,\n controls: Controls &\n Record<\n Exclude<\n keyof Controls,\n keyof AssetComponentProps<AssetTargetProps<NoInfer<C>>>\n >,\n never\n >,\n): () => void {\n const registration = { controls } as ControlsRegistration;\n let registrations: Set<ControlsRegistration>;\n try {\n const previous = (component as unknown as Record<string, unknown>)[\n TEMPO_CONTROLS_CONFIG_PROPERTY\n ] as Set<ControlsRegistration> | undefined;\n registrations = previous ?? new Set();\n registrations.add(registration);\n Object.defineProperty(component, TEMPO_CONTROLS_CONFIG_PROPERTY, {\n value: registrations,\n enumerable: false,\n configurable: true,\n });\n } catch {\n /* Frozen components still render; use a local wrapper to attach controls. */\n return () => {};\n }\n return () => registrations.delete(registration);\n}\n\nexport function getComponentControls(component: unknown): {\n controls?: Record<string, import(\"./controls\").AssetControlDefinition>;\n error?: string;\n} {\n if (\n !component ||\n (typeof component !== \"function\" && typeof component !== \"object\")\n )\n return {};\n const registrations = (component as Record<string, unknown>)[\n TEMPO_CONTROLS_CONFIG_PROPERTY\n ] as Set<ControlsRegistration> | undefined;\n const astro = (component as import(\"../canvas/astro-contract\").AstroComponent)\n .__tempoAstroControls;\n if (astro && (astro.controls || astro.error)) {\n if (registrations?.size && (!astro.shared || registrations.size > 1))\n return {\n error:\n \"Keep one controls declaration for this Astro component; remove the duplicate shared declaration.\",\n };\n return astro as ReturnType<typeof getComponentControls>;\n }\n if (!registrations?.size) return {};\n if (registrations.size > 1)\n return {\n error:\n \"Multiple defineControls declarations for this component. Keep one declaration in the component file or tempo/controls.ts; remove the duplicate.\",\n };\n return registrations.values().next().value ?? {};\n}\n"],"mappings":";;;;;;;;;;AAGO,SAAS,mBACd,OACA,OACmB;AACnB,QAAM,SAAS,EAAE,GAAG,MAAM;AAC1B,aAAW,CAAC,MAAM,KAAK,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Ac,OAAO,cAAc,YACzD,cAAc,MACd;AACA,WAAO;AAAA,EACT;AACA,QAAM,SAAU,UACd,2BACF;AACA,SAAO,WAAW,SACb,SACA;AACP;AAaO,IAAM,iCAAiC;AAYvC,SAAS,eAId,WACA,UAQY;AACZ,QAAM,eAAe,EAAE,SAAS;AAChC,MAAI;AACJ,MAAI;AACF,UAAM,WAAY,UAChB,8BACF;AACA,oBAAgB,YAAY,oBAAI,IAAI;AACpC,kBAAc,IAAI,YAAY;AAC9B,WAAO,eAAe,WAAW,gCAAgC;AAAA,MAC/D,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,cAAc;AAAA,IAChB,CAAC;AAAA,EACH,QAAQ;AAEN,WAAO,MAAM;AAAA,IAAC;AAAA,EAChB;AACA,SAAO,MAAM,cAAc,OAAO,YAAY;AAChD;AAEO,SAAS,qBAAqB,WAGnC;AACA,MACE,CAAC,aACA,OAAO,cAAc,cAAc,OAAO,cAAc;AAEzD,WAAO,CAAC;AACV,QAAM,gBAAiB,UACrB,8BACF;AACA,QAAM,QAAS,UACZ;AACH,MAAI,UAAU,MAAM,YAAY,MAAM,QAAQ;AAC5C,QAAI,eAAe,SAAS,CAAC,MAAM,UAAU,cAAc,OAAO;AAChE,aAAO;AAAA,QACL,OACE;AAAA,MACJ;AACF,WAAO;AAAA,EACT;AACA,MAAI,CAAC,eAAe,KAAM,QAAO,CAAC;AAClC,MAAI,cAAc,OAAO;AACvB,WAAO;AAAA,MACL,OACE;AAAA,IACJ;AACF,SAAO,cAAc,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC;AACjD;","names":["value","content","snapshot"]}
|
|
1
|
+
{"version":3,"sources":["../../assets/controls.ts","../../assets/prop-overrides.ts","../../assets/live-preview.tsx","../../assets/snapshot.ts","../../assets/index.ts"],"sourcesContent":["/** Browser-safe control definitions shared by authoring, parsing and the editor. */\nexport type AssetOption = string | number | boolean;\n\nexport type AssetControlDefinition =\n | false\n | { type: \"text\" | \"boolean\" | \"color\" | \"object\" | \"date\" }\n | { type: \"number\"; min?: number; max?: number; step?: number }\n | { type: \"range\"; min: number; max: number; step?: number }\n | {\n type:\n | \"select\"\n | \"radio\"\n | \"inline-radio\"\n | \"check\"\n | \"inline-check\"\n | \"multi-select\";\n options?: readonly AssetOption[];\n }\n | { type: \"file\"; accept?: string };\n\ntype Choices<T> = Extract<NonNullable<T>, AssetOption>;\ntype ObjectValue<T> = Exclude<Extract<NonNullable<T>, object>, Function>;\n\n/** A control must produce values the prop actually accepts. */\nexport type AssetPropControl<T> =\n | false\n | (string extends T ? { type: \"text\" | \"color\" } : never)\n | (boolean extends T ? { type: \"boolean\" } : never)\n | (number extends T\n ?\n | { type: \"number\"; min?: number; max?: number; step?: number }\n | { type: \"range\"; min: number; max: number; step?: number }\n | { type: \"date\" }\n : never)\n | ([Choices<T>] extends [never]\n ? never\n : {\n type: \"select\" | \"radio\" | \"inline-radio\";\n options?: readonly Choices<T>[];\n })\n | (NonNullable<T> extends readonly (infer E)[]\n ? {\n type: \"check\" | \"inline-check\" | \"multi-select\";\n options?: readonly Choices<E>[];\n }\n : never)\n | ([ObjectValue<T>] extends [never] ? never : { type: \"object\" })\n | (string[] extends T ? { type: \"file\"; accept?: string } : never);\n\n/** Index signatures do not establish that a particular named prop exists. */\nexport type AssetComponentProps<P> = {\n [K in keyof P as string extends K\n ? never\n : number extends K\n ? never\n : symbol extends K\n ? never\n : K extends \"key\" | \"ref\"\n ? never\n : K]: P[K];\n};\n\nexport type AssetControls<P> = {\n [K in keyof AssetComponentProps<P>]?: AssetPropControl<P[K]>;\n};\n\n/** Legacy radio declarations remain accepted, but are read as dropdowns. */\nexport function normalizeAssetControl(\n control: AssetControlDefinition,\n): AssetControlDefinition {\n return control &&\n (control.type === \"radio\" || control.type === \"inline-radio\")\n ? { ...control, type: \"select\" }\n : control;\n}\n\n/** Validate the literal configuration independently of the component contract. */\nexport function assetControlDefinitionError(value: unknown): string | null {\n if (value === false) return null;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return \"Use a control object with a type, or false\";\n }\n const control = value as Record<string, unknown>;\n const type = control.type;\n const fields: Record<string, readonly string[]> = {\n text: [],\n boolean: [],\n color: [],\n object: [],\n date: [],\n number: [\"min\", \"max\", \"step\"],\n range: [\"min\", \"max\", \"step\"],\n select: [\"options\"],\n radio: [\"options\"],\n \"inline-radio\": [\"options\"],\n check: [\"options\"],\n \"inline-check\": [\"options\"],\n \"multi-select\": [\"options\"],\n file: [\"accept\"],\n };\n if (\n typeof type !== \"string\" ||\n !Object.prototype.hasOwnProperty.call(fields, type)\n )\n return \"Unknown control type\";\n for (const key of Object.keys(control)) {\n if (key !== \"type\" && !fields[type]?.includes(key))\n return `Unsupported setting \"${key}\" for ${type}`;\n }\n for (const key of [\"min\", \"max\", \"step\"]) {\n if (\n key in control &&\n (typeof control[key] !== \"number\" || !Number.isFinite(control[key]))\n ) {\n return `${key} must be a finite number`;\n }\n }\n if (\n type === \"range\" &&\n (control.min === undefined || control.max === undefined)\n )\n return \"A range needs min and max\";\n if (\n typeof control.min === \"number\" &&\n typeof control.max === \"number\" &&\n control.min > control.max\n )\n return \"min must not exceed max\";\n if (typeof control.step === \"number\" && control.step <= 0)\n return \"step must be positive\";\n if (\n \"options\" in control &&\n (!Array.isArray(control.options) ||\n control.options.length === 0 ||\n control.options.some(\n (option) =>\n ![\"string\", \"number\", \"boolean\"].includes(typeof option) ||\n (typeof option === \"number\" && !Number.isFinite(option)),\n ))\n )\n return \"options must be a non-empty array of strings, numbers or booleans\";\n if (\"accept\" in control && typeof control.accept !== \"string\")\n return \"accept must be a string\";\n return null;\n}\n","/** Internal, JSON-safe omission marker. Never emitted as a component prop. */\nexport const OMIT_ASSET_PROP = { __tempo_omit_prop__: true } as const;\n\nexport function applyPropOverrides<T>(\n props: Readonly<Record<string, T>>,\n edits?: Readonly<Record<string, T>>,\n): Record<string, T> {\n const result = { ...props };\n for (const [name, value] of Object.entries(edits ?? {})) {\n if (\n value &&\n typeof value === \"object\" &&\n Object.keys(value).length === 1 &&\n (value as Record<string, unknown>).__tempo_omit_prop__ === true\n ) {\n delete result[name];\n } else\n Object.defineProperty(result, name, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return result;\n}\n","import { applyPropOverrides } from \"./prop-overrides\";\nimport {\n Component,\n createElement,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ComponentType,\n type ReactNode,\n} from \"react\";\nimport {\n getAssetConfig,\n type AssetDefinitionVariant,\n} from \"./index\";\nimport { getAssetConfigSnapshot } from \"./snapshot\";\nimport { captureAssetPreview } from \"./preview-snapshot\";\n\nexport const ASSET_PREVIEW_MESSAGE = \"tempo:asset-live-preview\";\n\nexport type AssetLivePreviewUpdate = {\n variant: string | null;\n edits: Record<string, unknown>;\n};\n\nclass PreviewBoundary extends Component<\n {\n children: ReactNode;\n update: AssetLivePreviewUpdate;\n },\n { error: string | null; update: AssetLivePreviewUpdate | null }\n> {\n state = {\n error: null as string | null,\n update: null as AssetLivePreviewUpdate | null,\n };\n static getDerivedStateFromProps(\n props: { update: AssetLivePreviewUpdate },\n state: { update: AssetLivePreviewUpdate | null },\n ) {\n return props.update !== state.update\n ? { update: props.update, error: null }\n : null;\n }\n static getDerivedStateFromError(error: Error) {\n return { error: error.message };\n }\n render() {\n return this.state.error ? (\n <p role=\"alert\" style={{ padding: 12, fontSize: 12 }}>\n {this.state.error}\n </p>\n ) : (\n this.props.children\n );\n }\n}\n\n/** One mounted component, driven by its editor. No file writes or captures on\n * variant/prop changes. Imports and source updates remain owned by Vite. */\nexport function AssetLivePreview({\n component,\n sessionId,\n}: {\n component: ComponentType<any>;\n sessionId: string;\n}) {\n const [update, setUpdate] = useState<AssetLivePreviewUpdate>({\n variant: null,\n edits: {},\n });\n const peer = useRef<{ origin: string } | null>(null);\n const viewport = useRef<HTMLDivElement>(null);\n const contentRoot = useRef<HTMLDivElement>(null);\n const [fit, setFit] = useState({ width: 0, height: 0, scale: 1 });\n const boundary = useRef<PreviewBoundary>(null);\n const [captureRequest, setCaptureRequest] = useState<string | null>(null);\n const lastMetadata = useRef(\"\");\n useLayoutEffect(() => {\n const frame = viewport.current!;\n const content = contentRoot.current!;\n const measure = () => {\n // Measure layout dimensions, not the transformed preview. The same\n // 16px inset and no-upscaling rule apply to its cached screenshot.\n const width = content.offsetWidth;\n const height = content.offsetHeight;\n const scale = Math.min(\n 1,\n Math.max(0, frame.clientWidth - 32) / (width || 1),\n Math.max(0, frame.clientHeight - 32) / (height || 1),\n );\n setFit((previous) =>\n previous.width === width &&\n previous.height === height &&\n previous.scale === scale\n ? previous\n : { width, height, scale },\n );\n };\n measure();\n const observer = new ResizeObserver(measure);\n observer.observe(frame);\n observer.observe(content);\n return () => observer.disconnect();\n }, []);\n const publish = () => {\n if (!peer.current) return;\n const metadata = getAssetConfigSnapshot(component);\n const serialized = JSON.stringify(metadata);\n if (lastMetadata.current === serialized) return;\n lastMetadata.current = serialized;\n window.parent.postMessage(\n {\n type: ASSET_PREVIEW_MESSAGE,\n sessionId,\n kind: \"metadata\",\n metadata,\n captureVersion: 1,\n },\n peer.current.origin,\n );\n };\n const publishRef = useRef(publish);\n publishRef.current = publish;\n useEffect(() => {\n const receive = (event: MessageEvent) => {\n if (\n event.source !== window.parent ||\n event.data?.type !== ASSET_PREVIEW_MESSAGE ||\n event.data.sessionId !== sessionId\n )\n return;\n if (event.data.kind === \"connect\") {\n peer.current = { origin: event.origin === \"null\" ? \"*\" : event.origin };\n lastMetadata.current = \"\";\n publishRef.current();\n } else if (\n (event.data.kind === \"update\" || event.data.kind === \"capture\") &&\n peer.current\n ) {\n const next = event.data.update;\n if (\n next &&\n (next.variant === null || typeof next.variant === \"string\") &&\n next.edits &&\n typeof next.edits === \"object\" &&\n !Array.isArray(next.edits)\n ) {\n setUpdate(next);\n if (\n event.data.kind === \"capture\" &&\n typeof event.data.requestId === \"string\"\n )\n setCaptureRequest(event.data.requestId);\n }\n }\n };\n window.addEventListener(\"message\", receive);\n // The parent may have received iframe.load before this lazy storyboard mounted.\n window.parent.postMessage(\n { type: ASSET_PREVIEW_MESSAGE, sessionId, kind: \"ready\" },\n \"*\",\n );\n return () => window.removeEventListener(\"message\", receive);\n }, [sessionId]);\n useLayoutEffect(() => {\n if (!captureRequest || !peer.current) return;\n // Capture after React has committed the EXACT props from the request, even\n // when Insert follows the last keystroke before its update message arrived.\n const frame = requestAnimationFrame(() => {\n let snapshot = null;\n try {\n if (contentRoot.current && !boundary.current?.state.error)\n snapshot = captureAssetPreview(contentRoot.current);\n } catch {\n // Snapshotting is an optimization; an unusual DOM must not block Add.\n }\n window.parent.postMessage(\n {\n type: ASSET_PREVIEW_MESSAGE,\n sessionId,\n kind: \"captured\",\n requestId: captureRequest,\n snapshot,\n },\n peer.current!.origin,\n );\n setCaptureRequest(null);\n });\n return () => cancelAnimationFrame(frame);\n }, [captureRequest, update, sessionId]);\n // A hot update can change metadata without changing the component identity.\n useEffect(publish);\n const config = getAssetConfig(component);\n const variant = (\n update.variant &&\n Object.prototype.hasOwnProperty.call(config?.variants ?? {}, update.variant)\n ? config?.variants?.[update.variant]\n : undefined\n ) as AssetDefinitionVariant<Record<string, unknown>> | undefined;\n const render =\n variant && \"render\" in variant ? variant.render : undefined;\n const content =\n update.variant === null\n ? null\n : render\n ? createElement(render)\n : createElement(\n component,\n applyPropOverrides(variant?.props ?? {}, update.edits),\n );\n return (\n <div\n ref={viewport}\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n overflow: \"hidden\",\n width: \"100%\",\n height: \"100%\",\n padding: 16,\n boxSizing: \"border-box\",\n }}\n >\n <div\n style={{\n position: \"relative\",\n flexShrink: 0,\n width: fit.width * fit.scale,\n height: fit.height * fit.scale,\n }}\n >\n <div\n ref={contentRoot}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"max-content\",\n height: \"max-content\",\n transform: `scale(${fit.scale})`,\n transformOrigin: \"top left\",\n }}\n >\n <PreviewBoundary ref={boundary} update={update}>\n {content}\n </PreviewBoundary>\n </div>\n </div>\n </div>\n );\n}\n","import { getAssetConfig, getComponentControls } from \"./index\";\nimport { UNRESOLVED_VALUE, type StaticValue } from \"./types\";\n\n/** Browser-side metadata transport. Unsupported values stay visible; JSON must\n * never silently drop a function, JSX child, cyclic object, or undefined prop. */\nfunction snapshot(value: unknown): StaticValue {\n function copy(value: unknown, seen: Set<object>, depth: number): StaticValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n )\n return value;\n if (typeof value === \"number\")\n return Number.isFinite(value) ? value : UNRESOLVED_VALUE;\n if (!value || typeof value !== \"object\" || depth > 16 || seen.has(value))\n return UNRESOLVED_VALUE;\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n )\n return UNRESOLVED_VALUE;\n if (\"$$typeof\" in value) return UNRESOLVED_VALUE;\n const next = new Set(seen).add(value);\n if (Array.isArray(value))\n return value.map((item) => copy(item, next, depth + 1));\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n copy(child, next, depth + 1),\n ]),\n );\n }\n return copy(value, new Set(), 0);\n}\n\nexport function getComponentControlsSnapshot(component: unknown): StaticValue {\n return snapshot(getComponentControls(component));\n}\nexport function getAssetConfigSnapshot(component: unknown): StaticValue {\n return snapshot({\n asset: getAssetConfig(component),\n ...getComponentControls(component),\n });\n}\n","/**\n * tempo-sdk/assets — runtime authoring surface for asset declarations.\n *\n * `defineAsset(Component, { ... })` marks a component (or canvas component)\n * as a design asset: library membership, usage instructions, and named prop\n * variants. `defineControls` independently describes prop editors. Tempo\n * discovers assets statically and reads explicit controls from the running\n * component. Source analysis supplies prop types and portable JSX for insertion.\n *\n * This subpath must stay browser-safe (no node imports): user component\n * files import it from app code, unlike the root entry's Vite plugin.\n * See specs/asset-libraries.md §2.\n */\nimport type { ComponentProps, ComponentType, ReactNode } from \"react\";\nimport type { AstroComponent } from \"../canvas/astro-contract\";\nimport {\n normalizeAssetControl,\n type AssetComponentProps,\n type AssetControls,\n type AssetControlDefinition,\n} from \"./controls\";\nexport { AssetLivePreview } from \"./live-preview\";\nexport type {\n AssetControlDefinition,\n AssetControls,\n AssetPropControl,\n} from \"./controls\";\n\n/** Property key `defineAsset` attaches its config under. Non-enumerable so it\n * never leaks into spreads or serialization of the component value. */\nexport const TEMPO_ASSET_CONFIG_PROPERTY = \"__tempoAssetConfig\";\n\nexport type AssetVariant<P> = {\n /** Must satisfy the component's prop types. Kept required for source\n * compatibility with the original public asset-reader contract. */\n props: P;\n};\n\nexport type AssetRenderVariant = {\n props?: never;\n render: () => ReactNode;\n};\n\nexport type AssetDefinitionVariant<P> =\n | (AssetVariant<P> & { render?: never })\n | AssetRenderVariant;\n\nexport type AssetVariants<P> = Record<string, AssetVariant<P>>;\n\nexport type AssetConfigBase = {\n /** What this asset is and when to reach for it — and when not (e.g. \"form\n * submits, CTAs — not navigation (use Link)\"). Shown on the asset detail\n * page and returned by the asset MCP tools. */\n usageInstructions?: string;\n /** Library names this asset belongs to. Arbitrary non-empty strings; a\n * library exists iff some asset names it. Unset/empty = library-less\n * (still an asset, still shown in the Assets tab). */\n libraries?: string[];\n};\n\n/**\n * `variants` is required exactly when the component has required props. This\n * preserves the public reader guarantees from the first published asset API.\n * `defineAsset` also accepts metadata-only and render-only declarations through\n * its additive authoring input below.\n */\nexport type AssetConfig<C extends ComponentType<any>> = AssetConfigBase &\n ({} extends ComponentProps<C>\n ? { variants?: AssetVariants<ComponentProps<C>> }\n : { variants: AssetVariants<ComponentProps<C>> });\n\nexport type AssetDefinitionConfig<C extends ComponentType<any>> =\n AssetConfigBase & {\n variants?: Record<string, AssetDefinitionVariant<ComponentProps<C>>>;\n };\n\ntype AssetTarget = ComponentType<any> | AstroComponent<any>;\ntype AssetTargetProps<C extends AssetTarget> =\n C extends ComponentType<any>\n ? ComponentProps<C>\n : C extends AstroComponent<infer Props>\n ? Props\n : never;\n\n/**\n * Declare a component or canvas as a design asset.\n *\n * Two supported shapes, both top-level statements. Prefer a declaration in a\n * canvas that curates the component — the\n * declaring canvas becomes the component's linked canvas:\n *\n * import { Button } from \"@/components/Button\";\n *\n * defineAsset(Button, {\n * usageInstructions: \"form submits, CTAs — not navigation (use Link)\",\n * variants: { Primary: { props: { label: \"Buy now\" } } },\n * });\n *\n * A legacy shape is the same statement in the file that defines the\n * component, placed after its definition — keeps working:\n *\n * export const Button = ({ label }: ButtonProps) => <button>{label}</button>;\n *\n * defineAsset(Button, {\n * libraries: [\"core\"],\n * variants: { Primary: { props: { label: \"Buy now\" } } },\n * });\n *\n * Returns void deliberately: `export default defineAsset(App, {...})` would\n * turn the export into a call expression and break React Fast Refresh's\n * component-only export analysis, so the wrapper form is a type error.\n */\nexport function defineAsset<C extends AssetTarget>(\n component: C,\n config: AssetConfigBase & {\n variants?: Record<\n string,\n C extends AstroComponent<any>\n ? AssetVariant<AssetTargetProps<C>>\n : AssetDefinitionVariant<AssetTargetProps<C>>\n >;\n },\n): void {\n try {\n // Re-runs on every hot update, re-attaching the current config —\n // configurable so the redefinition is legal.\n Object.defineProperty(component, TEMPO_ASSET_CONFIG_PROPERTY, {\n value: config,\n enumerable: false,\n configurable: true,\n writable: false,\n });\n } catch {\n // Frozen or exotic component values must never crash the user's app.\n }\n}\n\n/** Loosely-typed read shape: callers of getAssetConfig don't know the\n * component's prop types. */\nexport type ReadAssetConfig = AssetConfigBase & {\n variants?: AssetVariants<Record<string, unknown>>;\n};\n\n/** Read a config previously attached by `defineAsset`, if any. */\nexport function getAssetConfig(\n component: unknown,\n): ReadAssetConfig | undefined {\n if (\n (typeof component !== \"function\" && typeof component !== \"object\") ||\n component === null\n ) {\n return undefined;\n }\n const config = (component as Record<string, unknown>)[\n TEMPO_ASSET_CONFIG_PROPERTY\n ];\n return config === undefined\n ? (config as undefined)\n : (config as ReadAssetConfig);\n}\n\nexport {\n getAssetConfigSnapshot,\n getComponentControlsSnapshot,\n} from \"./snapshot\";\n\nexport type ComponentControls<P> = AssetControls<P>;\nexport type ComponentControlsTarget = {\n filePath: string;\n name: string;\n exportName?: string;\n};\nexport const TEMPO_CONTROLS_CONFIG_PROPERTY = \"__tempoControlsConfig\";\n\ntype ControlsRegistration = {\n controls: Record<string, import(\"./controls\").AssetControlDefinition>;\n};\n\n/** Describe real prop editors once, independently of assets and libraries.\n * New components keep this call in their own file. Existing components may use\n * tempo/controls.ts to avoid editing app source. Both work across every canvas.\n * Legacy canvas declarations remain supported.\n * The returned cleanup is used by Tempo's development transform during HMR.\n */\nexport function defineControls<\n C extends AssetTarget,\n const Controls extends AssetControls<AssetTargetProps<NoInfer<C>>>,\n>(\n component: C,\n controls: Controls &\n Record<\n Exclude<\n keyof Controls,\n keyof AssetComponentProps<AssetTargetProps<NoInfer<C>>>\n >,\n never\n >,\n): () => void {\n const registration: ControlsRegistration = {\n controls: Object.fromEntries(\n Object.entries(controls).map(([name, control]) => [\n name,\n normalizeAssetControl(control as AssetControlDefinition),\n ]),\n ),\n };\n let registrations: Set<ControlsRegistration>;\n try {\n const previous = (component as unknown as Record<string, unknown>)[\n TEMPO_CONTROLS_CONFIG_PROPERTY\n ] as Set<ControlsRegistration> | undefined;\n registrations = previous ?? new Set();\n registrations.add(registration);\n Object.defineProperty(component, TEMPO_CONTROLS_CONFIG_PROPERTY, {\n value: registrations,\n enumerable: false,\n configurable: true,\n });\n } catch {\n /* Frozen components still render; use a local wrapper to attach controls. */\n return () => {};\n }\n return () => registrations.delete(registration);\n}\n\nexport function getComponentControls(component: unknown): {\n controls?: Record<string, import(\"./controls\").AssetControlDefinition>;\n error?: string;\n} {\n if (\n !component ||\n (typeof component !== \"function\" && typeof component !== \"object\")\n )\n return {};\n const registrations = (component as Record<string, unknown>)[\n TEMPO_CONTROLS_CONFIG_PROPERTY\n ] as Set<ControlsRegistration> | undefined;\n const astro = (component as import(\"../canvas/astro-contract\").AstroComponent)\n .__tempoAstroControls;\n if (astro && (astro.controls || astro.error)) {\n if (registrations?.size && (!astro.shared || registrations.size > 1))\n return {\n error:\n \"Keep one controls declaration for this Astro component; remove the duplicate shared declaration.\",\n };\n return {\n ...astro,\n ...(astro.controls && {\n controls: Object.fromEntries(\n Object.entries(astro.controls).map(([name, control]) => [\n name,\n normalizeAssetControl(control as AssetControlDefinition),\n ]),\n ),\n }),\n } as ReturnType<typeof getComponentControls>;\n }\n if (!registrations?.size) return {};\n if (registrations.size > 1)\n return {\n error:\n \"Multiple defineControls declarations for this component. Keep one declaration in the component file or tempo/controls.ts; remove the duplicate.\",\n };\n return registrations.values().next().value ?? {};\n}\n"],"mappings":";;;;;;;;;;AAmEO,SAAS,sBACd,SACwB;AACxB,SAAO,YACJ,QAAQ,SAAS,WAAW,QAAQ,SAAS,kBAC5C,EAAE,GAAG,SAAS,MAAM,SAAS,IAC7B;AACN;;;ACvEO,SAAS,mBACd,OACA,OACmB;AACnB,QAAM,SAAS,EAAE,GAAG,MAAM;AAC1B,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,SAAS,CAAC,CAAC,GAAG;AACvD,QACE,SACA,OAAO,UAAU,YACjB,OAAO,KAAK,KAAK,EAAE,WAAW,KAC7B,MAAkC,wBAAwB,MAC3D;AACA,aAAO,OAAO,IAAI;AAAA,IACpB;AACE,aAAO,eAAe,QAAQ,MAAM;AAAA,QAClC;AAAA,QACA,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,UAAU;AAAA,MACZ,CAAC;AAAA,EACL;AACA,SAAO;AACT;;;ACxBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;;;ACLP,SAAS,SAAS,OAA6B;AAC7C,WAAS,KAAKA,QAAgB,MAAmB,OAA4B;AAC3E,QACEA,WAAU,QACV,OAAOA,WAAU,YACjB,OAAOA,WAAU;AAEjB,aAAOA;AACT,QAAI,OAAOA,WAAU;AACnB,aAAO,OAAO,SAASA,MAAK,IAAIA,SAAQ;AAC1C,QAAI,CAACA,UAAS,OAAO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,SAAO,MAAM,cAAc,OAAO,YAAY;AAChD;AAEO,SAAS,qBAAqB,WAGnC;AACA,MACE,CAAC,aACA,OAAO,cAAc,cAAc,OAAO,cAAc;AAEzD,WAAO,CAAC;AACV,QAAM,gBAAiB,UACrB,8BACF;AACA,QAAM,QAAS,UACZ;AACH,MAAI,UAAU,MAAM,YAAY,MAAM,QAAQ;AAC5C,QAAI,eAAe,SAAS,CAAC,MAAM,UAAU,cAAc,OAAO;AAChE,aAAO;AAAA,QACL,OACE;AAAA,MACJ;AACF,WAAO;AAAA,MACL,GAAG;AAAA,MACH,GAAI,MAAM,YAAY;AAAA,QACpB,UAAU,OAAO;AAAA,UACf,OAAO,QAAQ,MAAM,QAAQ,EAAE,IAAI,CAAC,CAAC,MAAM,OAAO,MAAM;AAAA,YACtD;AAAA,YACA,sBAAsB,OAAiC;AAAA,UACzD,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,MAAI,CAAC,eAAe,KAAM,QAAO,CAAC;AAClC,MAAI,cAAc,OAAO;AACvB,WAAO;AAAA,MACL,OACE;AAAA,IACJ;AACF,SAAO,cAAc,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC;AACjD;","names":["value","content","snapshot"]}
|
package/dist/astro.js
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
TEMPO_HOST_IDENTITY_ENDPOINT,
|
|
11
11
|
createTempoHostIdentity,
|
|
12
12
|
tempoVitePlugin
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-WTQQOLXM.js";
|
|
14
14
|
import "./chunk-F23JGM4U.js";
|
|
15
15
|
import "./chunk-H6OZIX2U.js";
|
|
16
16
|
import {
|
|
@@ -357,21 +357,75 @@ throw new Error(${JSON.stringify(error instanceof Error ? error.message : String
|
|
|
357
357
|
return routes;
|
|
358
358
|
}
|
|
359
359
|
function writeChanged(file, source) {
|
|
360
|
-
|
|
360
|
+
const exists = existsSync(file);
|
|
361
|
+
if (exists && readFileSync(file, "utf8") === source) return;
|
|
361
362
|
mkdirSync(dirname(file), { recursive: true });
|
|
362
363
|
writeFileSync(file, source);
|
|
364
|
+
return exists ? "updated" : "created";
|
|
365
|
+
}
|
|
366
|
+
function storyboardEntrypoint(registryFile) {
|
|
367
|
+
return String.raw`---
|
|
368
|
+
import { readFileSync } from "node:fs";
|
|
369
|
+
import { createComponent } from "astro/runtime/server/index.js";
|
|
370
|
+
const base = import.meta.env.BASE_URL.replace(/\/$/, "");
|
|
371
|
+
const pathname = Astro.url.pathname.slice(base.length).replace(/\/$/, "");
|
|
372
|
+
const routes = JSON.parse(readFileSync(${JSON.stringify(registryFile)}, "utf8"));
|
|
373
|
+
const route = routes.find((entry) => entry.path === pathname);
|
|
374
|
+
if (!route) return new Response("Astro storyboard not found", { status: 404 });
|
|
375
|
+
// Do not turn these into a glob or a static import map: unopened boards may
|
|
376
|
+
// contain broken imports, and their global CSS must never enter this document.
|
|
377
|
+
const { default: assets } = await import(/* @vite-ignore */ route.file + "?astroPropagatedAssets");
|
|
378
|
+
const { default: Page } = await assets.getMod();
|
|
379
|
+
const Preview = createComponent((result, props, slots) => {
|
|
380
|
+
// The generated document owns its <head>. It was loaded during frontmatter,
|
|
381
|
+
// after Astro computed the dispatch page's static head metadata.
|
|
382
|
+
result._metadata.headInTree = true;
|
|
383
|
+
result._metadata.routeHasPropagation = true;
|
|
384
|
+
for (const style of assets.collectedStyles) {
|
|
385
|
+
result.styles.add({ props: { "data-vite-dev-id": style.id }, children: style.content });
|
|
386
|
+
const src = style.id.startsWith("/@id/") ? style.id : "/@fs/" + style.id.replace(/^\//, "");
|
|
387
|
+
result.scripts.add({ props: { type: "module", src: base + src }, children: "" });
|
|
388
|
+
}
|
|
389
|
+
for (const href of assets.collectedLinks) {
|
|
390
|
+
result.links.add({ props: { rel: "stylesheet", href }, children: "" });
|
|
391
|
+
}
|
|
392
|
+
return Page(result, props, slots);
|
|
393
|
+
});
|
|
394
|
+
---
|
|
395
|
+
<Preview />`;
|
|
363
396
|
}
|
|
364
397
|
function createAstroStoryboardRegistry(root, canvasesRoot, generatedRoot, styles = []) {
|
|
365
398
|
const roots = Array.isArray(canvasesRoot) ? canvasesRoot : [canvasesRoot];
|
|
366
399
|
const routes = collectAstroStoryboards(root, roots, generatedRoot, styles);
|
|
367
400
|
let currentRoutes = routes;
|
|
368
401
|
const registryFile = join(generatedRoot, "routes.json");
|
|
369
|
-
const
|
|
370
|
-
|
|
402
|
+
const entrypoint = join(generatedRoot, "storyboards.astro");
|
|
403
|
+
const shape = (items) => JSON.stringify(
|
|
404
|
+
items.map(({ path, file }) => ({
|
|
405
|
+
path,
|
|
406
|
+
file: file.replaceAll("\\", "/")
|
|
407
|
+
}))
|
|
408
|
+
);
|
|
409
|
+
const unmodifiedNewFiles = /* @__PURE__ */ new Set();
|
|
410
|
+
const writeDocument = (route) => {
|
|
411
|
+
const change = writeChanged(route.file, route.source);
|
|
412
|
+
const file = route.file.replaceAll("\\", "/");
|
|
413
|
+
if (change === "created") unmodifiedNewFiles.add(file);
|
|
414
|
+
else if (change === "updated") unmodifiedNewFiles.delete(file);
|
|
415
|
+
return change;
|
|
416
|
+
};
|
|
417
|
+
for (const route of routes) writeDocument(route);
|
|
371
418
|
writeChanged(registryFile, shape(routes));
|
|
372
|
-
|
|
419
|
+
writeChanged(entrypoint, storyboardEntrypoint(registryFile));
|
|
373
420
|
const plugin = {
|
|
374
421
|
name: "tempo:astro-storyboards",
|
|
422
|
+
hotUpdate: {
|
|
423
|
+
order: "pre",
|
|
424
|
+
handler({ type, file, modules }) {
|
|
425
|
+
if (type === "create" && unmodifiedNewFiles.has(file))
|
|
426
|
+
return modules.filter((module) => module.file !== file);
|
|
427
|
+
}
|
|
428
|
+
},
|
|
375
429
|
configureServer(server) {
|
|
376
430
|
const changed = (file) => {
|
|
377
431
|
if (!file.endsWith(".canvas.tsx") || !roots.some((root2) => {
|
|
@@ -386,9 +440,15 @@ function createAstroStoryboardRegistry(root, canvasesRoot, generatedRoot, styles
|
|
|
386
440
|
generatedRoot,
|
|
387
441
|
styles
|
|
388
442
|
);
|
|
389
|
-
|
|
443
|
+
const updatedFiles = next.filter((route) => writeDocument(route) === "updated").map((route) => route.file);
|
|
444
|
+
const nextFiles = new Set(
|
|
445
|
+
next.map((route) => route.file.replaceAll("\\", "/"))
|
|
446
|
+
);
|
|
447
|
+
for (const file2 of unmodifiedNewFiles)
|
|
448
|
+
if (!nextFiles.has(file2)) unmodifiedNewFiles.delete(file2);
|
|
390
449
|
currentRoutes = next;
|
|
391
450
|
writeChanged(registryFile, shape(next));
|
|
451
|
+
for (const file2 of updatedFiles) server.watcher.emit("change", file2);
|
|
392
452
|
} catch (error) {
|
|
393
453
|
server.config.logger.error(String(error));
|
|
394
454
|
}
|
|
@@ -409,17 +469,14 @@ function createAstroStoryboardRegistry(root, canvasesRoot, generatedRoot, styles
|
|
|
409
469
|
});
|
|
410
470
|
};
|
|
411
471
|
server.ws.on("tempo:astro:revision-request", verifyRevision);
|
|
412
|
-
dispose = () => {
|
|
472
|
+
const dispose = () => {
|
|
413
473
|
server.ws.off("tempo:astro:revision-request", verifyRevision);
|
|
414
474
|
server.watcher.off("add", changed).off("change", changed).off("unlink", changed);
|
|
415
475
|
};
|
|
416
|
-
|
|
417
|
-
closeBundle() {
|
|
418
|
-
dispose?.();
|
|
419
|
-
dispose = void 0;
|
|
476
|
+
server.httpServer?.once("close", dispose);
|
|
420
477
|
}
|
|
421
478
|
};
|
|
422
|
-
return { routes, registryFile, plugin };
|
|
479
|
+
return { routes, registryFile, entrypoint, plugin };
|
|
423
480
|
}
|
|
424
481
|
|
|
425
482
|
// astro/project-context.ts
|
|
@@ -531,7 +588,6 @@ function tempoAstro(options = {}) {
|
|
|
531
588
|
updateConfig,
|
|
532
589
|
injectRoute,
|
|
533
590
|
createCodegenDir,
|
|
534
|
-
addWatchFile,
|
|
535
591
|
injectScript
|
|
536
592
|
}) {
|
|
537
593
|
if (command !== "dev" || !(options.enabled ?? Boolean(process.env.TEMPO)))
|
|
@@ -563,13 +619,11 @@ function tempoAstro(options = {}) {
|
|
|
563
619
|
generatedRoot,
|
|
564
620
|
options.styles?.map((file) => resolve3(appRoot, file)) ?? discoverAstroStyles(appRoot)
|
|
565
621
|
);
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
});
|
|
572
|
-
addWatchFile(registry.registryFile);
|
|
622
|
+
injectRoute({
|
|
623
|
+
pattern: "/__tempo/astro/[...storyboard]",
|
|
624
|
+
entrypoint: registry.entrypoint,
|
|
625
|
+
prerender: false
|
|
626
|
+
});
|
|
573
627
|
injectScript(
|
|
574
628
|
"head-inline",
|
|
575
629
|
`if(!document.querySelector('meta[name="tempo-project-root"]')){const m=document.createElement('meta');m.name='tempo-project-root';m.content=${JSON.stringify(root).replaceAll("<", "\\u003c")};document.head.append(m)}`
|
|
@@ -612,7 +666,12 @@ function tempoAstro(options = {}) {
|
|
|
612
666
|
vite: {
|
|
613
667
|
plugins: [
|
|
614
668
|
identity,
|
|
615
|
-
astroTailwindSources(root, [
|
|
669
|
+
astroTailwindSources(root, [
|
|
670
|
+
...canvasRoots,
|
|
671
|
+
// Request-time registry data contains paths, never utilities.
|
|
672
|
+
// Scanning it makes Tailwind reload pages on every board add.
|
|
673
|
+
resolve3(generatedRoot, "*.astro")
|
|
674
|
+
]),
|
|
616
675
|
...astroAnnotationPlugins(root, generatedRoot),
|
|
617
676
|
tempoVitePlugin({ root, enabled: true }),
|
|
618
677
|
registry.plugin
|