@first-to-fly/crm-sdk 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -574,6 +574,53 @@ in-frame navigation with the sub-path under the embed base (for example `/`, `/c
574
574
  `/contacts/42`, `/settings/business`), without a query string. Match by prefix to
575
575
  highlight your own nav item, e.g. `/comms` and `/conversations` both mean Inbox.
576
576
 
577
+ #### Host actions (create an enquiry, open a person)
578
+
579
+ Some things only your app can do, such as turning a chat with an unknown parent into a lead.
580
+ The embedded CRM can ask for them without knowing how your app works. You opt in per action:
581
+
582
+ ```tsx
583
+ <CrmEmbed
584
+ crmEmbedOrigin="https://app.crm.example.com"
585
+ getSession={crmSession('/api/crm/session')}
586
+ hostName="myEdu"
587
+ capabilities={['create-lead', 'open-person']}
588
+ onHostAction={(req) => {
589
+ if (req.action === 'create-lead') openEnquiryForm({ ...req.contact, note: req.messageSnippet });
590
+ if (req.action === 'open-person') router.push(`/people/by-crm-contact/${req.contact.crmContactId}`);
591
+ }}
592
+ />
593
+ ```
594
+
595
+ Low-level hosts pass the same `hostContext: { capabilities, hostName }` and `onHostAction` to
596
+ `createCrmEmbedHost`, and change them later with `setContext`.
597
+
598
+ - `capabilities` is channel-only (never in the iframe URL). Known values only (`create-lead`,
599
+ `open-person`), de-duplicated, at most 8. A new list replaces the old one; `[]` turns every
600
+ action off; omitted leaves it unchanged. With none, the CRM shows no host button.
601
+ - `hostName` (max 40 characters) is the label the CRM puts on its buttons and cards. When
602
+ absent the CRM says "the host app".
603
+ - Port message from the CRM: `{ type: 'crm:host-action', requestId, ...action }`, where the
604
+ action is one of:
605
+ - `{ action: 'create-lead', contact: { crmContactId, name?, phone?, email? }, conversationId, channel?, messageSnippet? }`.
606
+ `messageSnippet` is the last inbound message, at most 280 characters.
607
+ - `{ action: 'open-person', contact: { crmContactId } }`.
608
+ - Limits: `name` 200, `email` 320, `phone` 40, `channel` 40, ids 100, `messageSnippet` 280. A message
609
+ that is malformed, has an unknown action or any oversize field is dropped whole and never
610
+ reaches `onHostAction`. Nothing is delivered before the handshake completes.
611
+ - The handler gets `requestId` (the CRM's id for the click). Nothing is returned to the CRM.
612
+
613
+ **Security notes**
614
+
615
+ - Capabilities only decide what the CRM's UI offers. They are not authorisation. The embedded
616
+ page is a third-party document in your page: treat every field of every action as untrusted
617
+ input, check on your server that the signed-in user may do it, and never trust
618
+ `crmContactId` without looking it up for that user's workspace.
619
+ - Do not put contact details in URLs. Open your own form from in-memory state (or a server
620
+ side draft) rather than `?phone=...&name=...`, so names and numbers stay out of logs,
621
+ history and referrers.
622
+ - `hostName` and the snippet are plain text. Render them as text, never as HTML.
623
+
577
624
  React is an **optional peer dependency** — only pull in this entry if you use
578
625
  React. The low-level `embed-host` remains available for non-React consumers.
579
626
 
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var w=(e,n)=>{for(var r in n)m(e,r,{get:n[r],enumerable:!0})},R=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of M(n))!v.call(e,t)&&t!==r&&m(e,t,{get:()=>n[t],enumerable:!(o=H(n,t))||o.enumerable});return e};var k=e=>R(m({},"__esModule",{value:!0}),e);var L={};w(L,{buildCrmEmbedUrl:()=>P,createCrmEmbedHost:()=>I,crmSession:()=>_,encodeHostBrand:()=>p,hostContextQuery:()=>B,normalizeHostBrand:()=>u,normalizeHostContext:()=>l});module.exports=k(L);var E=["light","dark","system"],A=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,T=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,F=/^(\d{1,2}(?:\.\d{1,2})?)px$/,$=/^[A-Za-z0-9 ,'"_-]+$/;var O=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function h(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n.length>160||!$.test(n))&&!((n.match(/"/g)?.length??0)%2!==0||(n.match(/'/g)?.length??0)%2!==0))return n}function u(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let t of O){let a=e[t];if(typeof a=="string"&&T.test(a.trim())){let c=a.trim().toLowerCase();c.length===4&&(c=`#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`),n[t]=c}}if(typeof e.radius=="string"){let t=F.exec(e.radius.trim());t&&Number(t[1])<=24&&(n.radius=`${Number(t[1])}px`)}let r=h(e.fontFamily);r&&(n.fontFamily=r);let o=h(e.displayFontFamily);return o&&(n.displayFontFamily=o),Object.keys(n).length>0?n:void 0}function p(e){let n=u(e);if(!n)return null;let r=new TextEncoder().encode(JSON.stringify(n)),o="";r.forEach(a=>{o+=String.fromCharCode(a)});let t=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return t.length<=1500?t:null}function l(e){let n={};if(e?.brand===null)n.brand=null;else{let r=u(e?.brand);r&&(n.brand=r)}return e?.theme&&E.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&A.test(e.locale.trim())&&(n.locale=e.locale.trim()),n}function B(e){let n=l(e),r=[];n.theme&&r.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&r.push(`locale=${encodeURIComponent(n.locale)}`);let o=n.brand?p(n.brand):null;return o&&r.push(`brand=${o}`),r}function S(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function _(e,n){return async()=>{let r=await fetch(e,{method:"POST",...n}),o=await r.json().catch(()=>({}));if(!r.ok){let a=o?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${r.status})`)}let t=o;if(typeof t?.accessToken!="string"||typeof t?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return t}}function P(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function I(e){let n=e.windowTarget??window,r=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,t=null,a="",c=!1,d=l(e.hostContext);function g(s){if(s){t?.postMessage({type:"crm:host-context",...d,...s});return}if(!t||d.theme===void 0&&d.locale===void 0&&d.brand===void 0)return;let i={type:"crm:host-context",...d};t.postMessage(i)}async function f(){try{let s=await e.getBearer();return t?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),g(),!0}catch(s){return e.onError?.(s),!1}}function y(s){let i=s.data;if(i)if(i.type==="channel-ack"){if(i.nonce!==a)return;f()}else i.type==="route-change"?e.onRouteChange?.(i.path):i.type==="resize"?e.onResize?.(i.height):i.type==="session-expired"&&f().then(b=>{b&&t?.postMessage({type:"session-refreshed"})})}function x(){t?.close();let s=r();t=s.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,t.onmessage=y,t.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[s.port2])}function C(s){c||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||S(s.data)&&x())}return n.addEventListener("message",C),{navigate(s){t?.postMessage({type:"navigate",path:s})},setContext(s){let i=l(s);d={...d,...i},i.brand===null&&delete d.brand,g(i.brand===null?{brand:null}:void 0)},dispose(){c=!0,n.removeEventListener("message",C),t?.close(),t=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost,crmSession,encodeHostBrand,hostContextQuery,normalizeHostBrand,normalizeHostContext});
1
+ "use strict";var y=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var x=(e,n)=>{for(var t in n)y(e,t,{get:n[t],enumerable:!0})},O=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of T(n))!E.call(e,r)&&r!==t&&y(e,r,{get:()=>n[r],enumerable:!(o=b(n,r))||o.enumerable});return e};var N=e=>O(y({},"__esModule",{value:!0}),e);var z={};x(z,{HOST_ACTION_SNIPPET_MAX:()=>w,buildCrmEmbedUrl:()=>q,createCrmEmbedHost:()=>D,crmSession:()=>L,encodeHostBrand:()=>I,hostContextQuery:()=>$,normalizeHostBrand:()=>H,normalizeHostContext:()=>A,parseHostActionMessage:()=>_});module.exports=N(z);var R=["create-lead","open-person"];var w=280,k=["light","dark","system"],v=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,S=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,X=/^(\d{1,2}(?:\.\d{1,2})?)px$/,P=/^[A-Za-z0-9 ,'"_-]+$/;var F=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function M(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n.length>160||!P.test(n))&&!((n.match(/"/g)?.length??0)%2!==0||(n.match(/'/g)?.length??0)%2!==0))return n}function H(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let r of F){let a=e[r];if(typeof a=="string"&&S.test(a.trim())){let i=a.trim().toLowerCase();i.length===4&&(i=`#${i[1]}${i[1]}${i[2]}${i[2]}${i[3]}${i[3]}`),n[r]=i}}if(typeof e.radius=="string"){let r=X.exec(e.radius.trim());r&&Number(r[1])<=24&&(n.radius=`${Number(r[1])}px`)}let t=M(e.fontFamily);t&&(n.fontFamily=t);let o=M(e.displayFontFamily);return o&&(n.displayFontFamily=o),Object.keys(n).length>0?n:void 0}function I(e){let n=H(e);if(!n)return null;let t=new TextEncoder().encode(JSON.stringify(n)),o="";t.forEach(a=>{o+=String.fromCharCode(a)});let r=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return r.length<=1500?r:null}function A(e){let n={};if(e?.brand===null)n.brand=null;else{let t=H(e?.brand);t&&(n.brand=t)}if(e?.theme&&k.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&v.test(e.locale.trim())&&(n.locale=e.locale.trim()),Array.isArray(e?.capabilities)){let t=e.capabilities.filter(o=>R.includes(o));n.capabilities=[...new Set(t)].slice(0,8)}if(typeof e?.hostName=="string"){let t=e.hostName.trim();t&&t.length<=40&&!/[\u0000-\u001f\u007f]/.test(t)&&(n.hostName=t)}return n}function d(e,n,t){if(e===void 0)return t?null:void 0;if(typeof e!="string")return null;let o=e.trim();return o.length>n?null:o||(t?null:void 0)}function _(e){if(!e||typeof e!="object")return null;let n=e;if(n.type!=="crm:host-action")return null;let t=d(n.requestId,64,!0);if(!t)return null;let o=n.contact;if(!o||typeof o!="object"||Array.isArray(o))return null;let r=o,a=d(r.crmContactId,100,!0);if(!a)return null;if(n.action==="open-person")return{requestId:t,action:"open-person",contact:{crmContactId:a}};if(n.action!=="create-lead")return null;let i=d(r.name,200,!1),u=d(r.phone,40,!1),l=d(r.email,320,!1),C=d(n.conversationId,100,!0),m=d(n.channel,40,!1),p=d(n.messageSnippet,280,!1);if([i,u,l,m,p].some(s=>s===null)||!C)return null;let f={crmContactId:a};i&&(f.name=i),u&&(f.phone=u),l&&(f.email=l);let g={requestId:t,action:"create-lead",contact:f,conversationId:C};return m&&(g.channel=m),p&&(g.messageSnippet=p),g}function $(e){let n=A(e),t=[];n.theme&&t.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&t.push(`locale=${encodeURIComponent(n.locale)}`);let o=n.brand?I(n.brand):null;return o&&t.push(`brand=${o}`),t}function B(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function L(e,n){return async()=>{let t=await fetch(e,{method:"POST",...n}),o=await t.json().catch(()=>({}));if(!t.ok){let a=o?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${t.status})`)}let r=o;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function q(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function D(e){let n=e.windowTarget??window,t=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,a="",i=!1,u=!1,l=A(e.hostContext);function C(s){if(s){r?.postMessage({type:"crm:host-context",...l,...s});return}if(!r||Object.keys(l).length===0)return;let c={type:"crm:host-context",...l};r.postMessage(c)}async function m(){try{let s=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),C(),!0}catch(s){return e.onError?.(s),!1}}function p(s){let c=s.data;if(c)if(c.type==="channel-ack"){if(c.nonce!==a)return;i=!0,m()}else if(c.type==="route-change")e.onRouteChange?.(c.path);else if(c.type==="crm:host-action"){if(!i)return;let h=_(c);h&&e.onHostAction?.(h)}else c.type==="resize"?e.onResize?.(c.height):c.type==="session-expired"&&m().then(h=>{h&&r?.postMessage({type:"session-refreshed"})})}function f(){r?.close(),i=!1;let s=t();r=s.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=p,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[s.port2])}function g(s){u||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||B(s.data)&&f())}return n.addEventListener("message",g),{navigate(s){r?.postMessage({type:"navigate",path:s})},setContext(s){let c=A(s);l={...l,...c},c.brand===null&&delete l.brand,C(c.brand===null?{brand:null}:void 0)},dispose(){u=!0,n.removeEventListener("message",g),r?.close(),r=null}}}0&&(module.exports={HOST_ACTION_SNIPPET_MAX,buildCrmEmbedUrl,createCrmEmbedHost,crmSession,encodeHostBrand,hostContextQuery,normalizeHostBrand,normalizeHostContext,parseHostActionMessage});
2
2
  //# sourceMappingURL=embed-host.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || (context.theme === undefined && context.locale === undefined && context.brand === undefined)) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,eAAAC,EAAA,oBAAAC,EAAA,qBAAAC,EAAA,uBAAAC,EAAA,yBAAAC,IAAA,eAAAC,EAAAT,GAkFA,IAAMU,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAEbC,EAAY,kCACZC,EAAY,8BACZC,EAAa,uBAInB,IAAMC,EAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GAAI,GAACC,GAAKA,EAAE,OAAS,KAAY,CAACC,EAAW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AAO,IAAK,EAAI,MAAS,CAC/D,EACA,SAAgB,CACdhB,EAAW,GACXL,EAAO,oBAAoB,UAAWkB,CAAgC,EACtEf,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","encodeHostBrand","hostContextQuery","normalizeHostBrand","normalizeHostContext","__toCommonJS","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","hostContextQuery","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","next"]}
1
+ {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n * The same message carries `capabilities` (which host actions the CRM may offer) and\n * `hostName` (a label for the host app). Those two ride on the channel only, never the URL.\n * 7. CRM iframe sends { type: 'crm:host-action', requestId, action: ... } when the user asks for\n * something only the host can do (see {@link CrmHostAction}). Delivered to `onHostAction`.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */\nexport type CrmHostCapability = 'create-lead' | 'open-person';\n\n/** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */\nexport interface CrmHostActionContact {\n /** The CRM contact id. */\n crmContactId: string;\n name?: string;\n phone?: string;\n email?: string;\n}\n\n/**\n * Something the user asked the host to do from inside the embedded CRM.\n * Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side\n * and treat every field as untrusted input.\n */\nexport type CrmHostAction =\n | {\n action: 'create-lead';\n contact: CrmHostActionContact;\n conversationId: string;\n /** Channel of the conversation, e.g. \"whatsapp\". */\n channel?: string;\n /** The last inbound message text, at most 280 characters. */\n messageSnippet?: string;\n }\n | { action: 'open-person'; contact: { crmContactId: string } };\n\n/** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */\nexport type CrmHostActionRequest = CrmHostAction & { requestId: string };\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n /**\n * Host actions the CRM may offer. Channel only (never in the URL). Known values only,\n * de-duplicated, at most 8. A new list REPLACES the old one; `[]` turns every action off.\n * Omitted: unchanged (none before the first value).\n */\n capabilities?: CrmHostCapability[];\n /** Short name of the host app (max 40 chars), shown on buttons and cards, e.g. \"myEdu\". Channel only. */\n hostName?: string;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_CAPABILITIES: readonly string[] = ['create-lead', 'open-person'];\nconst CAPABILITIES_MAX = 8;\nconst HOST_NAME_MAX = 40;\nconst ACTION_REQUEST_ID_MAX = 64;\nconst ACTION_ID_MAX = 100;\nconst ACTION_NAME_MAX = 200;\nconst ACTION_EMAIL_MAX = 320;\nconst ACTION_PHONE_MAX = 40;\nconst ACTION_CHANNEL_MAX = 40;\n/** Longest `messageSnippet` the CRM sends and the host accepts. */\nexport const HOST_ACTION_SNIPPET_MAX = 280;\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n if (Array.isArray(ctx?.capabilities)) {\n const known = ctx.capabilities.filter((c): c is CrmHostCapability => HOST_CAPABILITIES.includes(c));\n out.capabilities = [...new Set(known)].slice(0, CAPABILITIES_MAX);\n }\n if (typeof ctx?.hostName === 'string') {\n const name = ctx.hostName.trim();\n if (name && name.length <= HOST_NAME_MAX && !/[\\u0000-\\u001f\\u007f]/.test(name)) out.hostName = name;\n }\n return out;\n}\n\nfunction boundedString(value: unknown, max: number, required: boolean): string | undefined | null {\n if (value === undefined) return required ? null : undefined;\n if (typeof value !== 'string') return null;\n const v = value.trim();\n if (v.length > max) return null;\n if (!v) return required ? null : undefined;\n return v;\n}\n\n/**\n * Validates a `crm:host-action` port message. Returns a clean request, or null when the\n * message is malformed, has an unknown action, or any field is too long. Unknown fields are\n * dropped. Never throws.\n */\nexport function parseHostActionMessage(data: unknown): CrmHostActionRequest | null {\n if (!data || typeof data !== 'object') return null;\n const m = data as Record<string, unknown>;\n if (m.type !== 'crm:host-action') return null;\n const requestId = boundedString(m.requestId, ACTION_REQUEST_ID_MAX, true);\n if (!requestId) return null;\n const c = m.contact;\n if (!c || typeof c !== 'object' || Array.isArray(c)) return null;\n const rc = c as Record<string, unknown>;\n const crmContactId = boundedString(rc.crmContactId, ACTION_ID_MAX, true);\n if (!crmContactId) return null;\n\n if (m.action === 'open-person') {\n return { requestId, action: 'open-person', contact: { crmContactId } };\n }\n if (m.action !== 'create-lead') return null;\n\n const name = boundedString(rc.name, ACTION_NAME_MAX, false);\n const phone = boundedString(rc.phone, ACTION_PHONE_MAX, false);\n const email = boundedString(rc.email, ACTION_EMAIL_MAX, false);\n const conversationId = boundedString(m.conversationId, ACTION_ID_MAX, true);\n const channel = boundedString(m.channel, ACTION_CHANNEL_MAX, false);\n const messageSnippet = boundedString(m.messageSnippet, HOST_ACTION_SNIPPET_MAX, false);\n if ([name, phone, email, channel, messageSnippet].some((v) => v === null) || !conversationId) return null;\n\n const contact: CrmHostActionContact = { crmContactId };\n if (name) contact.name = name;\n if (phone) contact.phone = phone;\n if (email) contact.email = email;\n const out: CrmHostActionRequest = {\n requestId, action: 'create-lead', contact, conversationId,\n };\n if (channel) out.channel = channel;\n if (messageSnippet) out.messageSnippet = messageSnippet;\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * Called when the user asks for something only the host can do (a {@link CrmHostAction}).\n * Messages that are malformed, oversize or of an unknown action never reach it, and nothing\n * is delivered before the handshake completes. Re-authorise every action on your server.\n */\n onHostAction?: (request: CrmHostActionRequest) => void;\n /** Initial theme/locale/capabilities, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' }\n | { type: 'crm:host-action'; requestId: string };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let acked = false;\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || Object.keys(context).length === 0) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n acked = true;\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'crm:host-action') {\n if (!acked) return; // nothing counts before the handshake completes\n const request = parseHostActionMessage(data);\n if (request) opts.onHostAction?.(request);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n acked = false;\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,qBAAAC,EAAA,uBAAAC,EAAA,eAAAC,EAAA,oBAAAC,EAAA,qBAAAC,EAAA,uBAAAC,EAAA,yBAAAC,EAAA,2BAAAC,IAAA,eAAAC,EAAAX,GA8HA,IAAMY,EAAuC,CAAC,cAAe,aAAa,EAUnE,IAAMC,EAA0B,IAEjCC,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAEbC,EAAY,kCACZC,EAAY,8BACZC,EAAa,uBAInB,IAAMC,EAAmB,CACvB,SAAU,mBAA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AAWxB,EAAK,MAAM,EAClBA,EAAK,OAAS,mBAIlBoC,EAAc,EAAE,KAAMM,GAAO,CAC5BA,GAAId,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,CACzD,CAAC,CAEL,CAEA,SAASe,GAAuB,CAC9Bf,GAAM,MAAM,EACZE,EAAQ,GACR,IAAMvB,EAAUmB,EAAY,EAC5BE,EAAOrB,EAAQ,MACfsB,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYW,EACjBX,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACpB,EAAQ,KAAK,CAChB,CACF,CAEA,SAASqC,EAAgBC,EAA2B,CAC9Cd,GACAc,EAAM,SAAWrB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBqB,EAAM,SAAWrB,EAAK,WACjDZ,EAAQiC,EAAM,IAAI,GAAGF,EAAe,EAC1C,CAEA,OAAAlB,EAAO,iBAAiB,UAAWmB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BlB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAkB,CAAK,CAAC,CAC9C,EACA,WAAWzD,EAA2B,CACpC,IAAM0D,EAAO3D,EAAqBC,CAAG,EACrC2C,EAAU,CAAE,GAAGA,EAAS,GAAGe,CAAK,EAC5BA,EAAK,QAAU,MAAM,OAAOf,EAAQ,MACxCC,EAAYc,EAAK,QAAU,KAAO,CAAE,MAAO,IAAK,EAAI,MAAS,CAC/D,EACA,SAAgB,CACdhB,EAAW,GACXN,EAAO,oBAAoB,UAAWmB,CAAgC,EACtEhB,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","HOST_ACTION_SNIPPET_MAX","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","encodeHostBrand","hostContextQuery","normalizeHostBrand","normalizeHostContext","parseHostActionMessage","__toCommonJS","HOST_CAPABILITIES","HOST_ACTION_SNIPPET_MAX","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","known","c","HOST_CAPABILITIES","name","boundedString","max","required","parseHostActionMessage","data","requestId","rc","crmContactId","phone","email","conversationId","channel","messageSnippet","contact","hostContextQuery","pairs","isReady","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","acked","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","request","ok","startHandshake","onWindowMessage","event","path","next"]}
@@ -17,6 +17,10 @@
17
17
  * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
18
18
  * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the
19
19
  * frame paints in the right theme before the handshake finishes.
20
+ * The same message carries `capabilities` (which host actions the CRM may offer) and
21
+ * `hostName` (a label for the host app). Those two ride on the channel only, never the URL.
22
+ * 7. CRM iframe sends { type: 'crm:host-action', requestId, action: ... } when the user asks for
23
+ * something only the host can do (see {@link CrmHostAction}). Delivered to `onHostAction`.
20
24
  *
21
25
  * @packageDocumentation
22
26
  */
@@ -55,6 +59,39 @@ interface CrmHostBrand {
55
59
  /** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
56
60
  displayFontFamily?: string;
57
61
  }
62
+ /** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */
63
+ type CrmHostCapability = 'create-lead' | 'open-person';
64
+ /** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */
65
+ interface CrmHostActionContact {
66
+ /** The CRM contact id. */
67
+ crmContactId: string;
68
+ name?: string;
69
+ phone?: string;
70
+ email?: string;
71
+ }
72
+ /**
73
+ * Something the user asked the host to do from inside the embedded CRM.
74
+ * Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side
75
+ * and treat every field as untrusted input.
76
+ */
77
+ type CrmHostAction = {
78
+ action: 'create-lead';
79
+ contact: CrmHostActionContact;
80
+ conversationId: string;
81
+ /** Channel of the conversation, e.g. "whatsapp". */
82
+ channel?: string;
83
+ /** The last inbound message text, at most 280 characters. */
84
+ messageSnippet?: string;
85
+ } | {
86
+ action: 'open-person';
87
+ contact: {
88
+ crmContactId: string;
89
+ };
90
+ };
91
+ /** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */
92
+ type CrmHostActionRequest = CrmHostAction & {
93
+ requestId: string;
94
+ };
58
95
  /**
59
96
  * Look and language the host passes to the embedded CRM. Both are optional; an omitted
60
97
  * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
@@ -69,11 +106,21 @@ interface CrmHostContext {
69
106
  * returns the CRM to its own look. Omitted: unchanged.
70
107
  */
71
108
  brand?: CrmHostBrand | null;
109
+ /**
110
+ * Host actions the CRM may offer. Channel only (never in the URL). Known values only,
111
+ * de-duplicated, at most 8. A new list REPLACES the old one; `[]` turns every action off.
112
+ * Omitted: unchanged (none before the first value).
113
+ */
114
+ capabilities?: CrmHostCapability[];
115
+ /** Short name of the host app (max 40 chars), shown on buttons and cards, e.g. "myEdu". Channel only. */
116
+ hostName?: string;
72
117
  }
73
118
  /** The message the host posts on the channel port to update {@link CrmHostContext}. */
74
119
  interface CrmHostContextMessage extends CrmHostContext {
75
120
  type: 'crm:host-context';
76
121
  }
122
+ /** Longest `messageSnippet` the CRM sends and the host accepts. */
123
+ declare const HOST_ACTION_SNIPPET_MAX = 280;
77
124
  /**
78
125
  * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and
79
126
  * safe font-family lists. Returns undefined when nothing valid is left.
@@ -87,6 +134,12 @@ declare function encodeHostBrand(brand: CrmHostBrand | undefined | null): string
87
134
  * the message. `brand: null` is kept so a message can clear an earlier brand.
88
135
  */
89
136
  declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
137
+ /**
138
+ * Validates a `crm:host-action` port message. Returns a clean request, or null when the
139
+ * message is malformed, has an unknown action, or any field is too long. Unknown fields are
140
+ * dropped. Never throws.
141
+ */
142
+ declare function parseHostActionMessage(data: unknown): CrmHostActionRequest | null;
90
143
  /** `theme`, `locale` and `brand` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN", "brand=eyJ..."]`). */
91
144
  declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
92
145
  interface CrmEmbedHostOptions {
@@ -110,7 +163,13 @@ interface CrmEmbedHostOptions {
110
163
  onResize?: (height: number) => void;
111
164
  /** Called on any handshake/bearer error. */
112
165
  onError?: (err: unknown) => void;
113
- /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */
166
+ /**
167
+ * Called when the user asks for something only the host can do (a {@link CrmHostAction}).
168
+ * Messages that are malformed, oversize or of an unknown action never reach it, and nothing
169
+ * is delivered before the handshake completes. Re-authorise every action on your server.
170
+ */
171
+ onHostAction?: (request: CrmHostActionRequest) => void;
172
+ /** Initial theme/locale/capabilities, sent to the CRM once the channel is up. Change it with `setContext()`. */
114
173
  hostContext?: CrmHostContext;
115
174
  /**
116
175
  * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
@@ -165,4 +224,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
165
224
  */
166
225
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
167
226
 
168
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostBrand, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, encodeHostBrand, hostContextQuery, normalizeHostBrand, normalizeHostContext };
227
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostAction, type CrmHostActionContact, type CrmHostActionRequest, type CrmHostBrand, type CrmHostCapability, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, HOST_ACTION_SNIPPET_MAX, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, encodeHostBrand, hostContextQuery, normalizeHostBrand, normalizeHostContext, parseHostActionMessage };
@@ -17,6 +17,10 @@
17
17
  * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
18
18
  * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the
19
19
  * frame paints in the right theme before the handshake finishes.
20
+ * The same message carries `capabilities` (which host actions the CRM may offer) and
21
+ * `hostName` (a label for the host app). Those two ride on the channel only, never the URL.
22
+ * 7. CRM iframe sends { type: 'crm:host-action', requestId, action: ... } when the user asks for
23
+ * something only the host can do (see {@link CrmHostAction}). Delivered to `onHostAction`.
20
24
  *
21
25
  * @packageDocumentation
22
26
  */
@@ -55,6 +59,39 @@ interface CrmHostBrand {
55
59
  /** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
56
60
  displayFontFamily?: string;
57
61
  }
62
+ /** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */
63
+ type CrmHostCapability = 'create-lead' | 'open-person';
64
+ /** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */
65
+ interface CrmHostActionContact {
66
+ /** The CRM contact id. */
67
+ crmContactId: string;
68
+ name?: string;
69
+ phone?: string;
70
+ email?: string;
71
+ }
72
+ /**
73
+ * Something the user asked the host to do from inside the embedded CRM.
74
+ * Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side
75
+ * and treat every field as untrusted input.
76
+ */
77
+ type CrmHostAction = {
78
+ action: 'create-lead';
79
+ contact: CrmHostActionContact;
80
+ conversationId: string;
81
+ /** Channel of the conversation, e.g. "whatsapp". */
82
+ channel?: string;
83
+ /** The last inbound message text, at most 280 characters. */
84
+ messageSnippet?: string;
85
+ } | {
86
+ action: 'open-person';
87
+ contact: {
88
+ crmContactId: string;
89
+ };
90
+ };
91
+ /** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */
92
+ type CrmHostActionRequest = CrmHostAction & {
93
+ requestId: string;
94
+ };
58
95
  /**
59
96
  * Look and language the host passes to the embedded CRM. Both are optional; an omitted
60
97
  * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
@@ -69,11 +106,21 @@ interface CrmHostContext {
69
106
  * returns the CRM to its own look. Omitted: unchanged.
70
107
  */
71
108
  brand?: CrmHostBrand | null;
109
+ /**
110
+ * Host actions the CRM may offer. Channel only (never in the URL). Known values only,
111
+ * de-duplicated, at most 8. A new list REPLACES the old one; `[]` turns every action off.
112
+ * Omitted: unchanged (none before the first value).
113
+ */
114
+ capabilities?: CrmHostCapability[];
115
+ /** Short name of the host app (max 40 chars), shown on buttons and cards, e.g. "myEdu". Channel only. */
116
+ hostName?: string;
72
117
  }
73
118
  /** The message the host posts on the channel port to update {@link CrmHostContext}. */
74
119
  interface CrmHostContextMessage extends CrmHostContext {
75
120
  type: 'crm:host-context';
76
121
  }
122
+ /** Longest `messageSnippet` the CRM sends and the host accepts. */
123
+ declare const HOST_ACTION_SNIPPET_MAX = 280;
77
124
  /**
78
125
  * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and
79
126
  * safe font-family lists. Returns undefined when nothing valid is left.
@@ -87,6 +134,12 @@ declare function encodeHostBrand(brand: CrmHostBrand | undefined | null): string
87
134
  * the message. `brand: null` is kept so a message can clear an earlier brand.
88
135
  */
89
136
  declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
137
+ /**
138
+ * Validates a `crm:host-action` port message. Returns a clean request, or null when the
139
+ * message is malformed, has an unknown action, or any field is too long. Unknown fields are
140
+ * dropped. Never throws.
141
+ */
142
+ declare function parseHostActionMessage(data: unknown): CrmHostActionRequest | null;
90
143
  /** `theme`, `locale` and `brand` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN", "brand=eyJ..."]`). */
91
144
  declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
92
145
  interface CrmEmbedHostOptions {
@@ -110,7 +163,13 @@ interface CrmEmbedHostOptions {
110
163
  onResize?: (height: number) => void;
111
164
  /** Called on any handshake/bearer error. */
112
165
  onError?: (err: unknown) => void;
113
- /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */
166
+ /**
167
+ * Called when the user asks for something only the host can do (a {@link CrmHostAction}).
168
+ * Messages that are malformed, oversize or of an unknown action never reach it, and nothing
169
+ * is delivered before the handshake completes. Re-authorise every action on your server.
170
+ */
171
+ onHostAction?: (request: CrmHostActionRequest) => void;
172
+ /** Initial theme/locale/capabilities, sent to the CRM once the channel is up. Change it with `setContext()`. */
114
173
  hostContext?: CrmHostContext;
115
174
  /**
116
175
  * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
@@ -165,4 +224,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
165
224
  */
166
225
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
167
226
 
168
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostBrand, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, encodeHostBrand, hostContextQuery, normalizeHostBrand, normalizeHostContext };
227
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostAction, type CrmHostActionContact, type CrmHostActionRequest, type CrmHostBrand, type CrmHostCapability, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, HOST_ACTION_SNIPPET_MAX, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, encodeHostBrand, hostContextQuery, normalizeHostBrand, normalizeHostContext, parseHostActionMessage };
@@ -1,2 +1,2 @@
1
- var x=["light","dark","system"],b=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,H=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,M=/^(\d{1,2}(?:\.\d{1,2})?)px$/,v=/^[A-Za-z0-9 ,'"_-]+$/;var w=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function f(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n.length>160||!v.test(n))&&!((n.match(/"/g)?.length??0)%2!==0||(n.match(/'/g)?.length??0)%2!==0))return n}function C(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let t of w){let a=e[t];if(typeof a=="string"&&H.test(a.trim())){let c=a.trim().toLowerCase();c.length===4&&(c=`#${c[1]}${c[1]}${c[2]}${c[2]}${c[3]}${c[3]}`),n[t]=c}}if(typeof e.radius=="string"){let t=M.exec(e.radius.trim());t&&Number(t[1])<=24&&(n.radius=`${Number(t[1])}px`)}let s=f(e.fontFamily);s&&(n.fontFamily=s);let i=f(e.displayFontFamily);return i&&(n.displayFontFamily=i),Object.keys(n).length>0?n:void 0}function R(e){let n=C(e);if(!n)return null;let s=new TextEncoder().encode(JSON.stringify(n)),i="";s.forEach(a=>{i+=String.fromCharCode(a)});let t=btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return t.length<=1500?t:null}function l(e){let n={};if(e?.brand===null)n.brand=null;else{let s=C(e?.brand);s&&(n.brand=s)}return e?.theme&&x.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&b.test(e.locale.trim())&&(n.locale=e.locale.trim()),n}function E(e){let n=l(e),s=[];n.theme&&s.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&s.push(`locale=${encodeURIComponent(n.locale)}`);let i=n.brand?R(n.brand):null;return i&&s.push(`brand=${i}`),s}function k(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function A(e,n){return async()=>{let s=await fetch(e,{method:"POST",...n}),i=await s.json().catch(()=>({}));if(!s.ok){let a=i?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${s.status})`)}let t=i;if(typeof t?.accessToken!="string"||typeof t?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return t}}function T(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function F(e){let n=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),i=e.devAllowAnyOrigin?"*":e.crmOrigin,t=null,a="",c=!1,d=l(e.hostContext);function m(r){if(r){t?.postMessage({type:"crm:host-context",...d,...r});return}if(!t||d.theme===void 0&&d.locale===void 0&&d.brand===void 0)return;let o={type:"crm:host-context",...d};t.postMessage(o)}async function u(){try{let r=await e.getBearer();return t?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""}),m(),!0}catch(r){return e.onError?.(r),!1}}function h(r){let o=r.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==a)return;u()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&u().then(y=>{y&&t?.postMessage({type:"session-refreshed"})})}function p(){t?.close();let r=s();t=r.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,t.onmessage=h,t.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},i,[r.port2])}function g(r){c||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||k(r.data)&&p())}return n.addEventListener("message",g),{navigate(r){t?.postMessage({type:"navigate",path:r})},setContext(r){let o=l(r);d={...d,...o},o.brand===null&&delete d.brand,m(o.brand===null?{brand:null}:void 0)},dispose(){c=!0,n.removeEventListener("message",g),t?.close(),t=null}}}export{T as buildCrmEmbedUrl,F as createCrmEmbedHost,A as crmSession,R as encodeHostBrand,E as hostContextQuery,C as normalizeHostBrand,l as normalizeHostContext};
1
+ var M=["create-lead","open-person"];var w=280,I=["light","dark","system"],_=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/,b=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,T=/^(\d{1,2}(?:\.\d{1,2})?)px$/,E=/^[A-Za-z0-9 ,'"_-]+$/;var x=["accent","accentForeground","background","surface","border","foreground","mutedForeground"];function y(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n.length>160||!E.test(n))&&!((n.match(/"/g)?.length??0)%2!==0||(n.match(/'/g)?.length??0)%2!==0))return n}function H(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n={};for(let r of x){let a=e[r];if(typeof a=="string"&&b.test(a.trim())){let i=a.trim().toLowerCase();i.length===4&&(i=`#${i[1]}${i[1]}${i[2]}${i[2]}${i[3]}${i[3]}`),n[r]=i}}if(typeof e.radius=="string"){let r=T.exec(e.radius.trim());r&&Number(r[1])<=24&&(n.radius=`${Number(r[1])}px`)}let t=y(e.fontFamily);t&&(n.fontFamily=t);let o=y(e.displayFontFamily);return o&&(n.displayFontFamily=o),Object.keys(n).length>0?n:void 0}function O(e){let n=H(e);if(!n)return null;let t=new TextEncoder().encode(JSON.stringify(n)),o="";t.forEach(a=>{o+=String.fromCharCode(a)});let r=btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return r.length<=1500?r:null}function A(e){let n={};if(e?.brand===null)n.brand=null;else{let t=H(e?.brand);t&&(n.brand=t)}if(e?.theme&&I.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&_.test(e.locale.trim())&&(n.locale=e.locale.trim()),Array.isArray(e?.capabilities)){let t=e.capabilities.filter(o=>M.includes(o));n.capabilities=[...new Set(t)].slice(0,8)}if(typeof e?.hostName=="string"){let t=e.hostName.trim();t&&t.length<=40&&!/[\u0000-\u001f\u007f]/.test(t)&&(n.hostName=t)}return n}function d(e,n,t){if(e===void 0)return t?null:void 0;if(typeof e!="string")return null;let o=e.trim();return o.length>n?null:o||(t?null:void 0)}function N(e){if(!e||typeof e!="object")return null;let n=e;if(n.type!=="crm:host-action")return null;let t=d(n.requestId,64,!0);if(!t)return null;let o=n.contact;if(!o||typeof o!="object"||Array.isArray(o))return null;let r=o,a=d(r.crmContactId,100,!0);if(!a)return null;if(n.action==="open-person")return{requestId:t,action:"open-person",contact:{crmContactId:a}};if(n.action!=="create-lead")return null;let i=d(r.name,200,!1),u=d(r.phone,40,!1),l=d(r.email,320,!1),C=d(n.conversationId,100,!0),m=d(n.channel,40,!1),p=d(n.messageSnippet,280,!1);if([i,u,l,m,p].some(s=>s===null)||!C)return null;let f={crmContactId:a};i&&(f.name=i),u&&(f.phone=u),l&&(f.email=l);let g={requestId:t,action:"create-lead",contact:f,conversationId:C};return m&&(g.channel=m),p&&(g.messageSnippet=p),g}function k(e){let n=A(e),t=[];n.theme&&t.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&t.push(`locale=${encodeURIComponent(n.locale)}`);let o=n.brand?O(n.brand):null;return o&&t.push(`brand=${o}`),t}function R(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function v(e,n){return async()=>{let t=await fetch(e,{method:"POST",...n}),o=await t.json().catch(()=>({}));if(!t.ok){let a=o?.error;throw new Error(a?`CRM session failed: ${a}`:`CRM session failed (HTTP ${t.status})`)}let r=o;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function S(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function X(e){let n=e.windowTarget??window,t=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,a="",i=!1,u=!1,l=A(e.hostContext);function C(s){if(s){r?.postMessage({type:"crm:host-context",...l,...s});return}if(!r||Object.keys(l).length===0)return;let c={type:"crm:host-context",...l};r.postMessage(c)}async function m(){try{let s=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),C(),!0}catch(s){return e.onError?.(s),!1}}function p(s){let c=s.data;if(c)if(c.type==="channel-ack"){if(c.nonce!==a)return;i=!0,m()}else if(c.type==="route-change")e.onRouteChange?.(c.path);else if(c.type==="crm:host-action"){if(!i)return;let h=N(c);h&&e.onHostAction?.(h)}else c.type==="resize"?e.onResize?.(c.height):c.type==="session-expired"&&m().then(h=>{h&&r?.postMessage({type:"session-refreshed"})})}function f(){r?.close(),i=!1;let s=t();r=s.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=p,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[s.port2])}function g(s){u||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||R(s.data)&&f())}return n.addEventListener("message",g),{navigate(s){r?.postMessage({type:"navigate",path:s})},setContext(s){let c=A(s);l={...l,...c},c.brand===null&&delete l.brand,C(c.brand===null?{brand:null}:void 0)},dispose(){u=!0,n.removeEventListener("message",g),r?.close(),r=null}}}export{w as HOST_ACTION_SNIPPET_MAX,S as buildCrmEmbedUrl,X as createCrmEmbedHost,v as crmSession,O as encodeHostBrand,k as hostContextQuery,H as normalizeHostBrand,A as normalizeHostContext,N as parseHostActionMessage};
2
2
  //# sourceMappingURL=embed-host.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || (context.theme === undefined && context.locale === undefined && context.brand === undefined)) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAkFA,IAAMA,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAEbC,EAAY,kCACZC,EAAY,8BACZC,EAAa,uBAInB,IAAMC,EAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GAAI,GAACC,GAAKA,EAAE,OAAS,KAAY,CAACC,EAAW,KAAKD,CAAC,IAC9C,GAAAA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,IAAMA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,GACnF,OAAOA,CACT,CAMO,SAASE,EAAmBC,EAAkE,CACnG,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAAG,OACjE,IAAMC,EAAoB,CAAC,EAC3B,QAAWC,KAAOR,EAAkB,CAClC,IAAMS,EAAMH,EAAME,CAAG,EACrB,GAAI,OAAOC,GAAQ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IZ,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,CACzD,CAAC,CAEL,CAEA,SAASa,GAAuB,CAC9Bb,GAAM,MAAM,EACZ,IAAMc,EAAUhB,EAAY,EAC5BE,EAAOc,EAAQ,MACfb,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYU,EACjBV,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACe,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9Cd,GACAc,EAAM,SAAWpB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBoB,EAAM,SAAWpB,EAAK,WACjDb,EAAQiC,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAhB,EAAO,iBAAiB,UAAWkB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BjB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAiB,CAAK,CAAC,CAC9C,EACA,WAAWvC,EAA2B,CACpC,IAAMwC,EAAOzC,EAAqBC,CAAG,EACrCyB,EAAU,CAAE,GAAGA,EAAS,GAAGe,CAAK,EAC5BA,EAAK,QAAU,MAAM,OAAOf,EAAQ,MACxCC,EAAYc,EAAK,QAAU,KAAO,CAAE,MAAO,IAAK,EAAI,MAAS,CAC/D,EACA,SAAgB,CACdhB,EAAW,GACXL,EAAO,oBAAoB,UAAWkB,CAAgC,EACtEf,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","hostContextQuery","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","next"]}
1
+ {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n * The same message carries `capabilities` (which host actions the CRM may offer) and\n * `hostName` (a label for the host app). Those two ride on the channel only, never the URL.\n * 7. CRM iframe sends { type: 'crm:host-action', requestId, action: ... } when the user asks for\n * something only the host can do (see {@link CrmHostAction}). Delivered to `onHostAction`.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */\nexport type CrmHostCapability = 'create-lead' | 'open-person';\n\n/** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */\nexport interface CrmHostActionContact {\n /** The CRM contact id. */\n crmContactId: string;\n name?: string;\n phone?: string;\n email?: string;\n}\n\n/**\n * Something the user asked the host to do from inside the embedded CRM.\n * Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side\n * and treat every field as untrusted input.\n */\nexport type CrmHostAction =\n | {\n action: 'create-lead';\n contact: CrmHostActionContact;\n conversationId: string;\n /** Channel of the conversation, e.g. \"whatsapp\". */\n channel?: string;\n /** The last inbound message text, at most 280 characters. */\n messageSnippet?: string;\n }\n | { action: 'open-person'; contact: { crmContactId: string } };\n\n/** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */\nexport type CrmHostActionRequest = CrmHostAction & { requestId: string };\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n /**\n * Host actions the CRM may offer. Channel only (never in the URL). Known values only,\n * de-duplicated, at most 8. A new list REPLACES the old one; `[]` turns every action off.\n * Omitted: unchanged (none before the first value).\n */\n capabilities?: CrmHostCapability[];\n /** Short name of the host app (max 40 chars), shown on buttons and cards, e.g. \"myEdu\". Channel only. */\n hostName?: string;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_CAPABILITIES: readonly string[] = ['create-lead', 'open-person'];\nconst CAPABILITIES_MAX = 8;\nconst HOST_NAME_MAX = 40;\nconst ACTION_REQUEST_ID_MAX = 64;\nconst ACTION_ID_MAX = 100;\nconst ACTION_NAME_MAX = 200;\nconst ACTION_EMAIL_MAX = 320;\nconst ACTION_PHONE_MAX = 40;\nconst ACTION_CHANNEL_MAX = 40;\n/** Longest `messageSnippet` the CRM sends and the host accepts. */\nexport const HOST_ACTION_SNIPPET_MAX = 280;\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n if (Array.isArray(ctx?.capabilities)) {\n const known = ctx.capabilities.filter((c): c is CrmHostCapability => HOST_CAPABILITIES.includes(c));\n out.capabilities = [...new Set(known)].slice(0, CAPABILITIES_MAX);\n }\n if (typeof ctx?.hostName === 'string') {\n const name = ctx.hostName.trim();\n if (name && name.length <= HOST_NAME_MAX && !/[\\u0000-\\u001f\\u007f]/.test(name)) out.hostName = name;\n }\n return out;\n}\n\nfunction boundedString(value: unknown, max: number, required: boolean): string | undefined | null {\n if (value === undefined) return required ? null : undefined;\n if (typeof value !== 'string') return null;\n const v = value.trim();\n if (v.length > max) return null;\n if (!v) return required ? null : undefined;\n return v;\n}\n\n/**\n * Validates a `crm:host-action` port message. Returns a clean request, or null when the\n * message is malformed, has an unknown action, or any field is too long. Unknown fields are\n * dropped. Never throws.\n */\nexport function parseHostActionMessage(data: unknown): CrmHostActionRequest | null {\n if (!data || typeof data !== 'object') return null;\n const m = data as Record<string, unknown>;\n if (m.type !== 'crm:host-action') return null;\n const requestId = boundedString(m.requestId, ACTION_REQUEST_ID_MAX, true);\n if (!requestId) return null;\n const c = m.contact;\n if (!c || typeof c !== 'object' || Array.isArray(c)) return null;\n const rc = c as Record<string, unknown>;\n const crmContactId = boundedString(rc.crmContactId, ACTION_ID_MAX, true);\n if (!crmContactId) return null;\n\n if (m.action === 'open-person') {\n return { requestId, action: 'open-person', contact: { crmContactId } };\n }\n if (m.action !== 'create-lead') return null;\n\n const name = boundedString(rc.name, ACTION_NAME_MAX, false);\n const phone = boundedString(rc.phone, ACTION_PHONE_MAX, false);\n const email = boundedString(rc.email, ACTION_EMAIL_MAX, false);\n const conversationId = boundedString(m.conversationId, ACTION_ID_MAX, true);\n const channel = boundedString(m.channel, ACTION_CHANNEL_MAX, false);\n const messageSnippet = boundedString(m.messageSnippet, HOST_ACTION_SNIPPET_MAX, false);\n if ([name, phone, email, channel, messageSnippet].some((v) => v === null) || !conversationId) return null;\n\n const contact: CrmHostActionContact = { crmContactId };\n if (name) contact.name = name;\n if (phone) contact.phone = phone;\n if (email) contact.email = email;\n const out: CrmHostActionRequest = {\n requestId, action: 'create-lead', contact, conversationId,\n };\n if (channel) out.channel = channel;\n if (messageSnippet) out.messageSnippet = messageSnippet;\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * Called when the user asks for something only the host can do (a {@link CrmHostAction}).\n * Messages that are malformed, oversize or of an unknown action never reach it, and nothing\n * is delivered before the handshake completes. Re-authorise every action on your server.\n */\n onHostAction?: (request: CrmHostActionRequest) => void;\n /** Initial theme/locale/capabilities, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' }\n | { type: 'crm:host-action'; requestId: string };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let acked = false;\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || Object.keys(context).length === 0) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n acked = true;\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'crm:host-action') {\n if (!acked) return; // nothing counts before the handshake completes\n const request = parseHostActionMessage(data);\n if (request) opts.onHostAction?.(request);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n acked = false;\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AA8HA,IAAMA,EAAuC,CAAC,cAAe,aAAa,EAUnE,IAAMC,EAA0B,IAEjCC,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAEbC,EAAY,kCACZC,EAAY,8BACZC,EAAa,uBAInB,IAAMC,EAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GAAI,GAACC,GAAKA,EAAE,OAAS,KAAY,CAACC,EAAW,KAAKD,CAAC,IAC9C,GAAAA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,IAAMA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,GACnF,OAAOA,CACT,CAMO,SAASE,EAAmBC,EAAkE,CACnG,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAAG,OACjE,IAAMC,EAAoB,CAAC,EAC3B,QAAWC,KAAOR,EAAkB,CAClC,IAAMS,EAAMH,EAAME,CAAG,EACrB,GAAI,OAAOC,GAAQ,UAAYC,EAAU,KAAKD,EAAI,KAAK,CAAC,EAAG,CACzD,IAAIE,EAAMF,EAAI,KAAK,EAAE,YAAY,EAC7BE,EAAI,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C,EAAM,IAAI,GAAGF,EAAe,EAC1C,CAEA,OAAAlB,EAAO,iBAAiB,UAAWmB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BlB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAkB,CAAK,CAAC,CAC9C,EACA,WAAWzD,EAA2B,CACpC,IAAM0D,EAAO3D,EAAqBC,CAAG,EACrC2C,EAAU,CAAE,GAAGA,EAAS,GAAGe,CAAK,EAC5BA,EAAK,QAAU,MAAM,OAAOf,EAAQ,MACxCC,EAAYc,EAAK,QAAU,KAAO,CAAE,MAAO,IAAK,EAAI,MAAS,CAC/D,EACA,SAAgB,CACdhB,EAAW,GACXN,EAAO,oBAAoB,UAAWmB,CAAgC,EACtEhB,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["HOST_CAPABILITIES","HOST_ACTION_SNIPPET_MAX","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","known","c","HOST_CAPABILITIES","name","boundedString","max","required","parseHostActionMessage","data","requestId","rc","crmContactId","phone","email","conversationId","channel","messageSnippet","contact","hostContextQuery","pairs","isReady","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","acked","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","request","ok","startHandshake","onWindowMessage","event","path","next"]}