forgeframe 0.0.6 → 0.0.9
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/constants.d.ts +1 -1
- package/dist/core/consumer/props-pipeline.d.ts +16 -0
- package/dist/core/consumer/renderer.d.ts +2 -0
- package/dist/core/consumer/transport.d.ts +1 -0
- package/dist/core/consumer.d.ts +12 -0
- package/dist/core/host.d.ts +44 -0
- package/dist/forgeframe.js +1034 -779
- package/dist/forgeframe.umd.cjs +2 -2
- package/dist/render/iframe.d.ts +30 -0
- package/dist/types.d.ts +1 -1
- package/package.json +1 -1
package/dist/forgeframe.umd.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(u,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(u=typeof globalThis<"u"?globalThis:u||self,p(u.ForgeFrame={}))})(this,(function(u){"use strict";const p={IFRAME:"iframe",POPUP:"popup"},m={RENDER:"render",RENDERED:"rendered",PRERENDER:"prerender",PRERENDERED:"prerendered",DISPLAY:"display",ERROR:"error",CLOSE:"close",DESTROY:"destroy",PROPS:"props",RESIZE:"resize",FOCUS:"focus"},O={JSON:"json",BASE64:"base64",DOTIFY:"dotify"},H={REQUEST:"request",RESPONSE:"response"},h={INIT:"forgeframe_init",PROPS:"forgeframe_props",CLOSE:"forgeframe_close",RESIZE:"forgeframe_resize",FOCUS:"forgeframe_focus",SHOW:"forgeframe_show",HIDE:"forgeframe_hide",ERROR:"forgeframe_error",EXPORT:"forgeframe_export",CALL:"forgeframe_call",CONSUMER_EXPORT:"forgeframe_consumer_export",GET_SIBLINGS:"forgeframe_get_siblings"},$="__forgeframe__",Y=(()=>{if("0.0.6".trim().length===0)throw new Error("ForgeFrame VERSION injection is missing. Configure __FORGEFRAME_VERSION__ in build/test tooling.");return"0.0.6"})();class pe{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const n=r=>(this.off(e,n),t(r));return this.on(e,n)}emit(e,t){const n=this.listeners.get(e);if(n)for(const r of n)try{const i=r(t);i&&typeof i=="object"&&"catch"in i&&typeof i.catch=="function"&&i.catch(o=>{console.error(`Error in async event handler for "${e}":`,o)})}catch(i){console.error(`Error in event handler for "${e}":`,i)}}off(e,t){if(!t){this.listeners.delete(e);return}const n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}removeAllListeners(){this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size??0}}function Ke(){const s=Date.now().toString(36),e=Math.random().toString(36).slice(2,11);return`${s}_${e}`}function A(){return Math.random().toString(36).slice(2,11)}class qe{tasks=[];cleaned=!1;register(e){if(this.cleaned){Promise.resolve().then(()=>e()).catch(t=>{console.error("Error in cleanup task:",t)});return}this.tasks.push(e)}async cleanup(){if(this.cleaned)return;this.cleaned=!0;const e=this.tasks.reverse();this.tasks=[];for(const t of e)try{await t()}catch(n){console.error("Error in cleanup task:",n)}}isCleaned(){return this.cleaned}reset(){this.tasks=[],this.cleaned=!1}}function fe(){let s,e;return{promise:new Promise((n,r)=>{s=n,e=r}),resolve:s,reject:e}}function Je(s,e,t="Operation timed out"){return new Promise((n,r)=>{const i=setTimeout(()=>{r(new Error(`${t} (${e}ms)`))},e);s.then(o=>{clearTimeout(i),n(o)}).catch(o=>{clearTimeout(i),r(o)})})}const v=new Map,Xe=200;function Ye(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ge(s){if(!s.includes("*"))return null;const e=v.get(s);if(e)return e;const t=s.split("*").map(r=>Ye(r)).join(".*"),n=new RegExp(`^${t}$`);if(v.size>=Xe){const r=v.keys().next().value;r&&v.delete(r)}return v.set(s,n),n}function Ze(s,e){return s.global||s.sticky?new RegExp(s.source,s.flags.replace(/[gy]/g,"")).test(e):s.test(e)}function G(s=window){try{return s.location.origin}catch{return""}}function Qe(s,e=window){try{return s.location.origin===e.location.origin}catch{return!1}}function C(s,e){if(typeof s=="string"){if(s==="*")return!0;const t=Ge(s);return t?t.test(e):s===e}return s instanceof RegExp?Ze(s,e):Array.isArray(s)?s.some(t=>C(t,e)):!1}function Z(s){if(!s)return!0;try{return s.closed}catch{return!0}}function et(s=window){try{return s.opener}catch{return null}}function tt(s=window){try{const e=s.parent;return e&&e!==s?e:null}catch{return null}}function st(s=window){try{return s.parent!==s}catch{return!0}}function nt(s=window){try{return s.opener!==null&&s.opener!==void 0}catch{return!1}}const me=100,E=new Map;function rt(){const s=[];for(const[e,t]of E.entries())Z(t)&&s.push(e);for(const e of s)E.delete(e)}function it(s,e){if(E.size>=me&&rt(),E.size>=me){const t=E.keys().next().value;t&&E.delete(t)}E.set(s,e)}function ot(s){E.delete(s)}function at(s,e){return s.global||s.sticky?new RegExp(s.source,s.flags.replace(/[gy]/g,"")).test(e):s.test(e)}class w{_optional=!1;_nullable=!1;_default;"~standard"={version:1,vendor:"forgeframe",validate:e=>e===null?this._nullable?{value:null}:{issues:[{message:"Expected a value, got null"}]}:e===void 0?this._default!==void 0?{value:typeof this._default=="function"?this._default():this._default}:this._optional?{value:void 0}:{issues:[{message:"Required"}]}:this._validate(e)};optional(){const e=this._clone();return e._optional=!0,e}nullable(){const e=this._clone();return e._nullable=!0,e}default(e){const t=this._clone();return t._default=e,t}}class L extends w{_minLength;_maxLength;_pattern;_patternMessage;_trim=!1;_validate(e){if(typeof e!="string")return{issues:[{message:`Expected string, got ${typeof e}`}]};const t=this._trim?e.trim():e;return this._minLength!==void 0&&t.length<this._minLength?{issues:[{message:`String must be at least ${this._minLength} characters`}]}:this._maxLength!==void 0&&t.length>this._maxLength?{issues:[{message:`String must be at most ${this._maxLength} characters`}]}:this._pattern&&!at(this._pattern,t)?{issues:[{message:this._patternMessage||`String must match pattern ${this._pattern}`}]}:{value:t}}_clone(){const e=new L;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._minLength=this._minLength,e._maxLength=this._maxLength,e._pattern=this._pattern,e._patternMessage=this._patternMessage,e._trim=this._trim,e}min(e){const t=this._clone();return t._minLength=e,t}max(e){const t=this._clone();return t._maxLength=e,t}length(e){const t=this._clone();return t._minLength=e,t._maxLength=e,t}pattern(e,t){const n=this._clone();return n._pattern=e,n._patternMessage=t,n}email(){return this.pattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"Invalid email address")}url(){return this.pattern(/^https?:\/\/.+/,"Invalid URL")}uuid(){return this.pattern(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"Invalid UUID")}trim(){const e=this._clone();return e._trim=!0,e}nonempty(){const e=this._clone();return e._minLength=1,e}}class z extends w{_min;_max;_int=!1;_validate(e){return typeof e!="number"||Number.isNaN(e)?{issues:[{message:`Expected number, got ${typeof e}`}]}:this._int&&!Number.isInteger(e)?{issues:[{message:"Expected integer"}]}:this._min!==void 0&&e<this._min?{issues:[{message:`Number must be >= ${this._min}`}]}:this._max!==void 0&&e>this._max?{issues:[{message:`Number must be <= ${this._max}`}]}:{value:e}}_clone(){const e=new z;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._min=this._min,e._max=this._max,e._int=this._int,e}min(e){const t=this._clone();return t._min=e,t}max(e){const t=this._clone();return t._max=e,t}int(){const e=this._clone();return e._int=!0,e}positive(){const e=this._clone();return e._min=Number.MIN_VALUE,e}nonnegative(){const e=this._clone();return e._min=0,e}negative(){const e=this._clone();return e._max=-Number.MIN_VALUE,e}}class k extends w{_validate(e){return typeof e!="boolean"?{issues:[{message:`Expected boolean, got ${typeof e}`}]}:{value:e}}_clone(){const e=new k;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class M extends w{_validate(e){return typeof e!="function"?{issues:[{message:`Expected function, got ${typeof e}`}]}:{value:e}}_clone(){const e=new M;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class I extends w{_itemSchema;_minLength;_maxLength;_validate(e){if(!Array.isArray(e))return{issues:[{message:`Expected array, got ${typeof e}`}]};if(this._minLength!==void 0&&e.length<this._minLength)return{issues:[{message:`Array must have at least ${this._minLength} items`}]};if(this._maxLength!==void 0&&e.length>this._maxLength)return{issues:[{message:`Array must have at most ${this._maxLength} items`}]};if(this._itemSchema){const t=[];for(let n=0;n<e.length;n++){const r=this._itemSchema["~standard"].validate(e[n]);if(r instanceof Promise)throw new Error("Async schema validation is not supported. Use synchronous schemas.");if(r.issues)return{issues:r.issues.map(i=>({...i,path:[n,...i.path||[]]}))};t.push(r.value)}return{value:t}}return{value:e}}_clone(){const e=new I;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._itemSchema=this._itemSchema,e._minLength=this._minLength,e._maxLength=this._maxLength,e}of(e){const t=new I;return t._optional=this._optional,t._nullable=this._nullable,t._itemSchema=e,t._minLength=this._minLength,t._maxLength=this._maxLength,t}min(e){const t=this._clone();return t._minLength=e,t}max(e){const t=this._clone();return t._maxLength=e,t}nonempty(){return this.min(1)}}class x extends w{_shape;_strict=!1;_validate(e){if(typeof e!="object"||e===null||Array.isArray(e))return{issues:[{message:`Expected object, got ${Array.isArray(e)?"array":typeof e}`}]};const t=e,n={};if(this._shape){if(this._strict){const r=new Set(Object.keys(this._shape));for(const i of Object.keys(t))if(!r.has(i))return{issues:[{message:`Unknown key: ${i}`,path:[i]}]}}for(const[r,i]of Object.entries(this._shape)){const o=i["~standard"].validate(t[r]);if(o instanceof Promise)throw new Error("Async schema validation is not supported. Use synchronous schemas.");if(o.issues)return{issues:o.issues.map(a=>({...a,path:[r,...a.path||[]]}))};n[r]=o.value}if(!this._strict)for(const r of Object.keys(t))r in this._shape||(n[r]=t[r]);return{value:n}}return{value:e}}_clone(){const e=new x;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._shape=this._shape,e._strict=this._strict,e}shape(e){const t=new x;return t._optional=this._optional,t._nullable=this._nullable,t._shape=e,t._strict=this._strict,t}strict(){const e=this._clone();return e._strict=!0,e}}class W extends w{_value;constructor(e){super(),this._value=e}_validate(e){return e!==this._value?{issues:[{message:`Expected ${JSON.stringify(this._value)}, got ${JSON.stringify(e)}`}]}:{value:e}}_clone(){const e=new W(this._value);return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class B extends w{_values;_valueSet;constructor(e){super(),this._values=e,this._valueSet=new Set(e)}_validate(e){return this._valueSet.has(e)?{value:e}:{issues:[{message:`Expected one of [${this._values.map(t=>JSON.stringify(t)).join(", ")}], got ${JSON.stringify(e)}`}]}}_clone(){const e=new B(this._values);return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class j extends w{constructor(){super(),this._nullable=!0}_validate(e){return{value:e}}_clone(){const e=new j;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}const f={string:()=>new L,number:()=>new z,boolean:()=>new k,function:()=>new M,array:()=>new I,object:()=>new x,literal:s=>new W(s),enum:s=>new B(s),any:()=>new j},b={uid:{schema:f.string().optional(),sendToHost:!0},tag:{schema:f.string().optional(),sendToHost:!0},dimensions:{schema:f.object().default(()=>({width:"100%",height:"100%"})),sendToHost:!1},timeout:{schema:f.number().default(1e4),sendToHost:!1},cspNonce:{schema:f.string().optional(),sendToHost:!0},onDisplay:{schema:f.function().optional(),sendToHost:!1},onRendered:{schema:f.function().optional(),sendToHost:!1},onRender:{schema:f.function().optional(),sendToHost:!1},onPrerendered:{schema:f.function().optional(),sendToHost:!1},onPrerender:{schema:f.function().optional(),sendToHost:!1},onClose:{schema:f.function().optional(),sendToHost:!1},onDestroy:{schema:f.function().optional(),sendToHost:!1},onResize:{schema:f.function().optional(),sendToHost:!1},onFocus:{schema:f.function().optional(),sendToHost:!1},onError:{schema:f.function().optional(),sendToHost:!1},onProps:{schema:f.function().optional(),sendToHost:!1}};function D(s){return typeof s=="object"&&s!==null&&"~standard"in s&&typeof s["~standard"]=="object"&&s["~standard"]!==null&&s["~standard"].version===1&&typeof s["~standard"].vendor=="string"&&typeof s["~standard"].validate=="function"}function ct(s,e,t){const n=s["~standard"].validate(e);if(n instanceof Promise)throw new Error(`Prop "${t}" uses an async schema. ForgeFrame only supports synchronous schema validation. Please use a synchronous schema or remove async operations (like database lookups) from your schema definition.`);if(n.issues){const r=n.issues.map(i=>`${lt(i.path,t)}: ${i.message}`);throw new Error(`Validation failed: ${r.join("; ")}`)}return n.value}function lt(s,e){if(!s||s.length===0)return e;const t=s.map(n=>{if(typeof n=="object"&&n!==null){if("key"in n&&n.key!==void 0)return String(n.key);if("index"in n&&typeof n.index=="number")return String(n.index)}return String(n)});return`${e}.${t.join(".")}`}function T(s){const e=D(s);return{isDirectSchema:e,definition:e?{schema:s}:s}}function ge(s,e,t){const n={...b,...e},r={};for(const[i,o]of Object.entries(n)){const{definition:a}=T(o);let c;const l=a.alias,d=i in s,g=l&&l in s;if(d)c=s[i];else if(g)c=s[l];else if(a.value)c=a.value(t);else if(a.default!==void 0)c=typeof a.default=="function"?a.default(t):a.default;else if(a.schema&&D(a.schema)){const y=a.schema["~standard"].validate(void 0);!(y instanceof Promise)&&!y.issues&&(c=y.value)}c!==void 0&&a.decorate&&(c=a.decorate({value:c,props:r})),r[i]=c}return r}function ye(s,e){const t={...b,...e};for(const[n,r]of Object.entries(t)){const{isDirectSchema:i,definition:o}=T(r);let a=s[n];if(o.required&&a===void 0)throw new Error(`Prop "${n}" is required but was not provided`);if(o.schema&&D(o.schema))(a!==void 0||i)&&(a=ct(o.schema,a,n),s[n]=a);else if(a===void 0)continue;o.validate&&o.validate({value:a,props:s})}}function we(s,e,t,n){const r={...b,...e},i={};for(const[o,a]of Object.entries(r)){const{definition:c}=T(a),l=s[o];if(c.sendToHost===!1||c.sameDomain&&!n)continue;if(c.trustedDomains){const g=c.trustedDomains;if(!C(g,t))continue}let d=l;c.hostDecorate&&l!==void 0&&(d=c.hostDecorate({value:l,props:s})),i[o]=d}return i}function ut(s,e){const t=new URLSearchParams,n={...b,...e};for(const[r,i]of Object.entries(n)){const{definition:o}=T(i),a=s[r];if(a===void 0||typeof a=="function"||!o.queryParam)continue;const c=typeof o.queryParam=="string"?o.queryParam:r;let l;typeof o.queryParam=="function"?l=o.queryParam({value:a}):typeof a=="object"?l=JSON.stringify(a):l=String(a),t.set(c,l)}return t}function ht(s,e){const t=new URLSearchParams,n={...b,...e};for(const[r,i]of Object.entries(n)){const{definition:o}=T(i),a=s[r];if(a===void 0||typeof a=="function"||!o.bodyParam)continue;const c=typeof o.bodyParam=="string"?o.bodyParam:r;let l;typeof o.bodyParam=="function"?l=o.bodyParam({value:a}):typeof a=="object"?l=JSON.stringify(a):l=String(a),t.set(c,l)}return t}const _e=500,dt=new Set(["__proto__"]);function Pe(s){return!dt.has(s)}class Q{constructor(e){this.messenger=e,this.setupCallHandler()}localFunctions=new Map;remoteFunctions=new Map;currentBatchIds=new Set;serialize(e,t){if(this.localFunctions.size>=_e){const r=this.localFunctions.keys().next().value;r&&this.localFunctions.delete(r)}const n=A();return this.localFunctions.set(n,e),this.currentBatchIds.add(n),{__type__:"function",__id__:n,__name__:t||e.name||"anonymous"}}deserialize(e,t,n){const r=`${e.__id__}`,i=this.remoteFunctions.get(r);if(i)return i;if(this.remoteFunctions.size>=_e){const a=this.remoteFunctions.keys().next().value;a&&this.remoteFunctions.delete(a)}const o=async(...a)=>this.messenger.send(t,n,h.CALL,{id:e.__id__,args:a});return Object.defineProperty(o,"name",{value:e.__name__,configurable:!0}),this.remoteFunctions.set(r,o),o}static isFunctionRef(e){return typeof e=="object"&&e!==null&&e.__type__==="function"&&typeof e.__id__=="string"}setupCallHandler(){this.messenger.on(h.CALL,async({id:e,args:t})=>{const n=this.localFunctions.get(e);if(!n)throw new Error(`Function with id "${e}" not found`);return n(...t)})}removeLocal(e){this.localFunctions.delete(e)}startBatch(){this.currentBatchIds.clear()}finishBatch(e=!1){if(e){this.currentBatchIds.clear();return}for(const t of this.localFunctions.keys())this.currentBatchIds.has(t)||this.localFunctions.delete(t);this.currentBatchIds.clear()}clearRemote(){this.remoteFunctions.clear()}get localFunctionCount(){return this.localFunctions.size}get remoteFunctionCount(){return this.remoteFunctions.size}destroy(){this.localFunctions.clear(),this.remoteFunctions.clear(),this.currentBatchIds.clear()}}function ee(s,e,t=new WeakSet){if(typeof s=="function")return e.serialize(s);if(Array.isArray(s)){if(t.has(s))throw new Error("Circular reference detected in props - arrays cannot contain circular references");t.add(s);try{return s.map(n=>ee(n,e,t))}finally{t.delete(s)}}if(typeof s=="object"&&s!==null){if(t.has(s))throw new Error("Circular reference detected in props - objects cannot contain circular references");t.add(s);try{const n={};for(const[r,i]of Object.entries(s))Pe(r)&&(n[r]=ee(i,e,t));return n}finally{t.delete(s)}}return s}function te(s,e,t,n,r=new WeakSet){if(Q.isFunctionRef(s))return e.deserialize(s,t,n);if(Array.isArray(s)){if(r.has(s))throw new Error("Circular reference detected in serialized props");r.add(s);try{return s.map(i=>te(i,e,t,n,r))}finally{r.delete(s)}}if(typeof s=="object"&&s!==null){if(r.has(s))throw new Error("Circular reference detected in serialized props");r.add(s);try{const i={};for(const[o,a]of Object.entries(s))Pe(o)&&(i[o]=te(a,e,t,n,r));return i}finally{r.delete(s)}}return s}const pt=new Set(["__proto__"]);function Ee(s){return!pt.has(s)}function be(s,e=""){const t=[];for(const[n,r]of Object.entries(s)){const i=e?`${e}.${n}`:n;if(r!==null&&typeof r=="object"&&!Array.isArray(r))t.push(be(r,i));else{const o=encodeURIComponent(JSON.stringify(r));t.push(`${i}=${o}`)}}return t.filter(Boolean).join("&")}function ft(s){const e={};if(!s)return e;const t=s.split("&");for(const n of t){const[r,i]=n.split("=");if(!r||i===void 0)continue;let o;try{o=JSON.parse(decodeURIComponent(i))}catch{o=decodeURIComponent(i)}const a=r.split(".");if(a.some(d=>!Ee(d)))continue;let c=e;for(let d=0;d<a.length-1;d++){const g=a[d],y=c[g];(!Object.prototype.hasOwnProperty.call(c,g)||typeof y!="object"||y===null||Array.isArray(y))&&(c[g]={}),c=c[g]}const l=a[a.length-1];c[l]=o}return e}function mt(s){return typeof s=="object"&&s!==null&&s.__type__==="dotify"&&typeof s.__value__=="string"}function gt(s,e,t){const n={...b,...e},r={};for(const[i,o]of Object.entries(s)){if(o===void 0)continue;const a=n[i];r[i]=yt(o,a,t)}return r}function yt(s,e,t){if(typeof s=="function")return t.serialize(s);const n=e?.serialization??O.JSON;if(n===O.BASE64&&typeof s=="object"){const r=JSON.stringify(s);return{__type__:"base64",__value__:btoa(encodeURIComponent(r))}}return n===O.DOTIFY&&typeof s=="object"&&s!==null&&!Array.isArray(s)?{__type__:"dotify",__value__:be(s)}:ee(s,t)}function Re(s,e,t,n,r,i){const o={...b,...e},a={};for(const[c,l]of Object.entries(s)){if(!Ee(c))continue;const d=o[c];a[c]=wt(l,d,t,n,r,i)}return a}function wt(s,e,t,n,r,i){if(_t(s))try{const o=decodeURIComponent(atob(s.__value__));return JSON.parse(o)}catch{return s}if(mt(s))try{return ft(s.__value__)}catch{return s}return te(s,n,r,i)}function _t(s){return typeof s=="object"&&s!==null&&s.__type__==="base64"&&typeof s.__value__=="string"}class Pt{constructor(e,t,n){this.options=e,this.createPropContext=n,this.inputProps={...t};const r=this.inputProps,i=this.createPropContext(r);this.props=ge(r,this.options.props,i)}props;inputProps;pendingPropsUpdate=null;buildNextProps(e){const t={...this.inputProps,...e},n={...this.props,...e},r=this.createPropContext(n),i=ge(n,this.options.props,r);return ye(i,this.options.props),this.options.validate?.({props:i}),{nextInputProps:t,nextProps:i}}updateProps(e,t){return this.queuePropsUpdate(async()=>{const{nextInputProps:n,nextProps:r}=this.buildNextProps(e),i=t.resolveUrl(r),o=t.resolveUrlOrigin(i);t.assertStableRenderedOrigin(o),this.inputProps=n,this.props=r,t.isRendered()||t.syncTrustedDomainForUrl(i),t.shouldSendPropsToHost()&&await t.sendPropsUpdateToHost(r),t.emitPropsUpdated(r)},t.shouldSendPropsToHost)}queuePropsUpdate(e,t){if(!this.pendingPropsUpdate){const r=e();return t()&&this.trackPendingUpdate(r),r}const n=this.pendingPropsUpdate.then(e,e);return this.trackPendingUpdate(n),n}trackPendingUpdate(e){const t=e.then(()=>{},()=>{});this.pendingPropsUpdate=t,t.finally(()=>{this.pendingPropsUpdate===t&&(this.pendingPropsUpdate=null)})}}function S(s,e="100%"){return s===void 0?e:typeof s=="number"?`${s}px`:s}function V(s,e){if(s===void 0)return e;if(typeof s=="number")return s;const t=parseInt(s,10);return isNaN(t)?e:t}function Et(s){try{s.src="about:blank",s.parentNode?.removeChild(s)}catch{}}function bt(s,e){Ot(s,e)}function Rt(s){s.style.display="",s.style.visibility="visible"}function Se(s){s.style.display="none",s.style.visibility="hidden"}function St(s){try{s.focus(),s.contentWindow?.focus()}catch{}}function Ot(s,e){e.width!==void 0&&(s.style.width=S(e.width)),e.height!==void 0&&(s.style.height=S(e.height))}class se extends Error{constructor(e="Popup blocked by browser"){super(e),this.name="PopupOpenError"}}function vt(s){const{url:e,name:t,dimensions:n}=s,r=V(n.width,500),i=V(n.height,500),o=Math.floor(window.screenX+(window.outerWidth-r)/2),a=Math.floor(window.screenY+(window.outerHeight-i)/2),c=[`width=${r}`,`height=${i}`,`left=${o}`,`top=${a}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),l=window.open(e,t,c);if(!l||xt(l))throw new se;return l}function Ct(s){try{s.closed||s.close()}catch{}}function It(s){try{s.closed||s.focus()}catch{}}function xt(s){if(!s)return!0;try{return!!(s.closed||s.innerHeight===0||s.innerWidth===0)}catch{return!0}}function Dt(s,e,t={}){const{initialInterval:n=100,maxInterval:r=2e3,multiplier:i=1.5}=t;let o=n,a,c=!1;const l=()=>{try{e()}catch(g){console.error("Error in popup close callback:",g)}},d=()=>{if(!c){try{if(s.closed){l();return}}catch{l();return}o=Math.min(o*i,r),a=setTimeout(d,o)}};return a=setTimeout(d,o),()=>{c=!0,clearTimeout(a)}}function Tt(s,e){try{const t=V(e.width,s.outerWidth),n=V(e.height,s.outerHeight);s.resizeTo(t,n)}catch{}}const Oe="forgeframe-spinner-style";function Ut(s,e){const t=s.getElementById(Oe);if(t){const r=t.getAttribute("nonce");if(!e||r===e)return;t.remove()}const n=s.createElement("style");n.id=Oe,e&&n.setAttribute("nonce",e),n.textContent=`
|
|
1
|
+
(function(u,d){typeof exports=="object"&&typeof module<"u"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(u=typeof globalThis<"u"?globalThis:u||self,d(u.ForgeFrame={}))})(this,(function(u){"use strict";const d={IFRAME:"iframe",POPUP:"popup"},g={RENDER:"render",RENDERED:"rendered",PRERENDER:"prerender",PRERENDERED:"prerendered",DISPLAY:"display",ERROR:"error",CLOSE:"close",DESTROY:"destroy",PROPS:"props",RESIZE:"resize",FOCUS:"focus"},I={JSON:"json",BASE64:"base64",DOTIFY:"dotify"},L={REQUEST:"request",RESPONSE:"response"},h={INIT:"forgeframe_init",PROPS:"forgeframe_props",CLOSE:"forgeframe_close",RESIZE:"forgeframe_resize",FOCUS:"forgeframe_focus",SHOW:"forgeframe_show",HIDE:"forgeframe_hide",ERROR:"forgeframe_error",EXPORT:"forgeframe_export",CALL:"forgeframe_call",CONSUMER_EXPORT:"forgeframe_consumer_export",GET_SIBLINGS:"forgeframe_get_siblings"},M="__forgeframe__",z=(()=>{if("0.0.9".trim().length===0)throw new Error("ForgeFrame VERSION injection is missing. Configure __FORGEFRAME_VERSION__ in build/test tooling.");return"0.0.9"})();class _e{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const s=r=>(this.off(e,s),t(r));return this.on(e,s)}emit(e,t){const s=this.listeners.get(e);if(s)for(const r of s)try{const i=r(t);i&&typeof i=="object"&&"catch"in i&&typeof i.catch=="function"&&i.catch(o=>{console.error(`Error in async event handler for "${e}":`,o)})}catch(i){console.error(`Error in event handler for "${e}":`,i)}}off(e,t){if(!t){this.listeners.delete(e);return}const s=this.listeners.get(e);s&&(s.delete(t),s.size===0&&this.listeners.delete(e))}removeAllListeners(){this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size??0}}function Ge(){const n=Date.now().toString(36),e=Math.random().toString(36).slice(2,11);return`${n}_${e}`}function k(){return Math.random().toString(36).slice(2,11)}class Ze{tasks=[];cleaned=!1;register(e){if(this.cleaned){Promise.resolve().then(()=>e()).catch(t=>{console.error("Error in cleanup task:",t)});return}this.tasks.push(e)}async cleanup(){if(this.cleaned)return;this.cleaned=!0;const e=this.tasks.reverse();this.tasks=[];for(const t of e)try{await t()}catch(s){console.error("Error in cleanup task:",s)}}isCleaned(){return this.cleaned}reset(){this.tasks=[],this.cleaned=!1}}function Pe(){let n,e;return{promise:new Promise((s,r)=>{n=s,e=r}),resolve:n,reject:e}}function Qe(n,e,t="Operation timed out"){return new Promise((s,r)=>{const i=setTimeout(()=>{r(new Error(`${t} (${e}ms)`))},e);n.then(o=>{clearTimeout(i),s(o)}).catch(o=>{clearTimeout(i),r(o)})})}const x=new Map,et=200;function tt(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nt(n){if(!n.includes("*"))return null;const e=x.get(n);if(e)return e;const t=n.split("*").map(r=>tt(r)).join(".*"),s=new RegExp(`^${t}$`);if(x.size>=et){const r=x.keys().next().value;r&&x.delete(r)}return x.set(n,s),s}function st(n,e){return n.global||n.sticky?new RegExp(n.source,n.flags.replace(/[gy]/g,"")).test(e):n.test(e)}function W(n=window){try{return n.location.origin}catch{return""}}function Ee(n,e=window){try{return n.location.origin===e.location.origin}catch{return!1}}function v(n,e){if(typeof n=="string"){if(n==="*")return!0;const t=nt(n);return t?t.test(e):n===e}return n instanceof RegExp?st(n,e):Array.isArray(n)?n.some(t=>v(t,e)):!1}function ne(n){if(!n)return!0;try{return n.closed}catch{return!0}}function rt(n=window){try{return n.opener}catch{return null}}function it(n=window){try{const e=n.parent;return e&&e!==n?e:null}catch{return null}}function ot(n=window){try{return n.parent!==n}catch{return!0}}function at(n=window){try{return n.opener!==null&&n.opener!==void 0}catch{return!1}}const be=100,E=new Map;function ct(){const n=[];for(const[e,t]of E.entries())ne(t)&&n.push(e);for(const e of n)E.delete(e)}function lt(n,e){if(E.size>=be&&ct(),E.size>=be){const t=E.keys().next().value;t&&E.delete(t)}E.set(n,e)}function ut(n){E.delete(n)}function ht(n,e){return n.global||n.sticky?new RegExp(n.source,n.flags.replace(/[gy]/g,"")).test(e):n.test(e)}class w{_optional=!1;_nullable=!1;_default;"~standard"={version:1,vendor:"forgeframe",validate:e=>e===null?this._nullable?{value:null}:{issues:[{message:"Expected a value, got null"}]}:e===void 0?this._default!==void 0?{value:typeof this._default=="function"?this._default():this._default}:this._optional?{value:void 0}:{issues:[{message:"Required"}]}:this._validate(e)};optional(){const e=this._clone();return e._optional=!0,e}nullable(){const e=this._clone();return e._nullable=!0,e}default(e){const t=this._clone();return t._default=e,t}}class j extends w{_minLength;_maxLength;_pattern;_patternMessage;_trim=!1;_validate(e){if(typeof e!="string")return{issues:[{message:`Expected string, got ${typeof e}`}]};const t=this._trim?e.trim():e;return this._minLength!==void 0&&t.length<this._minLength?{issues:[{message:`String must be at least ${this._minLength} characters`}]}:this._maxLength!==void 0&&t.length>this._maxLength?{issues:[{message:`String must be at most ${this._maxLength} characters`}]}:this._pattern&&!ht(this._pattern,t)?{issues:[{message:this._patternMessage||`String must match pattern ${this._pattern}`}]}:{value:t}}_clone(){const e=new j;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._minLength=this._minLength,e._maxLength=this._maxLength,e._pattern=this._pattern,e._patternMessage=this._patternMessage,e._trim=this._trim,e}min(e){const t=this._clone();return t._minLength=e,t}max(e){const t=this._clone();return t._maxLength=e,t}length(e){const t=this._clone();return t._minLength=e,t._maxLength=e,t}pattern(e,t){const s=this._clone();return s._pattern=e,s._patternMessage=t,s}email(){return this.pattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/,"Invalid email address")}url(){return this.pattern(/^https?:\/\/.+/,"Invalid URL")}uuid(){return this.pattern(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"Invalid UUID")}trim(){const e=this._clone();return e._trim=!0,e}nonempty(){const e=this._clone();return e._minLength=1,e}}class B extends w{_min;_max;_int=!1;_validate(e){return typeof e!="number"||Number.isNaN(e)?{issues:[{message:`Expected number, got ${typeof e}`}]}:this._int&&!Number.isInteger(e)?{issues:[{message:"Expected integer"}]}:this._min!==void 0&&e<this._min?{issues:[{message:`Number must be >= ${this._min}`}]}:this._max!==void 0&&e>this._max?{issues:[{message:`Number must be <= ${this._max}`}]}:{value:e}}_clone(){const e=new B;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._min=this._min,e._max=this._max,e._int=this._int,e}min(e){const t=this._clone();return t._min=e,t}max(e){const t=this._clone();return t._max=e,t}int(){const e=this._clone();return e._int=!0,e}positive(){const e=this._clone();return e._min=Number.MIN_VALUE,e}nonnegative(){const e=this._clone();return e._min=0,e}negative(){const e=this._clone();return e._max=-Number.MIN_VALUE,e}}class V extends w{_validate(e){return typeof e!="boolean"?{issues:[{message:`Expected boolean, got ${typeof e}`}]}:{value:e}}_clone(){const e=new V;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class q extends w{_validate(e){return typeof e!="function"?{issues:[{message:`Expected function, got ${typeof e}`}]}:{value:e}}_clone(){const e=new q;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class T extends w{_itemSchema;_minLength;_maxLength;_validate(e){if(!Array.isArray(e))return{issues:[{message:`Expected array, got ${typeof e}`}]};if(this._minLength!==void 0&&e.length<this._minLength)return{issues:[{message:`Array must have at least ${this._minLength} items`}]};if(this._maxLength!==void 0&&e.length>this._maxLength)return{issues:[{message:`Array must have at most ${this._maxLength} items`}]};if(this._itemSchema){const t=[];for(let s=0;s<e.length;s++){const r=this._itemSchema["~standard"].validate(e[s]);if(r instanceof Promise)throw new Error("Async schema validation is not supported. Use synchronous schemas.");if(r.issues)return{issues:r.issues.map(i=>({...i,path:[s,...i.path||[]]}))};t.push(r.value)}return{value:t}}return{value:e}}_clone(){const e=new T;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._itemSchema=this._itemSchema,e._minLength=this._minLength,e._maxLength=this._maxLength,e}of(e){const t=new T;return t._optional=this._optional,t._nullable=this._nullable,t._itemSchema=e,t._minLength=this._minLength,t._maxLength=this._maxLength,t}min(e){const t=this._clone();return t._minLength=e,t}max(e){const t=this._clone();return t._maxLength=e,t}nonempty(){return this.min(1)}}class U extends w{_shape;_strict=!1;_validate(e){if(typeof e!="object"||e===null||Array.isArray(e))return{issues:[{message:`Expected object, got ${Array.isArray(e)?"array":typeof e}`}]};const t=e,s={};if(this._shape){if(this._strict){const r=new Set(Object.keys(this._shape));for(const i of Object.keys(t))if(!r.has(i))return{issues:[{message:`Unknown key: ${i}`,path:[i]}]}}for(const[r,i]of Object.entries(this._shape)){const o=i["~standard"].validate(t[r]);if(o instanceof Promise)throw new Error("Async schema validation is not supported. Use synchronous schemas.");if(o.issues)return{issues:o.issues.map(a=>({...a,path:[r,...a.path||[]]}))};s[r]=o.value}if(!this._strict)for(const r of Object.keys(t))r in this._shape||(s[r]=t[r]);return{value:s}}return{value:e}}_clone(){const e=new U;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e._shape=this._shape,e._strict=this._strict,e}shape(e){const t=new U;return t._optional=this._optional,t._nullable=this._nullable,t._shape=e,t._strict=this._strict,t}strict(){const e=this._clone();return e._strict=!0,e}}class J extends w{_value;constructor(e){super(),this._value=e}_validate(e){return e!==this._value?{issues:[{message:`Expected ${JSON.stringify(this._value)}, got ${JSON.stringify(e)}`}]}:{value:e}}_clone(){const e=new J(this._value);return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class K extends w{_values;_valueSet;constructor(e){super(),this._values=e,this._valueSet=new Set(e)}_validate(e){return this._valueSet.has(e)?{value:e}:{issues:[{message:`Expected one of [${this._values.map(t=>JSON.stringify(t)).join(", ")}], got ${JSON.stringify(e)}`}]}}_clone(){const e=new K(this._values);return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}class Y extends w{constructor(){super(),this._nullable=!0}_validate(e){return{value:e}}_clone(){const e=new Y;return e._optional=this._optional,e._nullable=this._nullable,e._default=this._default,e}}const f={string:()=>new j,number:()=>new B,boolean:()=>new V,function:()=>new q,array:()=>new T,object:()=>new U,literal:n=>new J(n),enum:n=>new K(n),any:()=>new Y},b={uid:{schema:f.string().optional(),sendToHost:!0},tag:{schema:f.string().optional(),sendToHost:!0},dimensions:{schema:f.object().default(()=>({width:"100%",height:"100%"})),sendToHost:!1},timeout:{schema:f.number().default(1e4),sendToHost:!1},cspNonce:{schema:f.string().optional(),sendToHost:!0},onDisplay:{schema:f.function().optional(),sendToHost:!1},onRendered:{schema:f.function().optional(),sendToHost:!1},onRender:{schema:f.function().optional(),sendToHost:!1},onPrerendered:{schema:f.function().optional(),sendToHost:!1},onPrerender:{schema:f.function().optional(),sendToHost:!1},onClose:{schema:f.function().optional(),sendToHost:!1},onDestroy:{schema:f.function().optional(),sendToHost:!1},onResize:{schema:f.function().optional(),sendToHost:!1},onFocus:{schema:f.function().optional(),sendToHost:!1},onError:{schema:f.function().optional(),sendToHost:!1},onProps:{schema:f.function().optional(),sendToHost:!1}};function O(n){return typeof n=="object"&&n!==null&&"~standard"in n&&typeof n["~standard"]=="object"&&n["~standard"]!==null&&n["~standard"].version===1&&typeof n["~standard"].vendor=="string"&&typeof n["~standard"].validate=="function"}function dt(n,e,t){const s=n["~standard"].validate(e);if(s instanceof Promise)throw new Error(`Prop "${t}" uses an async schema. ForgeFrame only supports synchronous schema validation. Please use a synchronous schema or remove async operations (like database lookups) from your schema definition.`);if(s.issues){const r=s.issues.map(i=>`${pt(i.path,t)}: ${i.message}`);throw new Error(`Validation failed: ${r.join("; ")}`)}return s.value}function pt(n,e){if(!n||n.length===0)return e;const t=n.map(s=>{if(typeof s=="object"&&s!==null){if("key"in s&&s.key!==void 0)return String(s.key);if("index"in s&&typeof s.index=="number")return String(s.index)}return String(s)});return`${e}.${t.join(".")}`}function N(n){const e=O(n);return{isDirectSchema:e,definition:e?{schema:n}:n}}function Oe(n,e,t){const s={...b,...e},r={};for(const[i,o]of Object.entries(s)){const{definition:a}=N(o);let c;const l=a.alias,y=i in n,p=l&&l in n;if(y)c=n[i];else if(p)c=n[l];else if(a.value)c=a.value(t);else if(a.default!==void 0)c=typeof a.default=="function"?a.default(t):a.default;else if(a.schema&&O(a.schema)){const m=a.schema["~standard"].validate(void 0);!(m instanceof Promise)&&!m.issues&&(c=m.value)}c!==void 0&&a.decorate&&(c=a.decorate({value:c,props:r})),r[i]=c}return r}function F(n,e){const t={...b,...e};for(const[s,r]of Object.entries(t)){const{isDirectSchema:i,definition:o}=N(r);let a=n[s];if(o.required&&a===void 0)throw new Error(`Prop "${s}" is required but was not provided`);if(o.schema&&O(o.schema))(a!==void 0||i)&&(a=dt(o.schema,a,s),n[s]=a);else if(a===void 0)continue;o.validate&&o.validate({value:a,props:n})}}function Re(n,e,t,s){const r={...b,...e},i={};for(const[o,a]of Object.entries(r)){const{definition:c}=N(a),l=n[o];if(c.sendToHost===!1||c.sameDomain&&!s)continue;if(c.trustedDomains){const p=c.trustedDomains;if(!v(p,t))continue}let y=l;c.hostDecorate&&l!==void 0&&(y=c.hostDecorate({value:l,props:n})),i[o]=y}return i}function ft(n,e){const t=new URLSearchParams,s={...b,...e};for(const[r,i]of Object.entries(s)){const{definition:o}=N(i),a=n[r];if(a===void 0||typeof a=="function"||!o.queryParam)continue;const c=typeof o.queryParam=="string"?o.queryParam:r;let l;typeof o.queryParam=="function"?l=o.queryParam({value:a}):typeof a=="object"?l=JSON.stringify(a):l=String(a),t.set(c,l)}return t}function mt(n,e){const t=new URLSearchParams,s={...b,...e};for(const[r,i]of Object.entries(s)){const{definition:o}=N(i),a=n[r];if(a===void 0||typeof a=="function"||!o.bodyParam)continue;const c=typeof o.bodyParam=="string"?o.bodyParam:r;let l;typeof o.bodyParam=="function"?l=o.bodyParam({value:a}):typeof a=="object"?l=JSON.stringify(a):l=String(a),t.set(c,l)}return t}const Ce=500,gt=new Set(["__proto__"]);function Se(n){return!gt.has(n)}class se{constructor(e){this.messenger=e,this.setupCallHandler()}localFunctions=new Map;remoteFunctions=new Map;currentBatchIds=new Set;serialize(e,t){if(this.localFunctions.size>=Ce){const r=this.localFunctions.keys().next().value;r&&this.localFunctions.delete(r)}const s=k();return this.localFunctions.set(s,e),this.currentBatchIds.add(s),{__type__:"function",__id__:s,__name__:t||e.name||"anonymous"}}deserialize(e,t,s){const r=`${e.__id__}`,i=this.remoteFunctions.get(r);if(i)return i;if(this.remoteFunctions.size>=Ce){const a=this.remoteFunctions.keys().next().value;a&&this.remoteFunctions.delete(a)}const o=async(...a)=>this.messenger.send(t,s,h.CALL,{id:e.__id__,args:a});return Object.defineProperty(o,"name",{value:e.__name__,configurable:!0}),this.remoteFunctions.set(r,o),o}static isFunctionRef(e){return typeof e=="object"&&e!==null&&e.__type__==="function"&&typeof e.__id__=="string"}setupCallHandler(){this.messenger.on(h.CALL,async({id:e,args:t})=>{const s=this.localFunctions.get(e);if(!s)throw new Error(`Function with id "${e}" not found`);return s(...t)})}removeLocal(e){this.localFunctions.delete(e)}startBatch(){this.currentBatchIds.clear()}finishBatch(e=!1){if(e){this.currentBatchIds.clear();return}for(const t of this.localFunctions.keys())this.currentBatchIds.has(t)||this.localFunctions.delete(t);this.currentBatchIds.clear()}clearRemote(){this.remoteFunctions.clear()}get localFunctionCount(){return this.localFunctions.size}get remoteFunctionCount(){return this.remoteFunctions.size}destroy(){this.localFunctions.clear(),this.remoteFunctions.clear(),this.currentBatchIds.clear()}}function re(n,e,t=new WeakSet){if(typeof n=="function")return e.serialize(n);if(Array.isArray(n)){if(t.has(n))throw new Error("Circular reference detected in props - arrays cannot contain circular references");t.add(n);try{return n.map(s=>re(s,e,t))}finally{t.delete(n)}}if(typeof n=="object"&&n!==null){if(t.has(n))throw new Error("Circular reference detected in props - objects cannot contain circular references");t.add(n);try{const s={};for(const[r,i]of Object.entries(n))Se(r)&&(s[r]=re(i,e,t));return s}finally{t.delete(n)}}return n}function ie(n,e,t,s,r=new WeakSet){if(se.isFunctionRef(n))return e.deserialize(n,t,s);if(Array.isArray(n)){if(r.has(n))throw new Error("Circular reference detected in serialized props");r.add(n);try{return n.map(i=>ie(i,e,t,s,r))}finally{r.delete(n)}}if(typeof n=="object"&&n!==null){if(r.has(n))throw new Error("Circular reference detected in serialized props");r.add(n);try{const i={};for(const[o,a]of Object.entries(n))Se(o)&&(i[o]=ie(a,e,t,s,r));return i}finally{r.delete(n)}}return n}const yt=new Set(["__proto__"]),oe="__forgeframe.dotify_path__:";function De(n){return!yt.has(n)}function Ie(n,e=[]){const t=[];for(const[s,r]of Object.entries(n)){const i=[...e,s];if(r!==null&&typeof r=="object"&&!Array.isArray(r))t.push(Ie(r,i));else{const o=`${oe}${encodeURIComponent(JSON.stringify(i))}`,a=encodeURIComponent(JSON.stringify(r));t.push(`${o}=${a}`)}}return t.filter(Boolean).join("&")}function wt(n){const e={};if(!n)return e;const t=n.split("&");for(const s of t){const r=s.indexOf("=");if(r===-1)continue;const i=s.slice(0,r),o=s.slice(r+1);if(!i||o===void 0)continue;let a;try{a=JSON.parse(decodeURIComponent(o))}catch{a=decodeURIComponent(o)}const c=_t(i);if(c.some(p=>!De(p)))continue;let l=e;for(let p=0;p<c.length-1;p++){const m=c[p],D=l[m];(!Object.prototype.hasOwnProperty.call(l,m)||typeof D!="object"||D===null||Array.isArray(D))&&(l[m]={}),l=l[m]}const y=c[c.length-1];l[y]=a}return e}function _t(n){if(!n.startsWith(oe))throw new Error("Invalid DOTIFY path framing");const e=decodeURIComponent(n.slice(oe.length)),t=JSON.parse(e);if(Array.isArray(t)&&t.length>0&&t.every(s=>typeof s=="string"))return t;throw new Error("Invalid DOTIFY path framing")}function Pt(n){return typeof n=="object"&&n!==null&&n.__type__==="dotify"&&typeof n.__value__=="string"}function Et(n,e,t){const s={...b,...e},r={};for(const[i,o]of Object.entries(n)){if(o===void 0)continue;const a=s[i];r[i]=bt(o,a,t)}return r}function bt(n,e,t){if(typeof n=="function")return t.serialize(n);const s=e?.serialization??I.JSON;if(s===I.BASE64&&typeof n=="object"){const r=JSON.stringify(n);return{__type__:"base64",__value__:btoa(encodeURIComponent(r))}}return s===I.DOTIFY&&typeof n=="object"&&n!==null&&!Array.isArray(n)?{__type__:"dotify",__value__:Ie(n)}:re(n,t)}function xe(n,e,t,s,r,i){const o={...b,...e},a={};for(const[c,l]of Object.entries(n)){if(!De(c))continue;const y=o[c];a[c]=Ot(l,y,t,s,r,i)}return a}function Ot(n,e,t,s,r,i){if(Rt(n))try{const o=decodeURIComponent(atob(n.__value__));return JSON.parse(o)}catch{return n}if(Pt(n))try{return wt(n.__value__)}catch{return n}return ie(n,s,r,i)}function Rt(n){return typeof n=="object"&&n!==null&&n.__type__==="base64"&&typeof n.__value__=="string"}class Ct{constructor(e,t,s){this.options=e,this.createPropContext=s,this.inputProps={...t};const r=this.inputProps,i=this.createPropContext(r);this.props=Oe(r,this.options.props,i)}props;inputProps;pendingPropsUpdate=null;buildNextProps(e){const t={...this.inputProps,...e},s={...this.props,...e},r=this.createPropContext(s),i=Oe(s,this.options.props,r);return F(i,this.options.props),this.options.validate?.({props:i}),{nextInputProps:t,nextProps:i}}updateProps(e,t){return this.queuePropsUpdate(async()=>{const{nextInputProps:s,nextProps:r}=this.buildNextProps(e),i=t.resolveUrl(r),o=t.resolveUrlOrigin(i);t.assertStableRenderedOrigin(o),this.inputProps=s,this.props=r,t.isRendered()||t.syncTrustedDomainForUrl(i),t.shouldSendPropsToHost()&&await t.sendPropsUpdateToHost(r),t.emitPropsUpdated(r)},t.shouldSendPropsToHost)}syncCurrentPropsToHost(e){return this.queuePropsUpdate(async()=>{e.shouldSendPropsToHost()&&await e.sendPropsUpdateToHost(this.props)},e.shouldSendPropsToHost)}queuePropsUpdate(e,t){if(!this.pendingPropsUpdate){const r=e();return t()&&this.trackPendingUpdate(r),r}const s=this.pendingPropsUpdate.then(e,e);return this.trackPendingUpdate(s),s}trackPendingUpdate(e){const t=e.then(()=>{},()=>{});this.pendingPropsUpdate=t,t.finally(()=>{this.pendingPropsUpdate===t&&(this.pendingPropsUpdate=null)})}}function S(n,e="100%"){return n===void 0?e:typeof n=="number"?`${n}px`:n}function X(n,e){if(n===void 0)return e;if(typeof n=="number")return n;const t=parseInt(n,10);return isNaN(t)?e:t}function St(n){const{name:e,dimensions:t,attributes:s={},style:r={}}=n,i=document.createElement("iframe");return i.name=e,i.setAttribute("frameborder","0"),i.setAttribute("allowtransparency","true"),i.setAttribute("scrolling","auto"),Te(i,t),Ut(i,s),Tt(i,r),Nt(i,s),i}function Dt(n){try{n.src="about:blank",n.parentNode?.removeChild(n)}catch{}}function It(n,e){Te(n,e)}function xt(n){n.style.display="",n.style.visibility="visible"}function ve(n){n.style.display="none",n.style.visibility="hidden"}function vt(n){try{n.focus(),n.contentWindow?.focus()}catch{}}function Te(n,e){e.width!==void 0&&(n.style.width=S(e.width)),e.height!==void 0&&(n.style.height=S(e.height))}function Tt(n,e){for(const[t,s]of Object.entries(e)){if(s===void 0)continue;const r=typeof s=="number"?`${s}px`:s;n.style.setProperty(t.replace(/([A-Z])/g,"-$1").toLowerCase(),r)}}function Ut(n,e){for(const[t,s]of Object.entries(e))if(s!==void 0){if(typeof s=="boolean"){s&&n.setAttribute(t,"");continue}n.setAttribute(t,s)}}function Nt(n,e){e.sandbox||n.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox")}class ae extends Error{constructor(e="Popup blocked by browser"){super(e),this.name="PopupOpenError"}}function Ft(n){const{url:e,name:t,dimensions:s}=n,r=X(s.width,500),i=X(s.height,500),o=Math.floor(window.screenX+(window.outerWidth-r)/2),a=Math.floor(window.screenY+(window.outerHeight-i)/2),c=[`width=${r}`,`height=${i}`,`left=${o}`,`top=${a}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),l=window.open(e,t,c);if(!l||At(l))throw new ae;return l}function Ht(n){try{n.closed||n.close()}catch{}}function $t(n){try{n.closed||n.focus()}catch{}}function At(n){if(!n)return!0;try{return!!(n.closed||n.innerHeight===0||n.innerWidth===0)}catch{return!0}}function Lt(n,e,t={}){const{initialInterval:s=100,maxInterval:r=2e3,multiplier:i=1.5}=t;let o=s,a,c=!1;const l=()=>{try{e()}catch(p){console.error("Error in popup close callback:",p)}},y=()=>{if(!c){try{if(n.closed){l();return}}catch{l();return}o=Math.min(o*i,r),a=setTimeout(y,o)}};return a=setTimeout(y,o),()=>{c=!0,clearTimeout(a)}}function Mt(n,e){try{const t=X(e.width,n.outerWidth),s=X(e.height,n.outerHeight);n.resizeTo(t,s)}catch{}}const Ue="forgeframe-spinner-style";function zt(n,e){const t=n.getElementById(Ue);if(t){const r=t.getAttribute("nonce");if(!e||r===e)return;t.remove()}const s=n.createElement("style");s.id=Ue,e&&s.setAttribute("nonce",e),s.textContent=`
|
|
2
2
|
@keyframes forgeframe-spin {
|
|
3
3
|
to { transform: rotate(360deg); }
|
|
4
4
|
}
|
|
5
|
-
`,(s.head??s.documentElement).appendChild(n)}function Nt(s){const{doc:e,dimensions:t,uid:n,tag:r}=s,i=e.createElement("div");return i.id=`forgeframe-container-${n}`,i.setAttribute("data-forgeframe-tag",r),Object.assign(i.style,{display:"inline-block",position:"relative",width:S(t.width),height:S(t.height),overflow:"hidden"}),i}function Ft(s){const{doc:e,dimensions:t,cspNonce:n}=s;Ut(e,n);const r=e.createElement("div");Object.assign(r.style,{display:"flex",alignItems:"center",justifyContent:"center",width:S(t.width),height:S(t.height),backgroundColor:"#f5f5f5",position:"absolute",top:"0",left:"0",zIndex:"100"});const i=e.createElement("div");return Object.assign(i.style,{width:"40px",height:"40px",border:"3px solid #e0e0e0",borderTopColor:"#3498db",borderRadius:"50%",animation:"forgeframe-spin 1s linear infinite"}),r.appendChild(i),r}function Ht(s,e=200){return new Promise(t=>{s.style.opacity="0",s.style.transition=`opacity ${e}ms ease-in`,s.offsetHeight,s.style.opacity="1",setTimeout(t,e)})}function $t(s,e=200){return new Promise(t=>{s.style.transition=`opacity ${e}ms ease-out`,s.style.opacity="0",setTimeout(t,e)})}async function At(s,e,t){e&&(await $t(e,150),e.remove()),t.style.display="",t.style.visibility="visible",t.style.opacity="0",await Ht(t,150)}class Lt{constructor(e,t,n,r,i){this.options=e,this.uid=t,this.getProps=n,this.resolveDimensions=r,this.callbacks=i,this.context=this.options.defaultContext}context;iframe=null;container=null;prerenderElement=null;resolveContainer(e){if(!e)throw new Error("Container is required for rendering");if(typeof e=="string"){const t=document.querySelector(e);if(!t)throw new Error(`Container "${e}" not found`);return t}return e}async prerender(e,t){if(!this.container)return;const n=this.getProps(),r=this.options.prerenderTemplate??Ft,i=this.options.containerTemplate??Nt,o=this.resolveDimensions(),a=n.cspNonce;if(this.context===p.IFRAME){const g=t();this.iframe=e(g),Se(this.iframe)}const c={uid:this.uid,tag:this.options.tag,context:this.context,dimensions:o,props:n,doc:document,container:this.container,frame:this.iframe,prerenderFrame:null,close:()=>this.callbacks.close(),focus:()=>this.callbacks.focus(),cspNonce:a};this.prerenderElement=r(c);const l={uid:this.uid,tag:this.options.tag,context:this.context,dimensions:o,props:n,doc:document,container:this.container,frame:this.iframe,prerenderFrame:this.prerenderElement,close:()=>this.callbacks.close(),focus:()=>this.callbacks.focus(),cspNonce:a},d=i(l);d&&(this.container.appendChild(d),this.container=d),this.prerenderElement&&!this.prerenderElement.parentNode&&this.container.appendChild(this.prerenderElement),this.iframe&&!this.iframe.parentNode&&this.container.appendChild(this.iframe)}createIframeElement(e){const t=document.createElement("iframe"),n=this.resolveDimensions(),r=this.getProps(),i=typeof this.options.attributes=="function"?this.options.attributes(r):this.options.attributes??{},o=typeof this.options.style=="function"?this.options.style(r):this.options.style??{};t.name=e,t.setAttribute("frameborder","0"),t.setAttribute("allowtransparency","true"),t.setAttribute("scrolling","auto"),n.width!==void 0&&(t.style.width=typeof n.width=="number"?`${n.width}px`:n.width),n.height!==void 0&&(t.style.height=typeof n.height=="number"?`${n.height}px`:n.height);for(const[a,c]of Object.entries(i))c!==void 0&&(typeof c=="boolean"?c&&t.setAttribute(a,""):t.setAttribute(a,c));for(const[a,c]of Object.entries(o)){if(c===void 0)continue;const l=typeof c=="number"?`${c}px`:c;t.style.setProperty(a.replace(/([A-Z])/g,"-$1").toLowerCase(),String(l))}return i.sandbox||t.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"),t}open(e){const t=e.buildUrl(e.baseUrl),n=e.buildBodyParams(),r=n.toString().length>0;if(this.context===p.IFRAME){if(!this.iframe)throw new Error("Iframe not created during prerender");return r?e.submitBodyForm(this.iframe.name,t,n):this.iframe.src=t,this.iframe.contentWindow}const i=e.buildWindowName(),o=vt({url:r?"about:blank":t,name:i,dimensions:this.resolveDimensions()});r&&e.submitBodyForm(i,t,n);const a=Dt(o,()=>{e.onPopupClose()});return e.registerCleanup(a),o}async swapPrerenderContentIfNeeded(){this.context===p.IFRAME&&this.iframe&&this.container&&(await At(this.container,this.prerenderElement,this.iframe),this.prerenderElement=null)}submitBodyForm(e,t,n){const r=this.container?.ownerDocument??document,i=r.body??r.documentElement;if(!i)throw new Error("Document root is unavailable for bodyParam form submission");const o=r.createElement("form");o.method="POST",o.action=t,o.target=e,o.style.display="none";for(const[a,c]of n.entries()){const l=r.createElement("input");l.type="hidden",l.name=a,l.value=c,o.appendChild(l)}i.appendChild(o);try{o.submit()}finally{o.remove()}}focus(e){this.context===p.IFRAME&&this.iframe?St(this.iframe):this.context===p.POPUP&&e&&It(e)}resize(e,t){this.context===p.IFRAME&&this.iframe?bt(this.iframe,e):this.context===p.POPUP&&t&&Tt(t,e)}show(){this.context===p.IFRAME&&this.iframe&&Rt(this.iframe)}hide(){this.context===p.IFRAME&&this.iframe&&Se(this.iframe)}destroy(e){this.iframe&&(Et(this.iframe),this.iframe=null),this.context===p.POPUP&&e&&Ct(e),this.prerenderElement&&(this.prerenderElement.remove(),this.prerenderElement=null)}}const ne="forgeframe:";function re(s){return ne+JSON.stringify(s)}function zt(s){if(typeof s!="string"||!s.startsWith(ne))return null;try{const e=s.slice(ne.length),t=JSON.parse(e);return!t.id||!t.type||!t.name||!t.source?null:t}catch{return null}}function ve(s,e,t,n){return{id:s,type:H.REQUEST,name:e,data:t,source:n}}function kt(s,e,t,n){return{id:s,type:H.RESPONSE,name:"response",data:e,source:t,error:n?{message:n.message,stack:n.stack}:void 0}}function Mt(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wt(s){if(!s.includes("*"))return null;const e=s.split("*").map(t=>Mt(t)).join(".*");return new RegExp(`^${e}$`)}function Bt(s,e){return s.global||s.sticky?new RegExp(s.source,s.flags.replace(/[gy]/g,"")).test(e):s.test(e)}class Ce{constructor(e,t=window,n=window.location.origin,r){this.uid=e,this.win=t,this.domain=n,this.allowedOrigins.add(n),r&&this.addTrustedDomain(r),this.setupListener()}pending=new Map;handlers=new Map;listener=null;destroyed=!1;allowedOrigins=new Set;allowedOriginPatterns=[];wildcardPatternRegistry=new Map;sourceUidRegistry=new WeakMap;addTrustedDomain(e){if(Array.isArray(e))for(const t of e)this.addTrustedDomain(t);else if(e instanceof RegExp)this.allowedOriginPatterns.push(e);else{const t=Wt(e);t?this.wildcardPatternRegistry.has(e)||(this.wildcardPatternRegistry.set(e,t),this.allowedOriginPatterns.push(t)):this.allowedOrigins.add(e)}}removeTrustedDomain(e){if(Array.isArray(e))for(const t of e)this.removeTrustedDomain(t);else if(e instanceof RegExp)this.allowedOriginPatterns=this.allowedOriginPatterns.filter(t=>t!==e);else{const t=this.wildcardPatternRegistry.get(e);t&&(this.allowedOriginPatterns=this.allowedOriginPatterns.filter(n=>n!==t),this.wildcardPatternRegistry.delete(e)),this.allowedOrigins.delete(e)}}isOriginTrusted(e){if(this.allowedOrigins.has(e))return!0;for(const t of this.allowedOriginPatterns)if(Bt(t,e))return!0;return!1}resolveVerifiedSource(e,t,n){const r=e,i=this.sourceUidRegistry.get(r);if(i)return{uid:i,domain:t};const o=n&&typeof n.uid=="string"&&n.uid.length>0?n.uid:A();return this.sourceUidRegistry.set(r,o),{uid:o,domain:t}}async send(e,t,n,r,i=1e4){if(this.destroyed)throw new Error("Messenger has been destroyed");const o=A(),a=ve(o,n,r,{uid:this.uid,domain:this.domain}),c=fe(),l=setTimeout(()=>{this.pending.delete(o),c.reject(new Error(`Message "${n}" timed out after ${i}ms`))},i);this.pending.set(o,{deferred:c,timeout:l});try{e.postMessage(re(a),t)}catch(d){throw this.pending.delete(o),clearTimeout(l),d}return c.promise}post(e,t,n,r){if(this.destroyed)throw new Error("Messenger has been destroyed");const i=A(),o=ve(i,n,r,{uid:this.uid,domain:this.domain});e.postMessage(re(o),t)}on(e,t){return this.handlers.set(e,t),()=>this.handlers.delete(e)}setupListener(){this.listener=e=>{if(e.source===this.win||!this.isOriginTrusted(e.origin))return;const t=zt(e.data);if(!t)return;const n=e.source;!n||typeof n.postMessage!="function"||this.handleMessage(t,n,e.origin)},this.win.addEventListener("message",this.listener)}async handleMessage(e,t,n){if(e.type===H.RESPONSE){const r=this.pending.get(e.id);if(r)if(this.pending.delete(e.id),clearTimeout(r.timeout),e.error){const i=new Error(e.error.message);i.stack=e.error.stack,r.deferred.reject(i)}else r.deferred.resolve(e.data);return}if(e.type===H.REQUEST){const r=this.handlers.get(e.name);if(!r)return;let i,o;try{const c=this.resolveVerifiedSource(t,n,e.source);i=await r(e.data,c)}catch(c){o=c instanceof Error?c:new Error(String(c))}const a=kt(e.id,i,{uid:this.uid,domain:this.domain},o);try{t.postMessage(re(a),n)}catch{}}}destroy(){if(!this.destroyed){this.destroyed=!0,this.listener&&(this.win.removeEventListener("message",this.listener),this.listener=null);for(const e of this.pending.values())clearTimeout(e.timeout),e.deferred.reject(new Error("Messenger destroyed"));this.pending.clear(),this.handlers.clear()}}isDestroyed(){return this.destroyed}}const Ie=32*1024;function jt(s){const e=Vt(s);return`${$}${e}`}function xe(s){if(!s||!s.startsWith($))return null;const e=s.slice($.length);return Kt(e)}function ie(s=window){try{return s.name.startsWith($)}catch{return!1}}function oe(s,e=window){return xe(e.name)?.tag===s}function Vt(s){try{const e=JSON.stringify(s),t=btoa(encodeURIComponent(e)),n=new Blob([t]).size;if(n>Ie)throw new Error(`Payload size (${Math.round(n/1024)}KB) exceeds maximum allowed size (${Ie/1024}KB). Consider reducing the amount of data passed via props.`);return t}catch(e){throw e instanceof Error&&e.message.includes("Payload size")?e:new Error(`Failed to encode payload: ${e}`)}}function Kt(s){try{const e=decodeURIComponent(atob(s));return JSON.parse(e)}catch{return null}}function qt(s){return{uid:s.uid,tag:s.tag,version:Y,context:s.context,consumerDomain:s.consumerDomain,props:s.props,exports:s.exports,children:s.children}}function Jt(s=window){return xe(s.name)}class Xt{constructor(e,t,n,r){this.uid=e,this.options=t,this.resolveUrl=n,this.resolveUrlOrigin=r;const i=this.buildTrustedDomains();this.messenger=new Ce(this.uid,window,G(),i),this.bridge=new Q(this.messenger)}messenger;bridge;hostWindow=null;openedHostDomain=null;dynamicUrlTrustedOrigin=null;initPromise=null;hostInitialized=!1;buildTrustedDomains(){const e=[],t=this.resolveUrlOrigin(this.resolveUrl());if(t&&(e.push(t),this.dynamicUrlTrustedOrigin=t),this.options.domain&&(typeof this.options.domain=="string"?e.push(this.options.domain):Array.isArray(this.options.domain)?e.push(...this.options.domain):this.options.domain instanceof RegExp&&e.push(this.options.domain)),e.length!==0)return e.length===1?e[0]:e}isExplicitDomainTrust(e){return this.options.domain?C(this.options.domain,e):!1}syncTrustedDomainForUrl(e){const t=this.resolveUrlOrigin(e);if(!t)return;const n=this.dynamicUrlTrustedOrigin;n&&n!==t&&!this.isExplicitDomainTrust(n)&&this.messenger.removeTrustedDomain(n),this.messenger.addTrustedDomain(t),this.dynamicUrlTrustedOrigin=t}getHostDomain(){return this.openedHostDomain?this.openedHostDomain:this.resolveUrlOrigin(this.resolveUrl())??"*"}isHostConnected(){return!!(this.hostWindow&&!Z(this.hostWindow))}serializePropsForHost(e,t,n){this.bridge.startBatch();const r=n?.finishBatch??!0;try{const i=gt(e,t,this.bridge);return r&&this.bridge.finishBatch(),i}catch(i){throw this.bridge.finishBatch(!0),i}}async sendPropsUpdateToHost(e,t){if(!this.hostWindow||Z(this.hostWindow))return;const n=this.getHostDomain(),r=we(e,t,n,Qe(this.hostWindow)),i=this.serializePropsForHost(r,t,{finishBatch:!1});try{await this.messenger.send(this.hostWindow,n,h.PROPS,i),this.bridge.finishBatch()}catch(o){throw this.bridge.finishBatch(!0),o}}buildWindowName(e){const t=e.hostDomain??this.getHostDomain(),n=we(e.props,e.propDefinitions,t,!1),r=this.serializePropsForHost(n,e.propDefinitions),i=qt({uid:this.uid,tag:e.tag,context:e.context,consumerDomain:G(),props:r,exports:e.exports,children:e.children});return jt(i)}async waitForHost(e,t,n){if(this.hostInitialized)return;const r=fe();this.initPromise=r;try{await Je(r.promise,e,`Host component "${t}" (uid: ${this.uid}) did not initialize within ${e}ms. Check that the host page loads correctly and calls the initialization code.`)}catch(i){throw n(i),i}finally{this.initPromise===r&&(this.initPromise=null)}}setupMessageHandlers(e){this.messenger.on(h.INIT,()=>(this.hostInitialized=!0,this.initPromise&&this.initPromise.resolve(),{success:!0})),this.messenger.on(h.CLOSE,async()=>(await e.onClose(),{success:!0})),this.messenger.on(h.RESIZE,async t=>(await e.onResize(t),{success:!0})),this.messenger.on(h.FOCUS,async()=>(await e.onFocus(),{success:!0})),this.messenger.on(h.SHOW,async()=>(await e.onShow(),{success:!0})),this.messenger.on(h.HIDE,async()=>(await e.onHide(),{success:!0})),this.messenger.on(h.ERROR,async t=>{const n=new Error(t.message);return n.stack=t.stack,e.onError(n),{success:!0}}),this.messenger.on(h.EXPORT,async t=>(e.onExport(t),{success:!0})),this.messenger.on(h.CONSUMER_EXPORT,async t=>(e.onConsumerExport(t),{success:!0})),this.messenger.on(h.GET_SIBLINGS,async t=>e.onGetSiblings(t))}destroy(){this.messenger.destroy(),this.bridge.destroy()}}class ae{event;state={};exports;consumerExports;_uid;get uid(){return this._uid}options;cleanup;transport;renderer;propsPipeline;rendered=!1;destroyed=!1;get props(){return this.propsPipeline?this.propsPipeline.props:{}}set props(e){this.propsPipeline&&(this.propsPipeline.props=e)}get inputProps(){return this.propsPipeline?this.propsPipeline.inputProps:{}}set inputProps(e){this.propsPipeline&&(this.propsPipeline.inputProps=e)}get pendingPropsUpdate(){return this.propsPipeline?this.propsPipeline.pendingPropsUpdate:null}set pendingPropsUpdate(e){this.propsPipeline&&(this.propsPipeline.pendingPropsUpdate=e)}get context(){return this.renderer?this.renderer.context:this.options.defaultContext}set context(e){this.renderer&&(this.renderer.context=e)}get hostWindow(){return this.transport?this.transport.hostWindow:null}set hostWindow(e){this.transport&&(this.transport.hostWindow=e)}get openedHostDomain(){return this.transport?this.transport.openedHostDomain:null}set openedHostDomain(e){this.transport&&(this.transport.openedHostDomain=e)}get dynamicUrlTrustedOrigin(){return this.transport?this.transport.dynamicUrlTrustedOrigin:null}set dynamicUrlTrustedOrigin(e){this.transport&&(this.transport.dynamicUrlTrustedOrigin=e)}get iframe(){return this.renderer?this.renderer.iframe:null}set iframe(e){this.renderer&&(this.renderer.iframe=e)}get container(){return this.renderer?this.renderer.container:null}set container(e){this.renderer&&(this.renderer.container=e)}get initPromise(){return this.transport?this.transport.initPromise:null}set initPromise(e){this.transport&&(this.transport.initPromise=e)}get hostInitialized(){return this.transport?this.transport.hostInitialized:!1}set hostInitialized(e){this.transport&&(this.transport.hostInitialized=e)}get messenger(){if(!this.transport)throw new Error("Consumer transport is not initialized");return this.transport.messenger}get bridge(){if(!this.transport)throw new Error("Consumer transport is not initialized");return this.transport.bridge}constructor(e,t={}){this._uid=Ke(),this.options=this.normalizeOptions(e),this.event=new pe,this.cleanup=new qe,this.renderer=new Lt(this.options,this.uid,()=>this.props,()=>this.resolveDimensions(),{close:()=>this.close(),focus:()=>this.focus()}),this.propsPipeline=new Pt(this.options,{...t},n=>this.createPropContext(n)),this.transport=new Xt(this.uid,this.options,()=>this.resolveUrl(),n=>this.resolveUrlOrigin(n)),this.setupMessageHandlers(),this.setupCleanup()}async render(e,t){if(this.destroyed)throw new Error("Component has been destroyed");if(this.rendered)throw new Error("Component has already been rendered");this.context=t??this.options.defaultContext,this.checkEligibility(),ye(this.props,this.options.props),this.options.validate?.({props:this.props}),this.container=this.resolveContainer(e),this.event.emit(m.PRERENDER),this.callPropCallback("onPrerender"),await this.prerender(),this.event.emit(m.PRERENDERED),this.callPropCallback("onPrerendered"),this.event.emit(m.RENDER),this.callPropCallback("onRender");try{await this.open(),await this.waitForHost(),this.context===p.IFRAME&&this.iframe&&await this.renderer.swapPrerenderContentIfNeeded()}catch(n){throw await this.destroy().catch(()=>{}),n}this.rendered=!0,this.event.emit(m.RENDERED),this.callPropCallback("onRendered"),this.event.emit(m.DISPLAY),this.callPropCallback("onDisplay")}async renderTo(e,t,n){if(e!==window)throw new Error("Cross-window renderTo is not supported; pass the current window");return this.render(t,n)}async close(){this.destroyed||(this.event.emit(m.CLOSE),await this.destroy())}async focus(){this.renderer.focus(this.hostWindow),this.event.emit(m.FOCUS),this.callPropCallback("onFocus")}async resize(e){this.renderer.resize(e,this.hostWindow),this.event.emit(m.RESIZE,e),this.callPropCallback("onResize",e)}async show(){this.renderer.show()}async hide(){this.renderer.hide()}async updateProps(e){return this.applyPropsUpdate(e)}async applyPropsUpdate(e){const t={resolveUrl:n=>this.resolveUrl(n),resolveUrlOrigin:n=>this.resolveUrlOrigin(n),assertStableRenderedOrigin:n=>this.assertStableRenderedOrigin(n),isRendered:()=>this.rendered,syncTrustedDomainForUrl:n=>this.syncTrustedDomainForUrl(n),shouldSendPropsToHost:()=>this.transport.isHostConnected(),sendPropsUpdateToHost:n=>this.sendPropsUpdateToHost(n),emitPropsUpdated:()=>this.emitPropsUpdated()};await this.propsPipeline.updateProps(e,t)}assertStableRenderedOrigin(e){if(this.rendered&&this.openedHostDomain&&e&&e!==this.openedHostDomain)throw new Error(`Cannot change component URL origin after render (from "${this.openedHostDomain}" to "${e}")`)}async sendPropsUpdateToHost(e){await this.transport.sendPropsUpdateToHost(e,this.options.props)}emitPropsUpdated(){this.event.emit(m.PROPS,this.props),this.callPropCallback("onProps",this.props)}clone(){const e=new ae(this.options,this.props);return e.inputProps={...this.inputProps},e}isEligible(){return this.options.eligible?this.options.eligible({props:this.props}).eligible:!0}normalizeOptions(e){return{...e,props:e.props??{},defaultContext:e.defaultContext??p.IFRAME,dimensions:e.dimensions??{width:"100%",height:"100%"},timeout:e.timeout??1e4,children:e.children}}resolveUrl(e=this.props){return typeof this.options.url=="function"?this.options.url(e):this.options.url}resolveDimensions(){return typeof this.options.dimensions=="function"?this.options.dimensions(this.props):this.options.dimensions}resolveUrlOrigin(e){try{return new URL(e,window.location.origin).origin}catch{return null}}isExplicitDomainTrust(e){return this.transport.isExplicitDomainTrust(e)}syncTrustedDomainForUrl(e){const t=this.resolveUrlOrigin(e);t&&this.isExplicitDomainTrust(t),this.transport.syncTrustedDomainForUrl(e)}createPropContext(e=this.props){return{props:e,state:this.state,close:()=>this.close(),focus:()=>this.focus(),onError:t=>this.handleError(t),container:this.container,uid:this.uid,tag:this.options.tag}}resolveContainer(e){return this.renderer.resolveContainer(e)}checkEligibility(){if(!this.options.eligible)return;const e=this.options.eligible({props:this.props});if(!e.eligible)throw new Error(`Component not eligible: ${e.reason??"Unknown reason"}`)}async prerender(){await this.renderer.prerender(e=>this.createIframeElement(e),()=>this.buildWindowName())}createIframeElement(e){return this.renderer.createIframeElement(e)}async open(){const e=this.resolveUrl();this.syncTrustedDomainForUrl(e),this.openedHostDomain=this.resolveUrlOrigin(e),this.hostWindow=this.renderer.open({baseUrl:e,buildUrl:t=>this.buildUrl(t),buildBodyParams:()=>this.buildBodyParams(),buildWindowName:()=>this.buildWindowName(),submitBodyForm:(t,n,r)=>this.submitBodyForm(t,n,r),onPopupClose:()=>{this.close()},registerCleanup:t=>{this.cleanup.register(t)}}),this.hostWindow&&it(this.uid,this.hostWindow)}buildUrl(e=this.resolveUrl()){const n=ut(this.props,this.options.props).toString();if(!n)return e;const r=e.includes("?")?"&":"?";return`${e}${r}${n}`}buildBodyParams(){return ht(this.props,this.options.props)}submitBodyForm(e,t,n){this.renderer.submitBodyForm(e,t,n)}buildWindowName(){return this.transport.buildWindowName({tag:this.options.tag,context:this.context,props:this.props,propDefinitions:this.options.props,hostDomain:this.getHostDomain(),children:this.buildNestedHostRefs(),exports:this.createConsumerExports()})}buildNestedHostRefs(){if(!this.options.children)return;const e=this.options.children({props:this.props}),t={};for(const[n,r]of Object.entries(e)){const i=is(r);if(!i)throw new Error(`Nested component "${n}" is missing component metadata`);if(typeof i.url!="string")throw new Error(`Nested component "${n}" must use a static string URL. Function URLs are not supported in children.`);t[n]={tag:i.tag,url:i.url,props:i.props,dimensions:typeof i.dimensions=="function"?void 0:i.dimensions,defaultContext:i.defaultContext}}return Object.keys(t).length>0?t:void 0}createConsumerExports(){return{init:h.INIT,close:h.CLOSE,resize:h.RESIZE,show:h.SHOW,hide:h.HIDE,onError:h.ERROR,updateProps:h.PROPS,export:h.EXPORT}}getHostDomain(){return this.transport.getHostDomain()}async waitForHost(){await this.transport.waitForHost(this.options.timeout,this.options.tag,e=>this.handleError(e))}setupMessageHandlers(){this.transport.setupMessageHandlers({onClose:async()=>this.close(),onResize:async e=>this.resize(e),onFocus:async()=>this.focus(),onShow:async()=>this.show(),onHide:async()=>this.hide(),onError:e=>this.handleError(e),onExport:e=>{this.exports=e},onConsumerExport:e=>{this.consumerExports=e},onGetSiblings:e=>this.getSiblingInstances(e)})}getSiblingInstances(e){const t=[];if(e.options?.anyConsumer){for(const n of rs())n.instance.uid!==e.uid&&t.push({uid:n.instance.uid,tag:n.tag,exports:n.instance.exports});return t}for(const n of ns(e.tag))n.uid!==e.uid&&t.push({uid:n.uid,tag:e.tag,exports:n.exports});return t}setupCleanup(){this.cleanup.register(()=>{this.messenger.destroy(),this.bridge.destroy(),ot(this.uid)})}handleError(e){this.event.emit(m.ERROR,e),this.callPropCallback("onError",e)}callPropCallback(e,...t){const n=this.props[e];if(typeof n=="function")try{const r=n(...t);r&&typeof r=="object"&&"catch"in r&&typeof r.catch=="function"&&r.catch(i=>{console.error(`Error in async ${e} callback:`,i)})}catch(r){console.error(`Error in ${e} callback:`,r)}}async destroy(){this.destroyed||(this.destroyed=!0,this.initPromise&&(this.initPromise.reject(new Error(`Component "${this.options.tag}" was destroyed before initialization completed`)),this.initPromise=null),this.hostInitialized=!1,this.renderer.destroy(this.hostWindow),this.hostWindow=null,this.openedHostDomain=null,this.dynamicUrlTrustedOrigin=null,this.pendingPropsUpdate=null,await this.cleanup.cleanup(),this.event.emit(m.DESTROY),this.callPropCallback("onDestroy"),this.event.removeAllListeners())}}const U=new Map,N=new Map;function Yt(s,e){const t=e;U.get(t.uid)&&De(t.uid);let r=N.get(s);r||(r=new Map,N.set(s,r)),r.set(t.uid,t),U.set(t.uid,{tag:s,instance:t})}function De(s){const e=U.get(s);if(!e)return;U.delete(s);const t=N.get(e.tag);t&&(t.delete(s),t.size===0&&N.delete(e.tag))}function Gt(s){return Array.from(N.get(s)?.values()??[])}function Zt(){return Array.from(U.values())}const Te="Could not resolve consumer window",Qt=new Set(["uid","tag","close","focus","resize","show","hide","onProps","onError","getConsumer","getConsumerDomain","export","consumer","getPeerInstances","children"]);class es{constructor(e,t={},n,r=!1){this.propDefinitions=t,this.allowedConsumerDomains=n,this.deferInit=r,this.uid=e.uid,this.tag=e.tag,this.consumerDomain=e.consumerDomain,this.validateConsumerDomain(),this.event=new pe,this.messenger=new Ce(this.uid,window,G(),this.consumerDomain);let i=null;try{this.setupMessageHandlers(),this.consumerWindow=this.resolveConsumerWindow(),i=new Q(this.messenger),this.bridge=i,this.hostProps=this.buildHostProps(e),this.exposeHostProps(),this.deferInit||this.flushInit()}catch(o){throw i?.destroy(),this.messenger.destroy(),this.event.removeAllListeners(),this.propsHandlers.clear(),o}}hostProps;event;uid;tag;consumerWindow;consumerDomain;messenger;bridge;propsHandlers=new Set;consumerProps;initError=null;destroyed=!1;initSent=!1;deferredInitFlushScheduled=!1;flushInit(){this.destroyed||this.initSent||(this.initSent=!0,this.sendInit())}scheduleDeferredInitFlush(){this.deferredInitFlushScheduled||this.destroyed||this.initSent||(this.deferredInitFlushScheduled=!0,queueMicrotask(()=>{this.deferredInitFlushScheduled=!1,this.flushInit()}))}exposeHostProps(){const e=window;try{Object.defineProperty(e,"hostProps",{configurable:!0,enumerable:!0,get:()=>(this.deferInit&&!this.initSent&&!this.destroyed&&this.scheduleDeferredInitFlush(),this.hostProps),set:t=>{t&&(this.hostProps=t)}})}catch{e.hostProps=this.hostProps}}validateConsumerDomain(){if(this.allowedConsumerDomains&&!C(this.allowedConsumerDomains,this.consumerDomain))throw new Error(`Consumer domain "${this.consumerDomain}" is not allowed for component "${this.tag}"`)}getProps(){return this.hostProps}resolveConsumerWindow(){if(st()){const e=tt();if(e)return e}if(nt()){const e=et();if(e)return e}throw new Error(Te)}buildHostProps(e){const t=Re(e.props,this.propDefinitions,this.messenger,this.bridge,this.consumerWindow,this.consumerDomain);return this.consumerProps=t,{...t,uid:this.uid,tag:this.tag,close:()=>this.close(),focus:()=>this.focus(),resize:n=>this.resize(n),show:()=>this.show(),hide:()=>this.hide(),onProps:n=>this.onProps(n),onError:n=>this.onError(n),getConsumer:()=>this.consumerWindow,getConsumerDomain:()=>this.consumerDomain,export:n=>this.exportData(n),consumer:{props:this.consumerProps,export:n=>this.consumerExport(n)},getPeerInstances:n=>this.getPeerInstances(n),children:this.buildNestedComponents(e.children)}}async sendInit(){try{await this.messenger.send(this.consumerWindow,this.consumerDomain,h.INIT,{uid:this.uid,tag:this.tag})}catch(e){const t=e instanceof Error?e:new Error(String(e));this.initError=t,this.event.emit(m.ERROR,{type:"init_failed",message:`Failed to initialize host component: ${t.message}`,error:t}),console.error("Failed to send init message:",e)}}getInitError(){return this.initError}async close(){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.CLOSE,{})}async focus(){window.focus(),await this.messenger.send(this.consumerWindow,this.consumerDomain,h.FOCUS,{})}async resize(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.RESIZE,e)}async show(){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.SHOW,{})}async hide(){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.HIDE,{})}onProps(e){return this.propsHandlers.add(e),{cancel:()=>this.propsHandlers.delete(e)}}async onError(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.ERROR,{message:e.message,stack:e.stack})}async exportData(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.EXPORT,e)}async consumerExport(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.CONSUMER_EXPORT,e)}async getPeerInstances(e){return await this.messenger.send(this.consumerWindow,this.consumerDomain,h.GET_SIBLINGS,{uid:this.uid,tag:this.tag,options:e})??[]}buildNestedComponents(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e))try{t[n]=ce({tag:r.tag,url:r.url,props:r.props,dimensions:r.dimensions,defaultContext:r.defaultContext})}catch(i){console.warn(`Failed to create nested component "${n}":`,i)}return Object.keys(t).length>0?t:void 0}setupMessageHandlers(){this.messenger.on(h.PROPS,e=>{try{const t=this.consumerProps,n=Re(e,this.propDefinitions,this.messenger,this.bridge,this.consumerWindow,this.consumerDomain);this.removeStaleHostProps(t,n),this.consumerProps=n,Object.assign(this.hostProps,n),this.hostProps.consumer.props=this.consumerProps;for(const r of this.propsHandlers)try{r(n)}catch(i){console.error("Error in props handler:",i)}return this.event.emit(m.PROPS,n),{success:!0}}catch(t){const n=t instanceof Error?t:new Error(String(t));throw console.error("Error deserializing props:",n),this.event.emit(m.ERROR,n),n}})}removeStaleHostProps(e,t){for(const n of Object.keys(e))n in t||Qt.has(n)||delete this.hostProps[n]}destroy(){this.destroyed||(this.destroyed=!0,this.deferredInitFlushScheduled=!1,this.messenger.destroy(),this.bridge.destroy(),this.event.removeAllListeners(),this.propsHandlers.clear())}}let P=null;function K(s,e,t={}){if(P){if(e){const r=P.getProps().getConsumerDomain();if(!C(e,r))throw ts(),new Error(`Consumer domain "${r}" is not allowed for this host component`)}return t.deferInit||P.flushInit(),P}if(!ie())return null;const n=Jt();if(!n)return console.error("Failed to parse ForgeFrame payload from window.name"),null;try{P=new es(n,s,e,t.deferInit??!1)}catch(r){if(r instanceof Error&&r.message===Te)return null;throw r}return P}function Ue(){return ie()}function Ne(){return ie()}function Fe(){return window.hostProps}function ts(){P&&(P.destroy(),P=null),delete window.hostProps}const q=new Map,He=Symbol("forgeframe.component.options");function ss(s){if(!s.tag)throw new Error("Component tag is required");if(!/^[a-z][a-z0-9-]*$/.test(s.tag))throw new Error(`Invalid component tag "${s.tag}". Must start with lowercase letter and contain only lowercase letters, numbers, and hyphens.`);if(!s.url)throw new Error("Component url is required");if(typeof s.url=="string")try{new URL(s.url,window.location.origin)}catch{throw new Error(`Invalid component URL "${s.url}". Must be a valid absolute or relative URL.`)}if(q.has(s.tag))throw new Error(`Component "${s.tag}" is already registered`)}function ce(s){ss(s);const e=[];let t;if(oe(s.tag)){const r=K(s.props,s.allowedConsumerDomains);r&&(t=r.hostProps)}const n=function(r={}){const i=new ae(s,r);return e.push(i),Yt(s.tag,i),i.event.once("destroy",()=>{const o=e.indexOf(i);o!==-1&&e.splice(o,1),De(i.uid)}),i};return n.instances=e,n.isHost=()=>oe(s.tag),n.isEmbedded=()=>oe(s.tag),n.hostProps=t,n[He]=s,n.canRenderTo=async r=>r===window,q.set(s.tag,n),n}function ns(s){return Gt(s)}function rs(){return Zt()}function is(s){return s[He]}async function $e(s){await s.close()}async function le(s){const e=q.get(s);if(!e)return;const t=[...e.instances];await Promise.all(t.map(n=>n.close()))}async function Ae(){const s=Array.from(q.keys());await Promise.all(s.map(e=>le(e)))}function os(s,e){const t=Object.keys(s),n=Object.keys(e);if(t.length!==n.length)return!1;for(const r of t)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(s[r],e[r]))return!1;return!0}function Le(s,e){const{React:t}=e,{createElement:n,useRef:r,useEffect:i,useState:o,forwardRef:a}=t,c=a(function(g,y){const{onRendered:ke,onError:ue,onClose:Me,context:cs,className:We,style:Be,...je}=g,J=r(null),he=r(null),de=r(null),X=r(ue),[Ve,ls]=o(null);return i(()=>{X.current=ue},[ue]),i(()=>{const F=J.current;if(!F)return;const _=s(je);return he.current=_,ke&&_.event.once("rendered",ke),Me&&_.event.once("close",Me),_.event.on("error",R=>{X.current?.(R)}),_.render(F,cs).catch(R=>{ls(R),X.current?.(R)}),()=>{_.close().catch(()=>{}),he.current=null,de.current=null}},[]),i(()=>{const F=he.current;if(!F)return;const _=je,R=de.current;R&&os(R,_)||(de.current=_,F.updateProps(_).catch(us=>{X.current?.(us)}))}),i(()=>{y&&typeof y=="object"&&J.current&&(y.current=J.current)},[y]),Ve?n("div",{className:We,style:{color:"red",padding:"16px",...Be}},`Error: ${Ve.message}`):n("div",{ref:J,className:We,style:{display:"inline-block",...Be}})}),l=`ForgeFrame(${s.name||"Component"})`;return c.displayName=l,c}function as(s){return function(t){return Le(t,{React:s})}}K(void 0,void 0,{deferInit:!0});const ze={create:ce,destroy:$e,destroyByTag:le,destroyAll:Ae,isHost:Ue,isEmbedded:Ne,getHostProps:Fe,initHost:K,PROP_SERIALIZATION:O,CONTEXT:p,EVENT:m,PopupOpenError:se,VERSION:Y,isStandardSchema:D,prop:f};u.AnySchema=j,u.ArraySchema=I,u.BooleanSchema=k,u.CONTEXT=p,u.EVENT=m,u.EnumSchema=B,u.ForgeFrame=ze,u.FunctionSchema=M,u.LiteralSchema=W,u.NumberSchema=z,u.ObjectSchema=x,u.PROP_SERIALIZATION=O,u.PopupOpenError=se,u.PropSchema=w,u.StringSchema=L,u.VERSION=Y,u.create=ce,u.createReactComponent=Le,u.default=ze,u.destroy=$e,u.destroyAll=Ae,u.destroyByTag=le,u.getHostProps=Fe,u.initHost=K,u.isEmbedded=Ne,u.isHost=Ue,u.isStandardSchema=D,u.prop=f,u.withReactComponent=as,Object.defineProperties(u,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
5
|
+
`,(n.head??n.documentElement).appendChild(s)}function kt(n){const{doc:e,dimensions:t,uid:s,tag:r}=n,i=e.createElement("div");return i.id=`forgeframe-container-${s}`,i.setAttribute("data-forgeframe-tag",r),Object.assign(i.style,{display:"inline-block",position:"relative",width:S(t.width),height:S(t.height),overflow:"hidden"}),i}function Wt(n){const{doc:e,dimensions:t,cspNonce:s}=n;zt(e,s);const r=e.createElement("div");Object.assign(r.style,{display:"flex",alignItems:"center",justifyContent:"center",width:S(t.width),height:S(t.height),backgroundColor:"#f5f5f5",position:"absolute",top:"0",left:"0",zIndex:"100"});const i=e.createElement("div");return Object.assign(i.style,{width:"40px",height:"40px",border:"3px solid #e0e0e0",borderTopColor:"#3498db",borderRadius:"50%",animation:"forgeframe-spin 1s linear infinite"}),r.appendChild(i),r}function jt(n,e=200){return new Promise(t=>{n.style.opacity="0",n.style.transition=`opacity ${e}ms ease-in`,n.offsetHeight,n.style.opacity="1",setTimeout(t,e)})}function Bt(n,e=200){return new Promise(t=>{n.style.transition=`opacity ${e}ms ease-out`,n.style.opacity="0",setTimeout(t,e)})}async function Vt(n,e,t){e&&(await Bt(e,150),e.remove()),t.style.display="",t.style.visibility="visible",t.style.opacity="0",await jt(t,150)}class qt{constructor(e,t,s,r,i){this.options=e,this.uid=t,this.getProps=s,this.resolveDimensions=r,this.callbacks=i,this.context=this.options.defaultContext}context;iframe=null;container=null;prerenderElement=null;ownedContainer=null;resolveContainer(e){if(!e)throw new Error("Container is required for rendering");if(typeof e=="string"){const t=document.querySelector(e);if(!t)throw new Error(`Container "${e}" not found`);return t}return e}async prerender(e,t){if(!this.container)return;const s=this.container;this.ownedContainer=null;const r=this.getProps(),i=this.options.prerenderTemplate??Wt,o=this.options.containerTemplate??kt,a=this.resolveDimensions(),c=r.cspNonce;if(this.context===d.IFRAME){const m=t();this.iframe=e(m),ve(this.iframe)}const l={uid:this.uid,tag:this.options.tag,context:this.context,dimensions:a,props:r,doc:document,container:s,frame:this.iframe,prerenderFrame:null,close:()=>this.callbacks.close(),focus:()=>this.callbacks.focus(),cspNonce:c};this.prerenderElement=i(l);const y={uid:this.uid,tag:this.options.tag,context:this.context,dimensions:a,props:r,doc:document,container:s,frame:this.iframe,prerenderFrame:this.prerenderElement,close:()=>this.callbacks.close(),focus:()=>this.callbacks.focus(),cspNonce:c},p=o(y);if(p){if(p!==s){const m=!p.parentNode;s.appendChild(p),m&&(this.ownedContainer=p)}this.container=p}this.prerenderElement&&!this.prerenderElement.parentNode&&this.container.appendChild(this.prerenderElement),this.iframe&&!this.iframe.parentNode&&this.container.appendChild(this.iframe)}createIframeElement(e){const t=this.resolveDimensions(),s=this.getProps(),r=typeof this.options.attributes=="function"?this.options.attributes(s):this.options.attributes??{},i=typeof this.options.style=="function"?this.options.style(s):this.options.style??{};return St({name:e,dimensions:t,attributes:r,style:i})}open(e){const t=e.buildUrl(e.baseUrl),s=e.buildBodyParams(),r=s.toString().length>0;if(this.context===d.IFRAME){if(!this.iframe)throw new Error("Iframe not created during prerender");return r?e.submitBodyForm(this.iframe.name,t,s):this.iframe.src=t,this.iframe.contentWindow}const i=e.buildWindowName(),o=Ft({url:r?"about:blank":t,name:i,dimensions:this.resolveDimensions()});r&&e.submitBodyForm(i,t,s);const a=Lt(o,()=>{e.onPopupClose()});return e.registerCleanup(a),o}async swapPrerenderContentIfNeeded(){this.context===d.IFRAME&&this.iframe&&this.container&&(await Vt(this.container,this.prerenderElement,this.iframe),this.prerenderElement=null)}submitBodyForm(e,t,s){const r=this.container?.ownerDocument??document,i=r.body??r.documentElement;if(!i)throw new Error("Document root is unavailable for bodyParam form submission");const o=r.createElement("form");o.method="POST",o.action=t,o.target=e,o.style.display="none";for(const[a,c]of s.entries()){const l=r.createElement("input");l.type="hidden",l.name=a,l.value=c,o.appendChild(l)}i.appendChild(o);try{o.submit()}finally{o.remove()}}focus(e){this.context===d.IFRAME&&this.iframe?vt(this.iframe):this.context===d.POPUP&&e&&$t(e)}resize(e,t){this.context===d.IFRAME&&this.iframe?It(this.iframe,e):this.context===d.POPUP&&t&&Mt(t,e)}show(){this.context===d.IFRAME&&this.iframe&&xt(this.iframe)}hide(){this.context===d.IFRAME&&this.iframe&&ve(this.iframe)}destroy(e){this.iframe&&(Dt(this.iframe),this.iframe=null),this.context===d.POPUP&&e&&Ht(e),this.prerenderElement&&(this.prerenderElement.remove(),this.prerenderElement=null),this.ownedContainer&&(this.ownedContainer.remove(),this.ownedContainer=null),this.container=null}}const ce="forgeframe:";function le(n){return ce+JSON.stringify(n)}function Jt(n){if(typeof n!="string"||!n.startsWith(ce))return null;try{const e=n.slice(ce.length),t=JSON.parse(e);return!t.id||!t.type||!t.name||!t.source?null:t}catch{return null}}function Ne(n,e,t,s){return{id:n,type:L.REQUEST,name:e,data:t,source:s}}function Kt(n,e,t,s){return{id:n,type:L.RESPONSE,name:"response",data:e,source:t,error:s?{message:s.message,stack:s.stack}:void 0}}function Yt(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xt(n){if(!n.includes("*"))return null;const e=n.split("*").map(t=>Yt(t)).join(".*");return new RegExp(`^${e}$`)}function Gt(n,e){return n.global||n.sticky?new RegExp(n.source,n.flags.replace(/[gy]/g,"")).test(e):n.test(e)}function Zt(n,e,t){return e!==n.targetWin?!1:n.expectedOrigin==="*"?!0:t===n.expectedOrigin}function Qt(n,e){if(n==="*")return"*";if(n==="/")return e;try{return new URL(n,e).origin}catch{return n}}class Fe{constructor(e,t=window,s=window.location.origin,r){this.uid=e,this.win=t,this.domain=s,this.allowedOrigins.add(s),r&&this.addTrustedDomain(r),this.setupListener()}pending=new Map;handlers=new Map;listener=null;destroyed=!1;allowedOrigins=new Set;allowedOriginPatterns=[];wildcardPatternRegistry=new Map;sourceUidRegistry=new WeakMap;addTrustedDomain(e){if(Array.isArray(e))for(const t of e)this.addTrustedDomain(t);else if(e instanceof RegExp)this.allowedOriginPatterns.push(e);else{const t=Xt(e);t?this.wildcardPatternRegistry.has(e)||(this.wildcardPatternRegistry.set(e,t),this.allowedOriginPatterns.push(t)):this.allowedOrigins.add(e)}}removeTrustedDomain(e){if(Array.isArray(e))for(const t of e)this.removeTrustedDomain(t);else if(e instanceof RegExp)this.allowedOriginPatterns=this.allowedOriginPatterns.filter(t=>t!==e);else{const t=this.wildcardPatternRegistry.get(e);t&&(this.allowedOriginPatterns=this.allowedOriginPatterns.filter(s=>s!==t),this.wildcardPatternRegistry.delete(e)),this.allowedOrigins.delete(e)}}isOriginTrusted(e){if(this.allowedOrigins.has(e))return!0;for(const t of this.allowedOriginPatterns)if(Gt(t,e))return!0;return!1}resolveVerifiedSource(e,t,s){const r=e,i=this.sourceUidRegistry.get(r);if(i)return{uid:i,domain:t};const o=s&&typeof s.uid=="string"&&s.uid.length>0?s.uid:k();return this.sourceUidRegistry.set(r,o),{uid:o,domain:t}}async send(e,t,s,r,i=1e4){if(this.destroyed)throw new Error("Messenger has been destroyed");const o=k(),a=Ne(o,s,r,{uid:this.uid,domain:this.domain}),c=Pe(),l=setTimeout(()=>{this.pending.delete(o),c.reject(new Error(`Message "${s}" timed out after ${i}ms`))},i);this.pending.set(o,{deferred:c,timeout:l,targetWin:e,expectedOrigin:Qt(t,this.domain)});try{e.postMessage(le(a),t)}catch(y){throw this.pending.delete(o),clearTimeout(l),y}return c.promise}post(e,t,s,r){if(this.destroyed)throw new Error("Messenger has been destroyed");const i=k(),o=Ne(i,s,r,{uid:this.uid,domain:this.domain});e.postMessage(le(o),t)}on(e,t){return this.handlers.set(e,t),()=>this.handlers.delete(e)}setupListener(){this.listener=e=>{if(e.source===this.win||!this.isOriginTrusted(e.origin))return;const t=Jt(e.data);if(!t)return;const s=e.source;!s||typeof s.postMessage!="function"||this.handleMessage(t,s,e.origin)},this.win.addEventListener("message",this.listener)}async handleMessage(e,t,s){if(e.type===L.RESPONSE){const r=this.pending.get(e.id);if(r){if(!Zt(r,t,s))return;if(this.pending.delete(e.id),clearTimeout(r.timeout),e.error){const i=new Error(e.error.message);i.stack=e.error.stack,r.deferred.reject(i)}else r.deferred.resolve(e.data)}return}if(e.type===L.REQUEST){const r=this.handlers.get(e.name);if(!r)return;let i,o;try{const c=this.resolveVerifiedSource(t,s,e.source);i=await r(e.data,c)}catch(c){o=c instanceof Error?c:new Error(String(c))}const a=Kt(e.id,i,{uid:this.uid,domain:this.domain},o);try{t.postMessage(le(a),s)}catch{}}}destroy(){if(!this.destroyed){this.destroyed=!0,this.listener&&(this.win.removeEventListener("message",this.listener),this.listener=null);for(const e of this.pending.values())clearTimeout(e.timeout),e.deferred.reject(new Error("Messenger destroyed"));this.pending.clear(),this.handlers.clear()}}isDestroyed(){return this.destroyed}}const en=["init","close","resize","show","hide","onError","updateProps","export"],He=32*1024;function tn(n){const e=cn(n);return`${M}${e}`}function $e(n){if(!n||!n.startsWith(M))return null;const e=n.slice(M.length);return ln(e)}function R(n){return typeof n=="object"&&n!==null}function nn(n){return R(n)}function sn(n){return R(n)&&en.every(e=>typeof n[e]=="string"&&n[e].length>0)}function rn(n){if(!R(n)||typeof n.tag!="string"||n.tag.length===0||typeof n.url!="string"||n.url.length===0||n.props!==void 0&&!R(n.props)||n.defaultContext!==void 0&&n.defaultContext!==d.IFRAME&&n.defaultContext!==d.POPUP)return!1;if(n.dimensions!==void 0){if(!R(n.dimensions))return!1;const{width:e,height:t}=n.dimensions;if(e!==void 0&&typeof e!="string"&&typeof e!="number"||t!==void 0&&typeof t!="string"&&typeof t!="number")return!1}return!0}function on(n){return R(n)?Object.values(n).every(e=>rn(e)):!1}function an(n){return!(!R(n)||typeof n.uid!="string"||n.uid.length===0||typeof n.tag!="string"||n.tag.length===0||typeof n.version!="string"||n.version.length===0||n.version!==z||n.context!==d.IFRAME&&n.context!==d.POPUP||typeof n.consumerDomain!="string"||n.consumerDomain.length===0||!nn(n.props)||!sn(n.exports)||n.children!==void 0&&!on(n.children))}function ue(n=window){try{return n.name.startsWith(M)}catch{return!1}}function he(n,e=window){return $e(e.name)?.tag===n}function cn(n){try{const e=JSON.stringify(n),t=btoa(encodeURIComponent(e)),s=new Blob([t]).size;if(s>He)throw new Error(`Payload size (${Math.round(s/1024)}KB) exceeds maximum allowed size (${He/1024}KB). Consider reducing the amount of data passed via props.`);return t}catch(e){throw e instanceof Error&&e.message.includes("Payload size")?e:new Error(`Failed to encode payload: ${e}`)}}function ln(n){try{const e=decodeURIComponent(atob(n)),t=JSON.parse(e);return an(t)?t:null}catch{return null}}function un(n){return{uid:n.uid,tag:n.tag,version:z,context:n.context,consumerDomain:n.consumerDomain,props:n.props,exports:n.exports,children:n.children}}function hn(n=window){return $e(n.name)}class dn{constructor(e,t,s,r){this.uid=e,this.options=t,this.resolveUrl=s,this.resolveUrlOrigin=r;const i=this.buildTrustedDomains();this.messenger=new Fe(this.uid,window,W(),i),this.bridge=new se(this.messenger)}messenger;bridge;hostWindow=null;openedHostDomain=null;dynamicUrlTrustedOrigin=null;initPromise=null;hostInitialized=!1;buildTrustedDomains(){const e=[],t=this.resolveUrlOrigin(this.resolveUrl());if(t&&(e.push(t),this.dynamicUrlTrustedOrigin=t),this.options.domain&&(typeof this.options.domain=="string"?e.push(this.options.domain):Array.isArray(this.options.domain)?e.push(...this.options.domain):this.options.domain instanceof RegExp&&e.push(this.options.domain)),e.length!==0)return e.length===1?e[0]:e}isExplicitDomainTrust(e){return this.options.domain?v(this.options.domain,e):!1}syncTrustedDomainForUrl(e){const t=this.resolveUrlOrigin(e);if(!t)return;const s=this.dynamicUrlTrustedOrigin;s&&s!==t&&!this.isExplicitDomainTrust(s)&&this.messenger.removeTrustedDomain(s),this.messenger.addTrustedDomain(t),this.dynamicUrlTrustedOrigin=t}getHostDomain(){return this.openedHostDomain?this.openedHostDomain:this.resolveUrlOrigin(this.resolveUrl())??"*"}isHostConnected(){return!!(this.hostWindow&&!ne(this.hostWindow))}serializePropsForHost(e,t,s){this.bridge.startBatch();const r=s?.finishBatch??!0;try{const i=Et(e,t,this.bridge);return r&&this.bridge.finishBatch(),i}catch(i){throw this.bridge.finishBatch(!0),i}}async sendPropsUpdateToHost(e,t){if(!this.hostWindow||ne(this.hostWindow))return;const s=this.getHostDomain(),r=Re(e,t,s,Ee(this.hostWindow)),i=this.serializePropsForHost(r,t,{finishBatch:!1});try{await this.messenger.send(this.hostWindow,s,h.PROPS,i),this.bridge.finishBatch()}catch(o){throw this.bridge.finishBatch(!0),o}}buildWindowName(e){const t=e.hostDomain??this.getHostDomain(),s=Re(e.props,e.propDefinitions,t,!1),r=this.serializePropsForHost(s,e.propDefinitions),i=un({uid:this.uid,tag:e.tag,context:e.context,consumerDomain:W(),props:r,exports:e.exports,children:e.children});return tn(i)}async waitForHost(e,t,s){if(this.hostInitialized)return;const r=Pe();this.initPromise=r;try{await Qe(r.promise,e,`Host component "${t}" (uid: ${this.uid}) did not initialize within ${e}ms. Check that the host page loads correctly and calls the initialization code.`)}catch(i){throw s(i),i}finally{this.initPromise===r&&(this.initPromise=null)}}setupMessageHandlers(e){this.messenger.on(h.INIT,()=>(this.hostInitialized=!0,this.initPromise&&this.initPromise.resolve(),e.onInit&&queueMicrotask(()=>{Promise.resolve(e.onInit?.()).catch(t=>{e.onError(t)})}),{success:!0})),this.messenger.on(h.CLOSE,async()=>(await e.onClose(),{success:!0})),this.messenger.on(h.RESIZE,async t=>(await e.onResize(t),{success:!0})),this.messenger.on(h.FOCUS,async()=>(await e.onFocus(),{success:!0})),this.messenger.on(h.SHOW,async()=>(await e.onShow(),{success:!0})),this.messenger.on(h.HIDE,async()=>(await e.onHide(),{success:!0})),this.messenger.on(h.ERROR,async t=>{const s=new Error(t.message);return s.stack=t.stack,e.onError(s),{success:!0}}),this.messenger.on(h.EXPORT,async t=>(e.onExport(t),{success:!0})),this.messenger.on(h.CONSUMER_EXPORT,async t=>(e.onConsumerExport(t),{success:!0})),this.messenger.on(h.GET_SIBLINGS,async t=>e.onGetSiblings(t))}destroy(){this.messenger.destroy(),this.bridge.destroy()}}class de{event;state={};exports;consumerExports;_uid;get uid(){return this._uid}options;cleanup;transport;renderer;propsPipeline;rendered=!1;destroyed=!1;closing=!1;get props(){return this.propsPipeline?this.propsPipeline.props:{}}set props(e){this.propsPipeline&&(this.propsPipeline.props=e)}get inputProps(){return this.propsPipeline?this.propsPipeline.inputProps:{}}set inputProps(e){this.propsPipeline&&(this.propsPipeline.inputProps=e)}get pendingPropsUpdate(){return this.propsPipeline?this.propsPipeline.pendingPropsUpdate:null}set pendingPropsUpdate(e){this.propsPipeline&&(this.propsPipeline.pendingPropsUpdate=e)}get context(){return this.renderer?this.renderer.context:this.options.defaultContext}set context(e){this.renderer&&(this.renderer.context=e)}get hostWindow(){return this.transport?this.transport.hostWindow:null}set hostWindow(e){this.transport&&(this.transport.hostWindow=e)}get openedHostDomain(){return this.transport?this.transport.openedHostDomain:null}set openedHostDomain(e){this.transport&&(this.transport.openedHostDomain=e)}get dynamicUrlTrustedOrigin(){return this.transport?this.transport.dynamicUrlTrustedOrigin:null}set dynamicUrlTrustedOrigin(e){this.transport&&(this.transport.dynamicUrlTrustedOrigin=e)}get iframe(){return this.renderer?this.renderer.iframe:null}set iframe(e){this.renderer&&(this.renderer.iframe=e)}get container(){return this.renderer?this.renderer.container:null}set container(e){this.renderer&&(this.renderer.container=e)}get initPromise(){return this.transport?this.transport.initPromise:null}set initPromise(e){this.transport&&(this.transport.initPromise=e)}get hostInitialized(){return this.transport?this.transport.hostInitialized:!1}set hostInitialized(e){this.transport&&(this.transport.hostInitialized=e)}get messenger(){if(!this.transport)throw new Error("Consumer transport is not initialized");return this.transport.messenger}get bridge(){if(!this.transport)throw new Error("Consumer transport is not initialized");return this.transport.bridge}constructor(e,t={}){this._uid=Ge(),this.options=this.normalizeOptions(e),this.event=new _e,this.cleanup=new Ze,this.renderer=new qt(this.options,this.uid,()=>this.props,()=>this.resolveDimensions(),{close:()=>this.close(),focus:()=>this.focus()}),this.propsPipeline=new Ct(this.options,{...t},s=>this.createPropContext(s)),this.transport=new dn(this.uid,this.options,()=>this.resolveUrl(),s=>this.resolveUrlOrigin(s)),this.setupMessageHandlers(),this.setupCleanup()}async render(e,t){if(this.destroyed)throw new Error("Component has been destroyed");if(this.rendered)throw new Error("Component has already been rendered");this.context=t??this.options.defaultContext,this.checkEligibility(),F(this.props,this.options.props),this.options.validate?.({props:this.props}),this.container=this.resolveContainer(e),this.event.emit(g.PRERENDER),this.callPropCallback("onPrerender"),await this.prerender(),this.event.emit(g.PRERENDERED),this.callPropCallback("onPrerendered"),this.event.emit(g.RENDER),this.callPropCallback("onRender");try{await this.open(),await this.waitForHost(),this.context===d.IFRAME&&this.iframe&&await this.renderer.swapPrerenderContentIfNeeded()}catch(s){throw await this.destroy().catch(()=>{}),s}this.rendered=!0,this.event.emit(g.RENDERED),this.callPropCallback("onRendered"),this.event.emit(g.DISPLAY),this.callPropCallback("onDisplay")}async renderTo(e,t,s){if(e!==window)throw new Error("Cross-window renderTo is not supported; pass the current window");return this.render(t,s)}async close(){if(!(this.destroyed||this.closing)){this.closing=!0;try{this.event.emit(g.CLOSE),this.callPropCallback("onClose"),await this.destroy()}finally{this.closing=!1}}}async focus(){this.renderer.focus(this.hostWindow),this.event.emit(g.FOCUS),this.callPropCallback("onFocus")}async resize(e){this.renderer.resize(e,this.hostWindow),this.event.emit(g.RESIZE,e),this.callPropCallback("onResize",e)}async show(){this.renderer.show()}async hide(){this.renderer.hide()}async updateProps(e){return this.applyPropsUpdate(e)}async applyPropsUpdate(e){const t={resolveUrl:s=>this.resolveUrl(s),resolveUrlOrigin:s=>this.resolveUrlOrigin(s),assertStableRenderedOrigin:s=>this.assertStableRenderedOrigin(s),isRendered:()=>this.rendered,syncTrustedDomainForUrl:s=>this.syncTrustedDomainForUrl(s),shouldSendPropsToHost:()=>this.transport.isHostConnected(),sendPropsUpdateToHost:s=>this.sendPropsUpdateToHost(s),emitPropsUpdated:()=>this.emitPropsUpdated()};await this.propsPipeline.updateProps(e,t)}assertStableRenderedOrigin(e){if(this.rendered&&this.openedHostDomain&&e&&e!==this.openedHostDomain)throw new Error(`Cannot change component URL origin after render (from "${this.openedHostDomain}" to "${e}")`)}async sendPropsUpdateToHost(e){await this.transport.sendPropsUpdateToHost(e,this.options.props)}emitPropsUpdated(){this.event.emit(g.PROPS,this.props),this.callPropCallback("onProps",this.props)}clone(){const e=new de(this.options,this.props);return e.inputProps={...this.inputProps},e}isEligible(){return this.options.eligible?this.options.eligible({props:this.props}).eligible:!0}normalizeOptions(e){return{...e,props:e.props??{},defaultContext:e.defaultContext??d.IFRAME,dimensions:e.dimensions??{width:"100%",height:"100%"},timeout:e.timeout??1e4,children:e.children}}resolveUrl(e=this.props){return typeof this.options.url=="function"?this.options.url(e):this.options.url}resolveDimensions(){return typeof this.options.dimensions=="function"?this.options.dimensions(this.props):this.options.dimensions}resolveUrlOrigin(e){try{return new URL(e,window.location.origin).origin}catch{return null}}isExplicitDomainTrust(e){return this.transport.isExplicitDomainTrust(e)}syncTrustedDomainForUrl(e){const t=this.resolveUrlOrigin(e);t&&this.isExplicitDomainTrust(t),this.transport.syncTrustedDomainForUrl(e)}createPropContext(e=this.props){return{props:e,state:this.state,close:()=>this.close(),focus:()=>this.focus(),onError:t=>this.handleError(t),container:this.container,uid:this.uid,tag:this.options.tag}}resolveContainer(e){return this.renderer.resolveContainer(e)}checkEligibility(){if(!this.options.eligible)return;const e=this.options.eligible({props:this.props});if(!e.eligible)throw new Error(`Component not eligible: ${e.reason??"Unknown reason"}`)}async prerender(){await this.renderer.prerender(e=>this.createIframeElement(e),()=>this.buildWindowName())}createIframeElement(e){return this.renderer.createIframeElement(e)}async open(){const e=this.resolveUrl();this.syncTrustedDomainForUrl(e),this.openedHostDomain=this.resolveUrlOrigin(e),this.hostWindow=this.renderer.open({baseUrl:e,buildUrl:t=>this.buildUrl(t),buildBodyParams:()=>this.buildBodyParams(),buildWindowName:()=>this.buildWindowName(),submitBodyForm:(t,s,r)=>this.submitBodyForm(t,s,r),onPopupClose:()=>{this.close()},registerCleanup:t=>{this.cleanup.register(t)}}),this.hostWindow&<(this.uid,this.hostWindow)}buildUrl(e=this.resolveUrl()){const s=ft(this.props,this.options.props).toString();if(!s)return e;const r=e.includes("?")?"&":"?";return`${e}${r}${s}`}buildBodyParams(){return mt(this.props,this.options.props)}submitBodyForm(e,t,s){this.renderer.submitBodyForm(e,t,s)}buildWindowName(){return this.transport.buildWindowName({tag:this.options.tag,context:this.context,props:this.props,propDefinitions:this.options.props,hostDomain:this.getHostDomain(),children:this.buildNestedHostRefs(),exports:this.createConsumerExports()})}buildNestedHostRefs(){if(!this.options.children)return;const e=this.options.children({props:this.props}),t={};for(const[s,r]of Object.entries(e)){const i=bn(r);if(!i)throw new Error(`Nested component "${s}" is missing component metadata`);if(typeof i.url!="string")throw new Error(`Nested component "${s}" must use a static string URL. Function URLs are not supported in children.`);t[s]={tag:i.tag,url:i.url,props:i.props,dimensions:typeof i.dimensions=="function"?void 0:i.dimensions,defaultContext:i.defaultContext}}return Object.keys(t).length>0?t:void 0}createConsumerExports(){return{init:h.INIT,close:h.CLOSE,resize:h.RESIZE,show:h.SHOW,hide:h.HIDE,onError:h.ERROR,updateProps:h.PROPS,export:h.EXPORT}}getHostDomain(){return this.transport.getHostDomain()}async waitForHost(){await this.transport.waitForHost(this.options.timeout,this.options.tag,e=>this.handleError(e))}setupMessageHandlers(){this.transport.setupMessageHandlers({onInit:()=>this.syncSameDomainPropsAfterInit(),onClose:async()=>this.close(),onResize:async e=>this.resize(e),onFocus:async()=>this.focus(),onShow:async()=>this.show(),onHide:async()=>this.hide(),onError:e=>this.handleError(e),onExport:e=>{this.exports=e},onConsumerExport:e=>{this.consumerExports=e},onGetSiblings:e=>this.getSiblingInstances(e)})}async syncSameDomainPropsAfterInit(){if(!(!this.hostWindow||!this.transport.isHostConnected())&&Ee(this.hostWindow)&&this.hasSameDomainPropDefinition())try{await this.propsPipeline.syncCurrentPropsToHost({shouldSendPropsToHost:()=>this.transport.isHostConnected(),sendPropsUpdateToHost:e=>this.sendPropsUpdateToHost(e)})}catch(e){this.handleError(e)}}hasSameDomainPropDefinition(){return Object.values(this.options.props).some(e=>!e||O(e)?!1:e.sameDomain===!0)}getSiblingInstances(e){const t=[];if(e.options?.anyConsumer){for(const s of En())s.instance.uid!==e.uid&&t.push({uid:s.instance.uid,tag:s.tag,exports:s.instance.exports});return t}for(const s of Pn(e.tag))s.uid!==e.uid&&t.push({uid:s.uid,tag:e.tag,exports:s.exports});return t}setupCleanup(){this.cleanup.register(()=>{this.messenger.destroy(),this.bridge.destroy(),ut(this.uid)})}handleError(e){this.event.emit(g.ERROR,e),this.callPropCallback("onError",e)}callPropCallback(e,...t){const s=this.props[e];if(typeof s=="function")try{const r=s(...t);r&&typeof r=="object"&&"catch"in r&&typeof r.catch=="function"&&r.catch(i=>{console.error(`Error in async ${e} callback:`,i)})}catch(r){console.error(`Error in ${e} callback:`,r)}}async destroy(){this.destroyed||(this.destroyed=!0,this.initPromise&&(this.initPromise.reject(new Error(`Component "${this.options.tag}" was destroyed before initialization completed`)),this.initPromise=null),this.hostInitialized=!1,this.renderer.destroy(this.hostWindow),this.hostWindow=null,this.openedHostDomain=null,this.dynamicUrlTrustedOrigin=null,this.pendingPropsUpdate=null,await this.cleanup.cleanup(),this.event.emit(g.DESTROY),this.callPropCallback("onDestroy"),this.event.removeAllListeners())}}const H=new Map,$=new Map;function pn(n,e){const t=e;H.get(t.uid)&&Ae(t.uid);let r=$.get(n);r||(r=new Map,$.set(n,r)),r.set(t.uid,t),H.set(t.uid,{tag:n,instance:t})}function Ae(n){const e=H.get(n);if(!e)return;H.delete(n);const t=$.get(e.tag);t&&(t.delete(n),t.size===0&&$.delete(e.tag))}function fn(n){return Array.from($.get(n)?.values()??[])}function mn(){return Array.from(H.values())}const Le="Could not resolve consumer window",pe="Could not verify consumer origin",gn=new Set(["uid","tag","close","focus","resize","show","hide","onProps","onError","getConsumer","getConsumerDomain","export","consumer","getPeerInstances","children"]);class yn{constructor(e,t={},s,r=!1){this.propDefinitions=t,this.allowedConsumerDomains=s,this.deferInit=r,this.uid=e.uid,this.tag=e.tag,this.event=new _e;let i=null,o=null;try{this.consumerWindow=this.resolveConsumerWindow(),this.consumerDomain=this.resolveConsumerDomain(e.consumerDomain),o=new Fe(this.uid,window,W(),this.consumerDomain),this.messenger=o,this.setupMessageHandlers(),i=new se(this.messenger),this.bridge=i,this.hostProps=this.buildHostProps(e),this.exposeHostProps(),this.deferInit||this.flushInit()}catch(a){throw i?.destroy(),o?.destroy(),this.event.removeAllListeners(),this.propsHandlers.clear(),a}}hostProps;event;uid;tag;consumerWindow;consumerDomain;consumerDomainVerified=!1;messenger;bridge;propsHandlers=new Set;consumerProps;initError=null;destroyed=!1;initSent=!1;deferredInitFlushScheduled=!1;flushInit(){this.destroyed||this.initSent||(this.initSent=!0,this.sendInit())}scheduleDeferredInitFlush(){this.deferredInitFlushScheduled||this.destroyed||this.initSent||(this.deferredInitFlushScheduled=!0,queueMicrotask(()=>{this.deferredInitFlushScheduled=!1,this.flushInit()}))}exposeHostProps(){const e=window;try{Object.defineProperty(e,"hostProps",{configurable:!0,enumerable:!0,get:()=>(this.deferInit&&!this.initSent&&!this.destroyed&&this.scheduleDeferredInitFlush(),this.hostProps),set:t=>{t&&(this.hostProps=t)}})}catch{e.hostProps=this.hostProps}}validateConsumerDomain(){if(this.allowedConsumerDomains){if(!this.consumerDomain)throw new Error(`${pe} for component "${this.tag}"`);if(!v(this.allowedConsumerDomains,this.consumerDomain))throw new Error(`Consumer domain "${this.consumerDomain}" is not allowed for component "${this.tag}"`)}}getVerifiedConsumerOrigin(){return this.getReferrerOrigin()??this.getAccessibleConsumerOrigin()}setConsumerDomain(e,t){const s=this.consumerDomain;this.consumerDomain=e,this.consumerDomainVerified=t,!(!this.messenger||!s||s===e)&&(this.messenger.removeTrustedDomain(s),this.messenger.addTrustedDomain(e))}applyHostConfiguration(e,t){t!==void 0&&(this.allowedConsumerDomains=t),e!==void 0&&(this.propDefinitions=e,F(this.consumerProps,this.getBootstrapValidationDefinitions()),Object.assign(this.hostProps,this.consumerProps),this.hostProps.consumer.props=this.consumerProps)}resolveConsumerDomain(e){const t=this.getVerifiedConsumerOrigin();if(t)return this.consumerDomainVerified=!0,this.consumerDomain=t,this.validateConsumerDomain(),t;if(this.consumerDomainVerified=!1,this.allowedConsumerDomains)throw new Error(`${pe} for component "${this.tag}"`);return e}assertAllowedConsumerDomain(e){const t=this.getVerifiedConsumerOrigin();if(t&&this.setConsumerDomain(t,!0),!this.consumerDomainVerified)throw new Error(`${pe} for component "${this.tag}"`);if(!v(e,this.consumerDomain))throw new Error(`Consumer domain "${this.consumerDomain}" is not allowed for component "${this.tag}"`)}getReferrerOrigin(){if(!document.referrer)return null;try{return new URL(document.referrer,window.location.href).origin}catch{return null}}getAccessibleConsumerOrigin(){try{return this.consumerWindow.location.origin}catch{return null}}getProps(){return this.hostProps}resolveConsumerWindow(){if(ot()){const e=it();if(e)return e}if(at()){const e=rt();if(e)return e}throw new Error(Le)}buildHostProps(e){const t=xe(e.props,this.propDefinitions,this.messenger,this.bridge,this.consumerWindow,this.consumerDomain);return F(t,this.getBootstrapValidationDefinitions()),this.consumerProps=t,{...t,uid:this.uid,tag:this.tag,close:()=>this.close(),focus:()=>this.focus(),resize:s=>this.resize(s),show:()=>this.show(),hide:()=>this.hide(),onProps:s=>this.onProps(s),onError:s=>this.onError(s),getConsumer:()=>this.consumerWindow,getConsumerDomain:()=>this.consumerDomain,export:s=>this.exportData(s),consumer:{props:this.consumerProps,export:s=>this.consumerExport(s)},getPeerInstances:s=>this.getPeerInstances(s),children:this.buildNestedComponents(e.children)}}getBootstrapValidationDefinitions(){if(!this.consumerDomainVerified||this.consumerDomain!==W())return this.propDefinitions;let e=!1;const t={...this.propDefinitions};for(const[s,r]of Object.entries(this.propDefinitions))!r||O(r)||!r.sameDomain||(e=!0,t[s]={...r,required:!1});return e?t:this.propDefinitions}async sendInit(){try{await this.messenger.send(this.consumerWindow,this.consumerDomain,h.INIT,{uid:this.uid,tag:this.tag})}catch(e){const t=e instanceof Error?e:new Error(String(e));this.initError=t,this.event.emit(g.ERROR,{type:"init_failed",message:`Failed to initialize host component: ${t.message}`,error:t}),console.error("Failed to send init message:",e)}}getInitError(){return this.initError}async close(){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.CLOSE,{})}async focus(){window.focus(),await this.messenger.send(this.consumerWindow,this.consumerDomain,h.FOCUS,{})}async resize(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.RESIZE,e)}async show(){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.SHOW,{})}async hide(){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.HIDE,{})}onProps(e){return this.propsHandlers.add(e),{cancel:()=>this.propsHandlers.delete(e)}}async onError(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.ERROR,{message:e.message,stack:e.stack})}async exportData(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.EXPORT,e)}async consumerExport(e){await this.messenger.send(this.consumerWindow,this.consumerDomain,h.CONSUMER_EXPORT,e)}async getPeerInstances(e){return await this.messenger.send(this.consumerWindow,this.consumerDomain,h.GET_SIBLINGS,{uid:this.uid,tag:this.tag,options:e})??[]}buildNestedComponents(e){if(!e)return;const t={};for(const[s,r]of Object.entries(e))try{t[s]=fe({tag:r.tag,url:r.url,props:r.props,dimensions:r.dimensions,defaultContext:r.defaultContext})}catch(i){console.warn(`Failed to create nested component "${s}":`,i)}return Object.keys(t).length>0?t:void 0}setupMessageHandlers(){this.messenger.on(h.PROPS,e=>{try{const t=this.consumerProps,s=xe(e,this.propDefinitions,this.messenger,this.bridge,this.consumerWindow,this.consumerDomain);F(s,this.propDefinitions),this.removeStaleHostProps(t,s),this.consumerProps=s,Object.assign(this.hostProps,s),this.hostProps.consumer.props=this.consumerProps;for(const r of this.propsHandlers)try{r(s)}catch(i){console.error("Error in props handler:",i)}return this.event.emit(g.PROPS,s),{success:!0}}catch(t){const s=t instanceof Error?t:new Error(String(t));throw console.error("Error deserializing props:",s),this.event.emit(g.ERROR,s),s}})}removeStaleHostProps(e,t){for(const s of Object.keys(e))s in t||gn.has(s)||delete this.hostProps[s]}destroy(){this.destroyed||(this.destroyed=!0,this.deferredInitFlushScheduled=!1,this.messenger.destroy(),this.bridge.destroy(),this.event.removeAllListeners(),this.propsHandlers.clear())}}let _=null;function G(n,e,t={}){if(_){try{_.applyHostConfiguration(n,e),e&&_.assertAllowedConsumerDomain(e)}catch(r){throw wn(),r}return t.deferInit||_.flushInit(),_}if(!ue())return null;const s=hn();if(!s)return console.error("Failed to parse ForgeFrame payload from window.name"),null;try{_=new yn(s,n,e,t.deferInit??!1)}catch(r){if(r instanceof Error&&r.message===Le)return null;throw r}return _}function Me(){return ue()}function ze(){return ue()}function ke(){return window.hostProps}function wn(){_&&(_.destroy(),_=null),delete window.hostProps}const Z=new Map,We=Symbol("forgeframe.component.options");function _n(n){if(!n.tag)throw new Error("Component tag is required");if(!/^[a-z][a-z0-9-]*$/.test(n.tag))throw new Error(`Invalid component tag "${n.tag}". Must start with lowercase letter and contain only lowercase letters, numbers, and hyphens.`);if(!n.url)throw new Error("Component url is required");if(typeof n.url=="string")try{new URL(n.url,window.location.origin)}catch{throw new Error(`Invalid component URL "${n.url}". Must be a valid absolute or relative URL.`)}if(Z.has(n.tag))throw new Error(`Component "${n.tag}" is already registered`)}function fe(n){_n(n);const e=[];let t;if(he(n.tag)){const r=G(n.props,n.allowedConsumerDomains);r&&(t=r.hostProps)}const s=function(r={}){const i=new de(n,r);return e.push(i),pn(n.tag,i),i.event.once("destroy",()=>{const o=e.indexOf(i);o!==-1&&e.splice(o,1),Ae(i.uid)}),i};return s.instances=e,s.isHost=()=>he(n.tag),s.isEmbedded=()=>he(n.tag),s.hostProps=t,s[We]=n,s.canRenderTo=async r=>r===window,Z.set(n.tag,s),s}function Pn(n){return fn(n)}function En(){return mn()}function bn(n){return n[We]}async function je(n){await n.close()}async function me(n){const e=Z.get(n);if(!e)return;const t=[...e.instances];await Promise.all(t.map(s=>s.close()))}async function Be(){const n=Array.from(Z.keys());await Promise.all(n.map(e=>me(e)))}function On(n,e){const t=Object.keys(n),s=Object.keys(e);if(t.length!==s.length)return!1;for(const r of t)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(n[r],e[r]))return!1;return!0}function Ve(n,e){const{React:t}=e,{createElement:s,useRef:r,useEffect:i,useState:o,forwardRef:a}=t,c=a(function(p,m){const{onRendered:D,onError:ge,onClose:Je,context:Cn,className:Ke,style:Ye,...ye}=p,Q=r(null),we=r(null),ee=r(null),te=r(ge),[Xe,Sn]=o(null);return i(()=>{te.current=ge},[ge]),i(()=>{const A=Q.current;if(!A)return;const P=n(ye);return we.current=P,ee.current=ye,D&&P.event.once("rendered",D),Je&&P.event.once("close",Je),P.event.on("error",C=>{te.current?.(C)}),P.render(A,Cn).catch(C=>{Sn(C),te.current?.(C)}),()=>{P.close().catch(()=>{}),we.current=null,ee.current=null}},[]),i(()=>{const A=we.current;if(!A)return;const P=ye,C=ee.current;C&&On(C,P)||(ee.current=P,A.updateProps(P).catch(Dn=>{te.current?.(Dn)}))}),i(()=>{m&&typeof m=="object"&&Q.current&&(m.current=Q.current)},[m]),Xe?s("div",{className:Ke,style:{color:"red",padding:"16px",...Ye}},`Error: ${Xe.message}`):s("div",{ref:Q,className:Ke,style:{display:"inline-block",...Ye}})}),l=`ForgeFrame(${n.name||"Component"})`;return c.displayName=l,c}function Rn(n){return function(t){return Ve(t,{React:n})}}G(void 0,void 0,{deferInit:!0});const qe={create:fe,destroy:je,destroyByTag:me,destroyAll:Be,isHost:Me,isEmbedded:ze,getHostProps:ke,initHost:G,PROP_SERIALIZATION:I,CONTEXT:d,EVENT:g,PopupOpenError:ae,VERSION:z,isStandardSchema:O,prop:f};u.AnySchema=Y,u.ArraySchema=T,u.BooleanSchema=V,u.CONTEXT=d,u.EVENT=g,u.EnumSchema=K,u.ForgeFrame=qe,u.FunctionSchema=q,u.LiteralSchema=J,u.NumberSchema=B,u.ObjectSchema=U,u.PROP_SERIALIZATION=I,u.PopupOpenError=ae,u.PropSchema=w,u.StringSchema=j,u.VERSION=z,u.create=fe,u.createReactComponent=Ve,u.default=qe,u.destroy=je,u.destroyAll=Be,u.destroyByTag=me,u.getHostProps=ke,u.initHost=G,u.isEmbedded=ze,u.isHost=Me,u.isStandardSchema=O,u.prop=f,u.withReactComponent=Rn,Object.defineProperties(u,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
package/dist/render/iframe.d.ts
CHANGED
|
@@ -30,6 +30,35 @@ export interface IframeOptions {
|
|
|
30
30
|
*/
|
|
31
31
|
style?: IframeStyles;
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Configuration for creating an iframe element before navigation.
|
|
35
|
+
*
|
|
36
|
+
* @internal
|
|
37
|
+
*/
|
|
38
|
+
interface IframeElementOptions {
|
|
39
|
+
/**
|
|
40
|
+
* The name attribute for the iframe, used for targeting.
|
|
41
|
+
*/
|
|
42
|
+
name: string;
|
|
43
|
+
/**
|
|
44
|
+
* The width and height dimensions for the iframe.
|
|
45
|
+
*/
|
|
46
|
+
dimensions: Dimensions;
|
|
47
|
+
/**
|
|
48
|
+
* Optional additional HTML attributes to set on the iframe element.
|
|
49
|
+
*/
|
|
50
|
+
attributes?: IframeAttributes;
|
|
51
|
+
/**
|
|
52
|
+
* Optional CSS styles to apply to the iframe element.
|
|
53
|
+
*/
|
|
54
|
+
style?: IframeStyles;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Creates a configured iframe element without appending it or setting `src`.
|
|
58
|
+
*
|
|
59
|
+
* @internal
|
|
60
|
+
*/
|
|
61
|
+
export declare function createIframeElement(options: IframeElementOptions): HTMLIFrameElement;
|
|
33
62
|
/**
|
|
34
63
|
* Creates an iframe element with the specified options and appends it to a container.
|
|
35
64
|
*
|
|
@@ -211,3 +240,4 @@ export declare function focusIframe(iframe: HTMLIFrameElement): void;
|
|
|
211
240
|
* @public
|
|
212
241
|
*/
|
|
213
242
|
export declare function getIframeContentDimensions(iframe: HTMLIFrameElement): Dimensions | null;
|
|
243
|
+
export {};
|
package/dist/types.d.ts
CHANGED
|
@@ -209,7 +209,7 @@ export interface PropDefinition<T = unknown, P = Record<string, unknown>> {
|
|
|
209
209
|
value?: (ctx: PropContext<P>) => T;
|
|
210
210
|
/** Whether to send this prop to the host window (default: true) */
|
|
211
211
|
sendToHost?: boolean;
|
|
212
|
-
/** Only
|
|
212
|
+
/** Only deliver after the loaded host is verified to be same-origin */
|
|
213
213
|
sameDomain?: boolean;
|
|
214
214
|
/** List of trusted domains that can receive this prop */
|
|
215
215
|
trustedDomains?: DomainMatcher[];
|