@uibot/runtime 0.18.1 → 0.20.0

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.
@@ -3,6 +3,7 @@ import type { CompiledUIBotSpec, GapReport } from "@uibot/contracts";
3
3
  import { type UIBotLiveRendererProps, type ReactRegistry } from "@uibot/renderer-react";
4
4
  import type { UIBotAppRuntimeAdapter, UIBotPageResolution } from "./live-runtime-adapter.js";
5
5
  export interface UIBotAppHostProps {
6
+ applyDesign?: boolean;
6
7
  spec: CompiledUIBotSpec;
7
8
  registry: ReactRegistry;
8
9
  adapter: UIBotAppRuntimeAdapter;
@@ -16,6 +17,7 @@ export interface UIBotAppHostProps {
16
17
  }>) => React.ReactNode;
17
18
  onResolution?: (resolution: UIBotPageResolution) => void;
18
19
  onMountError?: UIBotLiveRendererProps["onMountError"];
20
+ onMounted?: UIBotLiveRendererProps["onMounted"];
19
21
  }
20
22
  /**
21
23
  * Client-safe router/auth gate for live specs.
@@ -0,0 +1,5 @@
1
+ import type { AppDocument } from "@uibot/contracts";
2
+ /** Validate every referenced TSX module before adopting an application revision. No source is executed. */
3
+ export declare function verifyAppModules(document: AppDocument, installed: Readonly<Record<string, {
4
+ sourceHash: string;
5
+ }>>): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -10,10 +10,15 @@
10
10
  */
11
11
  export { createLiveRuntimeAdapter, UIBotPageAccessError, type CreateLiveAdapterOptions, type UIBotAppRuntimeAdapter, type UIBotAuthorizationContext, type UIBotNavigationRequest, type UIBotPageResolution, type UIBotPageTarget, } from "./live-runtime-adapter.js";
12
12
  export { UIBotAppHost, type UIBotAppHostProps } from "./app-host.js";
13
+ export { createSpecPreviewSession } from "./preview-session.js";
13
14
  export { bindUrlState, type UrlStateIO } from "./url-state.js";
14
15
  export { CREATION_DATA_WEB_PROTOCOL, CREATION_DATA_WEB_V2_PROTOCOL, CREATION_DATA_WRITE_PROTOCOL, CreationDataPortRejection, createCreationDataWebShimSource, dispatchCreationData, } from "./creation-data.js";
15
16
  export type { CreationDataAuthorizeEntity, CreationDataCreateMetadata, CreationDataErrorCode, CreationDataFailure, CreationDataHost, CreationDataGenericHost, CreationDataJson, CreationDataMutationMetadata, CreationDataOperation, CreationDataPort, CreationDataRecord, CreationDataRequest, CreationDataResult, CreationDataSuccess, CreationDataWriteProtocol, CreationDataWebClient, CreationDataWebHost, CreationDataWebPort, CreationDataWebRequest, CreationDataWebRow, CreationDataWebV2Client, CreationDataWebV2Host, CreationDataWebV2Port, CreationDataWebV2Request, CreationDataWebShimOptions, } from "./creation-data.js";
16
17
  export { UIBotDiagnostics } from "./diagnostics.js";
18
+ export * from "./linked-spec.js";
17
19
  export { UIBotLiveRenderer, UIBotRenderer } from "@uibot/renderer-react";
18
20
  export type { UIBotRuntimeAdapter, UIBotLiveRendererProps, UIBotRendererProps, } from "@uibot/renderer-react";
19
21
  export { assembleInstalledUIBotLibrary, InstalledUIBotLibraryError, type InstalledUIBotLibrary, type InstalledUIBotLibraryInput, type InstalledUIBotTemplate, } from "./installed-library.js";
22
+ export * from "./linked-app.js";
23
+ export * from "./published-app.js";
24
+ export * from "./app-modules.js";
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import{createEngine as q,createLifecycleController as H}from"@uibot/engine";function L(e,t){if(t.enum&&!t.enum.includes(e))return t.default??"";if(typeof t.default==="number"){let n=Number(e);return Number.isFinite(n)?n:t.default}if(typeof t.default==="boolean"){if(e==="true")return!0;if(e==="false")return!1;return t.default}return e}function M(e,t){let n=e;if(t.enum&&(typeof n!=="string"||!t.enum.includes(n)))n=t.default;if(n===void 0||n===null||n==="")return null;if(t.default!==void 0&&Object.is(n,t.default))return null;if(typeof n==="string"||typeof n==="number"||typeof n==="boolean")return String(n);return null}function x(e,t,n){let i=new URLSearchParams(n.read()),l=!1;for(let[a,c]of Object.entries(t)){let u=M(e.get(a),c),r=i.get(c.param);if(u===null){if(r!==null)i.delete(c.param),l=!0}else if(r!==u)i.set(c.param,u),l=!0}if(l)n.write(i,{replace:!0})}function D(e,t,n){let i=n.read(),l={};for(let[c,u]of Object.entries(t)){let r=i.get(u.param);if(r===null)continue;l[c]=L(r,u)}if(Object.keys(l).length>0)e.setMany(l);let a=e.onWrite((c)=>{let u=new Set(Object.keys(t));if(!c.some((r)=>u.has(r.split(".")[0]??r)))return;x(e,t,n)});return x(e,t,n),a}var U=new WeakSet;function z(e,t){if(U.has(e))return;U.add(e),e.onWrite(()=>{for(let n of t)n()})}function G(e){let{spec:t}=e,n=t.pages[0],i=e.engine??q(n?.state??{});for(let r of t.connections??[])i.connections.registerConnection(r);for(let r of e.drivers??[])i.connections.registerDriver(r.type,r);if(e.resolveSecret)i.connections.setSecretResolver(e.resolveSecret);let l=new Set;z(i.store,l);let a=[];if(e.urlState){let r={};for(let s of t.pages)Object.assign(r,s.urlState);if(Object.keys(r).length>0)a.push(D(i.store,r,e.urlState))}let c=i.bus.on("navigate",(r)=>{if(!e.navigate||!r||typeof r!=="object")return;let s=r;if(typeof s.destination!=="string")return;let o={destination:s.destination,target:s.target==="_blank"?"_blank":"_self"};try{Promise.resolve(e.navigate(o)).catch(()=>{e.onNavigationError?.(o)})}catch{e.onNavigationError?.(o)}}),u=async(r={})=>{let s=r.pagePath?E(r.pagePath):void 0,o=t.pages.find((p)=>{if(r.pageId&&p.id!==r.pageId)return!1;if(s&&E(p.path)!==s)return!1;return Boolean(r.pageId||s)})??(!r.pageId&&!s?n:void 0);if(!o)return{status:"not-found",...r.pageId?{pageId:r.pageId}:{},...s?{pagePath:s}:{}};let d;try{d=e.authorize?await e.authorize(o,{user:i.session.getUser()}):!o.auth?.role||i.session.hasRole(o.auth.role)}catch{return{status:"error",message:"Page access check failed"}}if(!d)return{status:"unauthorized",pageId:o.id,pagePath:o.path,...o.auth?.redirect?{redirect:o.auth.redirect}:{}};return{status:"ready",pageId:o.id,pagePath:o.path}};return{resolvePage:u,snapshot(){return i.store.view()},async dispatch(r,s){await i.runner.run(r,s)},subscribeAny(r){return l.add(r),()=>{l.delete(r)}},async mountPage(r){let s=await u({pageId:r});if(s.status!=="ready")throw new I(r,s);let o=t.pages.find((p)=>p.id===s.pageId);if(!o)throw new I(r,{status:"not-found",pageId:r});let d=H({store:i.store,session:i.session,...o?.computed?{computed:o.computed}:{},...o?.lifecycle?.onMount?{onMount:o.lifecycle.onMount}:{},...o?.lifecycle?.onUnmount?{onUnmount:o.lifecycle.onUnmount}:{},...o?.lifecycle?.onStateChange?{onStateChange:o.lifecycle.onStateChange}:{},runChain:(p)=>i.runner.run(p)});try{await d.mount()}catch(p){if(typeof console<"u")console.warn(`[live-runtime] page "${r}" onMount failed; rendering from snapshot`,p)}return()=>{d.dispose()}},dispose(){for(let r of a)r();c(),l.clear()}}}function E(e){let t=e.split("#",1)[0]??e;return(t.split("?",1)[0]??t)||"/"}class I extends Error{resolution;constructor(e,t){super(t.status==="unauthorized"?`Page "${e}" is not authorized`:`Page "${e}" is unavailable`);this.resolution=t;this.name="UIBotPageAccessError"}}import C from"react";import{UIBotLiveRenderer as J,UIBotMountError as F}from"@uibot/renderer-react";import{jsxDEV as R,Fragment as P}from"react/jsx-dev-runtime";function K(e){let{spec:t,registry:n,adapter:i,pageId:l,pagePath:a,gaps:c=[],loading:u=null,fallback:r,onResolution:s,onMountError:o}=e,d=c.length>0,p=C.useRef(o);p.current=o,C.useEffect(()=>{if(!d)return;let b=c[0];p.current?.(new F("compile",Error(b?.context??`${c.length} compile gaps`),b?.elementKey))},[d,c]);let y=`${l??""}\x00${a??""}`,[m,V]=C.useState(null),S=C.useRef(s);if(S.current=s,C.useEffect(()=>{let b=!0,j={...l?{pageId:l}:{},...a?{pagePath:a}:{}};return i.resolvePage(j).then((A)=>{if(!b)return;V({key:y,resolution:A}),S.current?.(A)}),()=>{b=!1}},[i,l,a,y]),d)return R(P,{children:r?.({status:"error",message:`${c.length} compile gaps`})??null},void 0,!1,void 0,this);if(!m||m.key!==y)return R(P,{children:u},void 0,!1,void 0,this);if(m.resolution.status!=="ready")return R(P,{children:r?.(m.resolution)??null},void 0,!1,void 0,this);return R(J,{spec:t,registry:n,adapter:i,pageId:m.resolution.pageId,...o?{onMountError:o}:{}},void 0,!1,void 0,this)}import{CREATION_DATA_WEB_PROTOCOL as O,CREATION_DATA_WEB_V2_PROTOCOL as W,CREATION_DATA_WEB_MAX_DEPTH as X,CREATION_DATA_WEB_MAX_TEXT_BYTES as Z,CREATION_DATA_WEB_MAX_VALUES as Y,CREATION_DATA_WRITE_PROTOCOL as k,CreationDataPortRejection as Q,readCreationDataJson as ee,readCreationDataWebJson as te,readCreationDataWebResult as re,validateCreationDataMessage as oe}from"@uibot/contracts";import{CREATION_DATA_WEB_PROTOCOL as fe,CREATION_DATA_WEB_V2_PROTOCOL as me,CREATION_DATA_WRITE_PROTOCOL as ge,CreationDataPortRejection as ye}from"@uibot/contracts";var ae="Entity is not allowed.",h="Data port failed.",w="Creation data host is incomplete.",B="Data port returned a non-JSON result.",ne="Web data request exceeds JSON limits.",ie="Data port rejected the operation.",T="The original data write outcome is unknown; reconcile it before another attempt.";function f(e,t){return{ok:!1,code:e,message:t}}function se(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.list==="function"&&typeof t.get==="function"&&typeof t.create==="function"&&typeof t.update==="function"&&typeof t.remove==="function"}function N(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.writeProtocol===k&&typeof t.list==="function"&&typeof t.get==="function"&&typeof t.create==="function"&&typeof t.update==="function"}function le(e){return N(e)&&typeof e.remove==="function"}function ue(e,t){switch(t.op){case"list":return t.filter===void 0?e.list(t.entity):e.list(t.entity,t.filter);case"get":return e.get(t.entity,t.id);case"create":return e.create(t.entity,t.record,{operationId:t.operationId});case"update":return e.update(t.entity,t.id,t.patch,{operationId:t.operationId,expectedVersion:t.expectedVersion});case"remove":if(!("remove"in e)||typeof e.remove!=="function")throw Error("Creation data remove port is missing");return e.remove(t.entity,t.id,{operationId:t.operationId,expectedVersion:t.expectedVersion})}}function _(e){return e.op==="create"||e.op==="update"||e.op==="remove"}function ce(e){let t=e.publicMessage;if(typeof t!=="string"||t.trim()==="")return ie;return t}async function de(e,t){try{let n=typeof t==="object"&&t!==null?t.webProtocol:void 0,i=n===O,l=n===W,a=i||l,c=a?te(e):null;if(c&&!c.ok)return f("invalid-request",ne);let u=oe(c?.ok?c.value:e);if(!u.ok)return u;if(typeof t!=="object"||t===null||typeof t.authorizeEntity!=="function"||!(l?le(t.dataPort):i?N(t.dataPort):se(t.dataPort)))return f("invalid-host",w);if(t.webProtocol!==void 0&&!a)return f("invalid-host",w);let r=l||i&&u.request.op!=="remove"?u.request:null;if(i&&!r)return f("unknown-op","The Web data bridge does not support removal.");let s;try{s=await t.authorizeEntity(u.request.entity)}catch{return f("host-failed",h)}if(s===!1)return f("entity-not-allowed",ae);if(s!==!0)return f("host-failed",h);if(_(u.request)&&t.dataPort.writeProtocol!==k)return f("invalid-host",w);try{let o=await ue(t.dataPort,u.request);if(r){let p=re(r.op,o);if(!p.ok)return _(u.request)?f("unknown",T):f("invalid-result",B);return{ok:!0,data:p.data}}let d=ee(o);if(!d.ok)return f("invalid-result",B);return{ok:!0,data:d.value}}catch(o){if(a&&_(u.request))return f("unknown",T);if(a)return f("host-failed",h);if(o instanceof Q)return f("host-rejected",ce(o));return f("host-failed",h)}}catch{return f("host-failed",h)}}function pe(e){let t=e.protocol??O,n=/^[A-Za-z0-9_-]{16,128}$/,i=/^[A-Za-z0-9_-]{1,128}$/,l=/^__[A-Za-z][A-Za-z0-9_]{0,62}$/;if(!n.test(e.previewToken)||!i.test(e.requestSource)||!i.test(e.responseSource)||![O,W].includes(t)||e.compatibilityGlobalName!==void 0&&(!l.test(e.compatibilityGlobalName)||["__uibotData","__uibotDataWebV1Shim","__proto__"].includes(e.compatibilityGlobalName)))throw Error("Invalid creation data Web bridge configuration");let a=JSON.stringify(e.requestSource),c=JSON.stringify(e.responseSource),u=JSON.stringify(e.previewToken),r=JSON.stringify(e.compatibilityGlobalName??null),s=JSON.stringify(t);return`(function(){
2
- var seq = 0, requestSource = ${a}, responseSource = ${c};
1
+ import{createEngine as J,createLifecycleController as F}from"@uibot/engine";function z(e,t){if(t.enum&&!t.enum.includes(e))return t.default??"";if(typeof t.default==="number"){let a=Number(e);return Number.isFinite(a)?a:t.default}if(typeof t.default==="boolean"){if(e==="true")return!0;if(e==="false")return!1;return t.default}return e}function G(e,t){let a=e;if(t.enum&&(typeof a!=="string"||!t.enum.includes(a)))a=t.default;if(a===void 0||a===null||a==="")return null;if(t.default!==void 0&&Object.is(a,t.default))return null;if(typeof a==="string"||typeof a==="number"||typeof a==="boolean")return String(a);return null}function B(e,t,a){let o=new URLSearchParams(a.read()),i=!1;for(let[s,d]of Object.entries(t)){let u=G(e.get(s),d),r=o.get(d.param);if(u===null){if(r!==null)o.delete(d.param),i=!0}else if(r!==u)o.set(d.param,u),i=!0}if(i)a.write(o,{replace:!0})}function _(e,t,a){let o=a.read(),i={};for(let[d,u]of Object.entries(t)){let r=o.get(u.param);if(r===null)continue;i[d]=z(r,u)}if(Object.keys(i).length>0)e.setMany(i);let s=e.onWrite((d)=>{let u=new Set(Object.keys(t));if(!d.some((r)=>u.has(r.split(".")[0]??r)))return;B(e,t,a)});return B(e,t,a),s}var L=new WeakSet;function K(e,t){if(L.has(e))return;L.add(e),e.onWrite(()=>{for(let a of t)a()})}function k(e){let{spec:t}=e,a=t.pages[0],o=e.engine??J(a?.state??{});for(let r of t.connections??[])o.connections.registerConnection(r);for(let r of e.drivers??[])o.connections.registerDriver(r.type,r);if(e.resolveSecret)o.connections.setSecretResolver(e.resolveSecret);let i=new Set;K(o.store,i);let s=[];if(e.urlState){let r={};for(let c of t.pages)Object.assign(r,c.urlState);if(Object.keys(r).length>0)s.push(_(o.store,r,e.urlState))}let d=o.bus.on("navigate",(r)=>{if(!e.navigate||!r||typeof r!=="object")return;let c=r;if(typeof c.destination!=="string")return;let n={destination:c.destination,target:c.target==="_blank"?"_blank":"_self"};try{Promise.resolve(e.navigate(n)).catch(()=>{e.onNavigationError?.(n)})}catch{e.onNavigationError?.(n)}}),u=async(r={})=>{let c=r.pagePath?W(r.pagePath):void 0,n=t.pages.find((l)=>{if(r.pageId&&l.id!==r.pageId)return!1;if(c&&W(l.path)!==c)return!1;return Boolean(r.pageId||c)})??(!r.pageId&&!c?a:void 0);if(!n)return{status:"not-found",...r.pageId?{pageId:r.pageId}:{},...c?{pagePath:c}:{}};let p;try{p=e.authorize?await e.authorize(n,{user:o.session.getUser()}):!n.auth?.role||o.session.hasRole(n.auth.role)}catch{return{status:"error",message:"Page access check failed"}}if(!p)return{status:"unauthorized",pageId:n.id,pagePath:n.path,...n.auth?.redirect?{redirect:n.auth.redirect}:{}};return{status:"ready",pageId:n.id,pagePath:n.path}};return{resolvePage:u,snapshot(){return o.store.view()},async dispatch(r,c){await o.runner.run(r,c)},subscribeAny(r){return i.add(r),()=>{i.delete(r)}},async mountPage(r){let c=await u({pageId:r});if(c.status!=="ready")throw new A(r,c);let n=t.pages.find((l)=>l.id===c.pageId);if(!n)throw new A(r,{status:"not-found",pageId:r});let p=F({store:o.store,session:o.session,...n?.computed?{computed:n.computed}:{},...n?.lifecycle?.onMount?{onMount:n.lifecycle.onMount}:{},...n?.lifecycle?.onUnmount?{onUnmount:n.lifecycle.onUnmount}:{},...n?.lifecycle?.onStateChange?{onStateChange:n.lifecycle.onStateChange}:{},runChain:(l)=>o.runner.run(l)});try{await p.mount()}catch(l){if(typeof console<"u")console.warn(`[live-runtime] page "${r}" onMount failed; rendering from snapshot`,l)}return()=>{p.dispose()}},dispose(){for(let r of s)r();d(),i.clear()}}}function W(e){let t=e.split("#",1)[0]??e;return(t.split("?",1)[0]??t)||"/"}class A extends Error{resolution;constructor(e,t){super(t.status==="unauthorized"?`Page "${e}" is not authorized`:`Page "${e}" is unavailable`);this.resolution=t;this.name="UIBotPageAccessError"}}import I from"react";import{UIBotLiveRenderer as X,UIBotMountError as Z}from"@uibot/renderer-react";import{jsx as x,Fragment as O}from"react/jsx-runtime";function Y(e){let{spec:t,registry:a,adapter:o,pageId:i,pagePath:s,gaps:d=[],loading:u=null,fallback:r,onResolution:c,onMountError:n}=e,p=d.length>0,l=I.useRef(n);l.current=n,I.useEffect(()=>{if(!p)return;let h=d[0];l.current?.(new Z("compile",Error(h?.context??`${d.length} compile gaps`),h?.elementKey))},[p,d]);let v=`${i??""}\x00${s??""}`,[g,b]=I.useState(null),m=I.useRef(c);if(m.current=c,I.useEffect(()=>{let h=!0,P={...i?{pageId:i}:{},...s?{pagePath:s}:{}};return o.resolvePage(P).then((D)=>{if(!h)return;b({key:v,resolution:D}),m.current?.(D)}),()=>{h=!1}},[o,i,s,v]),p)return x(O,{children:r?.({status:"error",message:`${d.length} compile gaps`})??null});if(!g||g.key!==v)return x(O,{children:u});if(g.resolution.status!=="ready")return x(O,{children:r?.(g.resolution)??null});return x(X,{...e.applyDesign?{applyDesign:!0}:{},spec:t,registry:a,adapter:o,pageId:g.resolution.pageId,...n?{onMountError:n}:{},...e.onMounted?{onMounted:e.onMounted}:{}})}function Q(e){let t=new Map;if(new Set(e.spec.pages.map((a)=>a.path)).size!==e.spec.pages.length)throw Error("Duplicate preview page path");for(let a of e.spec.pages)t.set(a.path,k({...e,spec:{...e.spec,pages:[a,...e.spec.pages.filter((o)=>o!==a)]}}));return{adapters:t,dispose(){for(let a of t.values())a.dispose();t.clear()}}}import{CREATION_DATA_WEB_PROTOCOL as E,CREATION_DATA_WEB_V2_PROTOCOL as V,CREATION_DATA_WEB_MAX_DEPTH as ee,CREATION_DATA_WEB_MAX_TEXT_BYTES as te,CREATION_DATA_WEB_MAX_VALUES as re,CREATION_DATA_WRITE_PROTOCOL as M,CreationDataPortRejection as ne,readCreationDataJson as ae,readCreationDataWebJson as oe,readCreationDataWebResult as ie,validateCreationDataMessage as se}from"@uibot/contracts";import{CREATION_DATA_WEB_PROTOCOL as ve,CREATION_DATA_WEB_V2_PROTOCOL as be,CREATION_DATA_WRITE_PROTOCOL as he,CreationDataPortRejection as Se}from"@uibot/contracts";var ce="Entity is not allowed.",R="Data port failed.",T="Creation data host is incomplete.",N="Data port returned a non-JSON result.",ue="Web data request exceeds JSON limits.",de="Data port rejected the operation.",j="The original data write outcome is unknown; reconcile it before another attempt.";function y(e,t){return{ok:!1,code:e,message:t}}function le(e){if(typeof e!=="object"||e===null)return!1;let t=e;return typeof t.list==="function"&&typeof t.get==="function"&&typeof t.create==="function"&&typeof t.update==="function"&&typeof t.remove==="function"}function q(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.writeProtocol===M&&typeof t.list==="function"&&typeof t.get==="function"&&typeof t.create==="function"&&typeof t.update==="function"}function pe(e){return q(e)&&typeof e.remove==="function"}function fe(e,t){switch(t.op){case"list":return t.filter===void 0?e.list(t.entity):e.list(t.entity,t.filter);case"get":return e.get(t.entity,t.id);case"create":return e.create(t.entity,t.record,{operationId:t.operationId});case"update":return e.update(t.entity,t.id,t.patch,{operationId:t.operationId,expectedVersion:t.expectedVersion});case"remove":if(!("remove"in e)||typeof e.remove!=="function")throw Error("Creation data remove port is missing");return e.remove(t.entity,t.id,{operationId:t.operationId,expectedVersion:t.expectedVersion})}}function U(e){return e.op==="create"||e.op==="update"||e.op==="remove"}function me(e){let t=e.publicMessage;if(typeof t!=="string"||t.trim()==="")return de;return t}async function ye(e,t){try{let a=typeof t==="object"&&t!==null?t.webProtocol:void 0,o=a===E,i=a===V,s=o||i,d=s?oe(e):null;if(d&&!d.ok)return y("invalid-request",ue);let u=se(d?.ok?d.value:e);if(!u.ok)return u;if(typeof t!=="object"||t===null||typeof t.authorizeEntity!=="function"||!(i?pe(t.dataPort):o?q(t.dataPort):le(t.dataPort)))return y("invalid-host",T);if(t.webProtocol!==void 0&&!s)return y("invalid-host",T);let r=i||o&&u.request.op!=="remove"?u.request:null;if(o&&!r)return y("unknown-op","The Web data bridge does not support removal.");let c;try{c=await t.authorizeEntity(u.request.entity)}catch{return y("host-failed",R)}if(c===!1)return y("entity-not-allowed",ce);if(c!==!0)return y("host-failed",R);if(U(u.request)&&t.dataPort.writeProtocol!==M)return y("invalid-host",T);try{let n=await fe(t.dataPort,u.request);if(r){let l=ie(r.op,n);if(!l.ok)return U(u.request)?y("unknown",j):y("invalid-result",N);return{ok:!0,data:l.data}}let p=ae(n);if(!p.ok)return y("invalid-result",N);return{ok:!0,data:p.value}}catch(n){if(s&&U(u.request))return y("unknown",j);if(s)return y("host-failed",R);if(n instanceof ne)return y("host-rejected",me(n));return y("host-failed",R)}}catch{return y("host-failed",R)}}function ge(e){let t=e.protocol??E,a=/^[A-Za-z0-9_-]{16,128}$/,o=/^[A-Za-z0-9_-]{1,128}$/,i=/^__[A-Za-z][A-Za-z0-9_]{0,62}$/;if(!a.test(e.previewToken)||!o.test(e.requestSource)||!o.test(e.responseSource)||![E,V].includes(t)||e.compatibilityGlobalName!==void 0&&(!i.test(e.compatibilityGlobalName)||["__uibotData","__uibotDataWebV1Shim","__proto__"].includes(e.compatibilityGlobalName)))throw Error("Invalid creation data Web bridge configuration");let s=JSON.stringify(e.requestSource),d=JSON.stringify(e.responseSource),u=JSON.stringify(e.previewToken),r=JSON.stringify(e.compatibilityGlobalName??null),c=JSON.stringify(t);return`(function(){
2
+ var seq = 0, requestSource = ${s}, responseSource = ${d};
3
3
  var previewToken = ${u}, compatibilityGlobalName = ${r};
4
- var webProtocol = ${s}, isV2 = webProtocol === 'uibot.creation-data.web.v2';
4
+ var webProtocol = ${c}, isV2 = webProtocol === 'uibot.creation-data.web.v2';
5
5
  if (window.__uibotDataWebV1Shim || window.__uibotData !== undefined ||
6
6
  (compatibilityGlobalName && window[compatibilityGlobalName] !== undefined))
7
7
  throw new Error('creation_data_bridge_collision');
8
- var maxDepth = ${X}, maxValues = ${Y};
9
- var maxTextBytes = ${Z};
8
+ var maxDepth = ${ee}, maxValues = ${re};
9
+ var maxTextBytes = ${te};
10
10
  function plain(value){
11
11
  if (value === null || typeof value !== 'object' || Array.isArray(value) || Object.prototype.toString.call(value) !== '[object Object]') return false;
12
12
  var proto = Object.getPrototypeOf(value);
@@ -159,4 +159,4 @@ import{createEngine as q,createLifecycleController as H}from"@uibot/engine";func
159
159
  window.__uibotData = client;
160
160
  if (compatibilityGlobalName) window[compatibilityGlobalName] = client;
161
161
  window.__uibotDataWebV1Shim = true;
162
- })();`}import{jsxDEV as v}from"react/jsx-dev-runtime";function ve(){return globalThis.process?.env?.NODE_ENV==="production"}function be(e){if(!(e.enabled??!ve()))return null;let n=e.gaps??[],i=e.warnings??[],l=e.droppedEventFields??[];if(n.length+i.length+l.length===0)return null;return v("aside",{"data-uibot-diagnostics":"true",style:{position:"fixed",right:12,bottom:12,maxWidth:360,padding:12,background:"var(--uibot-surface, #fff)",color:"var(--uibot-text, #111)",border:"1px solid var(--uibot-border, #ccc)",font:"12px/1.4 var(--uibot-font, sans-serif)"},children:[v("strong",{children:"UIBot diagnostics"},void 0,!1,void 0,this),v("ul",{children:[n.map((a)=>v("li",{children:[a.code??a.reason," ",a.elementKey," ",a.path??a.missingType]},`gap:${a.elementKey}:${a.path??a.missingType}`,!0,void 0,this)),i.map((a)=>v("li",{children:[a.code," ",a.elementKey," ",a.path]},`warn:${a.elementKey??""}:${a.path??a.code}`,!0,void 0,this)),l.map((a)=>v("li",{children:["dropped event field ",a]},`drop:${a}`,!0,void 0,this))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}import{UIBotLiveRenderer as Ge,UIBotRenderer as Je}from"@uibot/renderer-react";import{defineCatalog as Ce,parseUIBotRegistryItemDescriptor as he}from"@uibot/contracts";import{defineRegistry as Ie}from"@uibot/renderer-react";class g extends Error{constructor(e){super(`installed UIBot library: ${e}`);this.name="InstalledUIBotLibraryError"}}function Re(e){let t={},n=new Map,i=new Map,l={};for(let[c,u]of Object.entries(e.descriptors)){let r=he(u),s=c.slice(0,c.lastIndexOf("/")+1);for(let o of r.components??[]){let d=n.get(o.name);if(d)throw new g(`component "${o.name}" is provided by both "${d}" and "${r.item}"`);let p=`${s}${o.module}`,y=e.modules[p];if(!y)throw new g(`"${r.item}" needs ${p}, which is not installed`);let m=y[o.export];if(typeof m!=="function")throw new g(`${p} has no component export "${o.export}" for "${o.name}"`);n.set(o.name,r.item),t[o.name]=o.catalog,l[o.name]={category:o.catalog.category,sourcePlugin:`registry:${r.item}`,component:m}}if(r.template){let o=r.template.contract.name;if(i.has(o))throw new g(`template "${o}" is installed twice`);let d=e.templateSources?.[`${s}${r.template.file}`];if(e.templateSources&&d===void 0)throw new g(`template "${o}" needs ${s}${r.template.file}, which is not installed`);i.set(o,{contract:r.template.contract,...d===void 0?{}:{source:d}})}}let a=Object.fromEntries(i);return{catalog:Ce({components:t,templates:Object.fromEntries(Object.entries(a).map(([c,u])=>[c,u.contract]))}),registry:Ie(l),templates:a}}export{fe as CREATION_DATA_WEB_PROTOCOL,me as CREATION_DATA_WEB_V2_PROTOCOL,ge as CREATION_DATA_WRITE_PROTOCOL,ye as CreationDataPortRejection,g as InstalledUIBotLibraryError,K as UIBotAppHost,be as UIBotDiagnostics,Ge as UIBotLiveRenderer,I as UIBotPageAccessError,Je as UIBotRenderer,Re as assembleInstalledUIBotLibrary,D as bindUrlState,pe as createCreationDataWebShimSource,G as createLiveRuntimeAdapter,de as dispatchCreationData};
162
+ })();`}import{jsx as Re,jsxs as C}from"react/jsx-runtime";function we(){return globalThis.process?.env?.NODE_ENV==="production"}function Ie(e){if(!(e.enabled??!we()))return null;let a=e.gaps??[],o=e.warnings??[],i=e.droppedEventFields??[];if(a.length+o.length+i.length===0)return null;return C("aside",{"data-uibot-diagnostics":"true",style:{position:"fixed",right:12,bottom:12,maxWidth:360,padding:12,background:"var(--uibot-surface, #fff)",color:"var(--uibot-text, #111)",border:"1px solid var(--uibot-border, #ccc)",font:"12px/1.4 var(--uibot-font, sans-serif)"},children:[Re("strong",{children:"UIBot diagnostics"}),C("ul",{children:[a.map((s)=>C("li",{children:[s.code??s.reason," ",s.elementKey," ",s.path??s.missingType]},`gap:${s.elementKey}:${s.path??s.missingType}`)),o.map((s)=>C("li",{children:[s.code," ",s.elementKey," ",s.path]},`warn:${s.elementKey??""}:${s.path??s.code}`)),i.map((s)=>C("li",{children:["dropped event field ",s]},`drop:${s}`))]})]})}import{linkedSpecEtag as Ce,readLinkedSpecSnapshot as Pe}from"@uibot/contracts";class f extends Error{status;constructor(e){super(`Linked Spec ${e}`);this.status=e}}function w(e){let t=e.intervalMs??1000,a=e.timeoutMs??15000;if(!Number.isSafeInteger(t)||t<250||t>60000||!Number.isSafeInteger(a)||a<250||a>60000)throw Error("Invalid linked Spec timing");let o=!1,i,s="loading",d,u,r,c=(l)=>{let v=e.cursor?.(l)??{id:l.revisionId,sequence:l.revisionNumber??0};if(!Number.isSafeInteger(v.sequence)||v.sequence<1)throw new f("invalid");return v},n=(l)=>{s=l,e.onStatus?.(l)};async function p(){if(o)return;if(u)return u;clearTimeout(r);let l=new AbortController;d=l;let v=setTimeout(()=>l.abort(),a),g=()=>{if(o)return!1;if(l.signal.aborted)throw new f("offline");return!0};return u=Promise.resolve().then(async()=>{try{if(!g())return;let b=await e.read({signal:l.signal,...i?{revisionId:c(i).id}:{}});if(!g())return;if(b===void 0){if(!i)throw new f("invalid");n("synced");return}let m;try{m=e.decode(b)}catch{throw new f("invalid")}if(!m){i=void 0,n("unpublished");return}if(m.projectId!==e.projectId||m.artifactId!==e.artifactId)throw new f("invalid");let h=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e.content(m)))),(D)=>D.toString(16).padStart(2,"0")).join("");if(!g())return;if(h!==m.sourceHash)throw new f("invalid");if(i){if(c(m).id===c(i).id){if(m.sourceHash!==i.sourceHash||m.revisionId!==i.revisionId||m.revisionNumber!==i.revisionNumber||c(m).sequence!==c(i).sequence)throw new f("invalid");n("synced");return}if(c(m).sequence<=c(i).sequence)throw new f("invalid")}if(e.canApply?.()===!1){n("conflict");return}let P;try{P=await e.prepare(m,l.signal)}catch{throw new f("invalid")}if(!g())return;if(e.canApply?.()===!1){n("conflict");return}e.apply(P,m),i=m,n("synced")}catch(b){if(!o)n(b instanceof f?b.status:"offline")}finally{if(clearTimeout(v),d=void 0,u=void 0,!o)r=setTimeout(()=>void p(),t)}}),u}return p(),{refresh:p,status:()=>s,revision:()=>i?c(i).id:void 0,stop(){o=!0,clearTimeout(r),d?.abort()}}}function H(e){return async({revisionId:t,signal:a})=>{let o=new Headers(await e.headers?.());if(o.set("accept","application/json"),t)o.set("if-none-match",(e.etag??Ce)(t));let i=await(e.fetcher??fetch)(e.url,{headers:o,signal:a,cache:"no-store",redirect:"error"});if(i.status===401||i.status===403)throw new f("denied");if(i.status===304){if(!t)throw new f("invalid");return}if(!i.ok)throw new f("offline");let s=i.body?.getReader();if(!s)throw new f("invalid");let d=[],u=0;try{while(!0){let{done:n,value:p}=await s.read();if(n)break;if(u+=p.length,u>8000000)throw await s.cancel(),new f("invalid");d.push(p)}}finally{s.releaseLock()}let r=new Uint8Array(u),c=0;for(let n of d)r.set(n,c),c+=n.length;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new f("invalid")}}}function Qe(e){return w({...e,decode:Pe,content:(t)=>t.source.content})}import{UIBotLiveRenderer as Dt,UIBotRenderer as At}from"@uibot/renderer-react";import{defineCatalog as De,parseUIBotRegistryItemDescriptor as Ae}from"@uibot/contracts";import{defineRegistry as xe}from"@uibot/renderer-react";class S extends Error{constructor(e){super(`installed UIBot library: ${e}`);this.name="InstalledUIBotLibraryError"}}function _e(e){let t={},a=new Map,o=new Map,i={};for(let[d,u]of Object.entries(e.descriptors)){let r=Ae(u),c=d.slice(0,d.lastIndexOf("/")+1);for(let n of r.components??[]){let p=a.get(n.name);if(p)throw new S(`component "${n.name}" is provided by both "${p}" and "${r.item}"`);let l=`${c}${n.module}`,v=e.modules[l];if(!v)throw new S(`"${r.item}" needs ${l}, which is not installed`);let g=v[n.export];if(typeof g!=="function")throw new S(`${l} has no component export "${n.export}" for "${n.name}"`);a.set(n.name,r.item),t[n.name]=n.catalog,i[n.name]={category:n.catalog.category,sourcePlugin:`registry:${r.item}`,component:g}}if(r.template){let n=r.template.contract.name;if(o.has(n))throw new S(`template "${n}" is installed twice`);let p=e.templateSources?.[`${c}${r.template.file}`];if(e.templateSources&&p===void 0)throw new S(`template "${n}" needs ${c}${r.template.file}, which is not installed`);o.set(n,{contract:r.template.contract,...p===void 0?{}:{source:p}})}}let s=Object.fromEntries(o);return{catalog:De({components:t,templates:Object.fromEntries(Object.entries(s).map(([d,u])=>[d,u.contract]))}),registry:xe(i),templates:s}}import{appDocumentText as ke,readLinkedAppSnapshot as Oe}from"@uibot/contracts";function st(e){return w({...e,decode:Oe,content:(t)=>ke(t.document)})}import{appDocumentText as Te,appReleaseEtag as Ue,readAppReleaseView as Ee}from"@uibot/contracts";function pt(e){return H({...e,etag:Ue})}function ft(e){return w({...e,decode:(t)=>{let a=Ee(t);if(a.projectId!==e.projectId||a.artifactId!==e.artifactId)throw Error("Foreign release pointer");return a.published?a:void 0},content:(t)=>Te(t.document),cursor:(t)=>({id:t.releaseId,sequence:t.releaseSequence})})}async function yt(e,t){for(let a of e.tsx){let o=t[a.id];if(!o)throw Error(`Application TSX module is not installed: ${a.id}`);let i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a.source));if(Array.from(new Uint8Array(i),(d)=>d.toString(16).padStart(2,"0")).join("")!==o.sourceHash)throw Error(`Application TSX module needs a host build: ${a.id}`)}}export{ve as CREATION_DATA_WEB_PROTOCOL,be as CREATION_DATA_WEB_V2_PROTOCOL,he as CREATION_DATA_WRITE_PROTOCOL,Se as CreationDataPortRejection,S as InstalledUIBotLibraryError,f as LinkedSpecError,Y as UIBotAppHost,Ie as UIBotDiagnostics,Dt as UIBotLiveRenderer,A as UIBotPageAccessError,At as UIBotRenderer,_e as assembleInstalledUIBotLibrary,_ as bindUrlState,ge as createCreationDataWebShimSource,st as createLinkedAppSync,H as createLinkedSpecHttpReader,Qe as createLinkedSpecSync,k as createLiveRuntimeAdapter,pt as createPublishedAppHttpReader,ft as createPublishedAppSync,Q as createSpecPreviewSession,ye as dispatchCreationData,yt as verifyAppModules};
@@ -0,0 +1,17 @@
1
+ import { type LinkedAppSnapshot, type LinkedSpecIdentity } from "@uibot/contracts";
2
+ import { type LinkedSpecReader, type LinkedSpecStatus } from "./revision-sync.js";
3
+ /** Application-level following uses the same cancellation, ordering and draft guards as linked Spec. */
4
+ export declare function createLinkedAppSync<T>(options: LinkedSpecIdentity & {
5
+ read: LinkedSpecReader;
6
+ prepare: (snapshot: LinkedAppSnapshot, signal: AbortSignal) => Promise<T>;
7
+ apply: (candidate: T, snapshot: LinkedAppSnapshot) => void;
8
+ canApply?: () => boolean;
9
+ onStatus?: (status: LinkedSpecStatus) => void;
10
+ intervalMs?: number;
11
+ timeoutMs?: number;
12
+ }): {
13
+ refresh: () => Promise<void>;
14
+ status: () => LinkedSpecStatus;
15
+ revision: () => string | undefined;
16
+ stop(): void;
17
+ };
@@ -0,0 +1,24 @@
1
+ import { type LinkedSpecIdentity, type LinkedSpecSnapshot } from "@uibot/contracts";
2
+ import { type LinkedSpecReader, type LinkedSpecStatus } from "./revision-sync.js";
3
+ export { LinkedSpecError, type LinkedSpecReader, type LinkedSpecReadInput, type LinkedSpecStatus, } from "./revision-sync.js";
4
+ /** Host supplies its own authenticated transport. There is no browser secret discovery. */
5
+ export declare function createLinkedSpecHttpReader(options: {
6
+ url: string;
7
+ fetcher?: typeof fetch;
8
+ headers?: () => HeadersInit | Promise<HeadersInit>;
9
+ etag?: (id: string) => string;
10
+ }): LinkedSpecReader;
11
+ export declare function createLinkedSpecSync<T>(options: LinkedSpecIdentity & {
12
+ read: LinkedSpecReader;
13
+ prepare: (snapshot: LinkedSpecSnapshot, signal: AbortSignal) => Promise<T>;
14
+ apply: (candidate: T, snapshot: LinkedSpecSnapshot) => void;
15
+ canApply?: () => boolean;
16
+ onStatus?: (status: LinkedSpecStatus) => void;
17
+ intervalMs?: number;
18
+ timeoutMs?: number;
19
+ }): {
20
+ refresh: () => Promise<void>;
21
+ status: () => LinkedSpecStatus;
22
+ revision: () => string | undefined;
23
+ stop(): void;
24
+ };
@@ -0,0 +1,6 @@
1
+ import type { CreateLiveAdapterOptions, UIBotAppRuntimeAdapter } from "./live-runtime-adapter.js";
2
+ /** Local preview pages keep independent state and share only host-injected drivers. */
3
+ export declare function createSpecPreviewSession(options: Omit<CreateLiveAdapterOptions, "engine">): {
4
+ adapters: Map<string, UIBotAppRuntimeAdapter>;
5
+ dispose(): void;
6
+ };
@@ -0,0 +1,19 @@
1
+ import { type AppRelease, type LinkedSpecIdentity } from "@uibot/contracts";
2
+ import { type LinkedSpecReader, type LinkedSpecStatus } from "./revision-sync.js";
3
+ import { createLinkedSpecHttpReader } from "./linked-spec.js";
4
+ export declare function createPublishedAppHttpReader(options: Parameters<typeof createLinkedSpecHttpReader>[0]): LinkedSpecReader;
5
+ /** No development fallback. The trusted host reads NowAPI releases/current. */
6
+ export declare function createPublishedAppSync<T>(options: LinkedSpecIdentity & {
7
+ read: LinkedSpecReader;
8
+ prepare: (snapshot: AppRelease, signal: AbortSignal) => Promise<T>;
9
+ apply: (candidate: T, snapshot: AppRelease) => void;
10
+ canApply?: () => boolean;
11
+ onStatus?: (status: LinkedSpecStatus) => void;
12
+ intervalMs?: number;
13
+ timeoutMs?: number;
14
+ }): {
15
+ refresh: () => Promise<void>;
16
+ status: () => LinkedSpecStatus;
17
+ revision: () => string | undefined;
18
+ stop(): void;
19
+ };
@@ -0,0 +1,40 @@
1
+ import type { LinkedSpecIdentity } from "@uibot/contracts";
2
+ export interface RevisionSnapshot extends LinkedSpecIdentity {
3
+ revisionId: string;
4
+ revisionNumber?: number;
5
+ sourceHash: string;
6
+ }
7
+ export type LinkedSpecStatus = "loading" | "synced" | "offline" | "denied" | "conflict" | "invalid" | "unpublished";
8
+ export interface LinkedSpecReadInput {
9
+ revisionId?: string;
10
+ signal: AbortSignal;
11
+ }
12
+ export type LinkedSpecReader = (input: LinkedSpecReadInput) => Promise<unknown | undefined>;
13
+ export declare class LinkedSpecError extends Error {
14
+ readonly status: "offline" | "denied" | "invalid";
15
+ constructor(status: "offline" | "denied" | "invalid");
16
+ }
17
+ /** Read-only, serialized revision following. Preparation must not mutate the mounted application. */
18
+ export declare function createRevisionSync<T, S extends RevisionSnapshot>(options: LinkedSpecIdentity & {
19
+ /** Undefined means a validated, explicitly unpublished application. */
20
+ decode: (value: unknown) => S | undefined;
21
+ content: (snapshot: S) => string;
22
+ /** Publication uses the release cursor so rollback can select an older revision. */
23
+ cursor?: (snapshot: S) => {
24
+ id: string;
25
+ sequence: number;
26
+ };
27
+ read: LinkedSpecReader;
28
+ prepare: (snapshot: S, signal: AbortSignal) => Promise<T>;
29
+ /** Synchronously adopt one fully prepared candidate. Hosts own runtime state and routing. */
30
+ apply: (candidate: T, snapshot: S) => void;
31
+ canApply?: () => boolean;
32
+ onStatus?: (status: LinkedSpecStatus) => void;
33
+ intervalMs?: number;
34
+ timeoutMs?: number;
35
+ }): {
36
+ refresh: () => Promise<void>;
37
+ status: () => LinkedSpecStatus;
38
+ revision: () => string | undefined;
39
+ stop(): void;
40
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uibot/runtime",
3
- "version": "0.18.1",
3
+ "version": "0.20.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,9 +30,9 @@
30
30
  "react": ">=18"
31
31
  },
32
32
  "dependencies": {
33
- "@uibot/contracts": "^0.18.1",
34
- "@uibot/engine": "^0.18.1",
35
- "@uibot/renderer-react": "^0.18.1"
33
+ "@uibot/contracts": "^0.20.0",
34
+ "@uibot/engine": "^0.20.0",
35
+ "@uibot/renderer-react": "^0.20.0"
36
36
  },
37
37
  "scripts": {
38
38
  "build": "rm -rf dist && bun build --minify ./src/index.ts --tsconfig-override ../../scripts/tsconfig.bundle.json --outdir ./dist --format esm --target browser --packages external --external react --external react/* --external @uibot/contracts --external @uibot/engine --external @uibot/renderer-react && bun x tsc -p tsconfig.json",