@first-to-fly/crm-sdk 1.6.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.
@@ -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? } 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=` and `?locale=`), 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 * 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\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\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\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` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\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 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(): void {\n if (!port || (context.theme === undefined && context.locale === 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 context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\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,qBAAAC,EAAA,yBAAAC,IAAA,eAAAC,EAAAP,GAgDA,IAAMQ,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,EAAa,4CAMZ,SAASH,EAAqBI,EAAiD,CACpF,IAAMC,EAAsB,CAAC,EAC7B,OAAID,GAAK,OAASF,EAAY,SAASE,EAAI,KAAK,IAAGC,EAAI,MAAQD,EAAI,OAC/D,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BC,EAA2B,CAC9Cb,GACAa,EAAM,SAAWnB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBmB,EAAM,SAAWnB,EAAK,WACjDV,EAAQ6B,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAf,EAAO,iBAAiB,UAAWiB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BhB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAgB,CAAK,CAAC,CAC9C,EACA,WAAWlC,EAA2B,CACpCqB,EAAU,CAAE,GAAGA,EAAS,GAAGzB,EAAqBI,CAAG,CAAE,EACrDsB,EAAY,CACd,EACA,SAAgB,CACdF,EAAW,GACXL,EAAO,oBAAoB,UAAWiB,CAAgC,EACtEd,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","crmSession","hostContextQuery","normalizeHostContext","__toCommonJS","HOST_THEMES","BCP47_LIKE","ctx","out","clean","pairs","isReady","data","url","init","res","body","code","result","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
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,EAC3D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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"]}
@@ -13,10 +13,14 @@
13
13
  * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
14
14
  * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
15
15
  * - on 'session-expired' the host re-fetches a bearer and re-sends it.
16
- * 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,
16
+ * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,
17
17
  * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
18
- * The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the
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
  */
@@ -27,6 +31,67 @@ interface CrmBearer {
27
31
  }
28
32
  /** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
29
33
  type CrmHostTheme = 'light' | 'dark' | 'system';
34
+ /**
35
+ * Brand tokens that make the embedded CRM look like part of the host. All optional.
36
+ * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.
37
+ * Pass the values for the host's CURRENT theme and send a new brand when it toggles.
38
+ * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.
39
+ */
40
+ interface CrmHostBrand {
41
+ /** Buttons, selected tabs, focus rings, chart accent. */
42
+ accent?: string;
43
+ /** Text on the accent. Defaults to white or near-black, whichever reads better. */
44
+ accentForeground?: string;
45
+ /** Page background. */
46
+ background?: string;
47
+ /** Cards, popovers and inputs. Defaults to `background`. */
48
+ surface?: string;
49
+ /** Hairlines and input borders. Derived from background and foreground when omitted. */
50
+ border?: string;
51
+ /** Body text. */
52
+ foreground?: string;
53
+ /** Secondary text. Derived when omitted. */
54
+ mutedForeground?: string;
55
+ /** Corner radius for controls, `0px` to `24px`, e.g. `"6px"`. Larger surfaces scale from it. */
56
+ radius?: string;
57
+ /** UI font family list, e.g. `"Inter, system-ui"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */
58
+ fontFamily?: string;
59
+ /** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
60
+ displayFontFamily?: string;
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
+ };
30
95
  /**
31
96
  * Look and language the host passes to the embedded CRM. Both are optional; an omitted
32
97
  * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
@@ -36,17 +101,46 @@ interface CrmHostContext {
36
101
  theme?: CrmHostTheme;
37
102
  /** BCP 47 language tag, e.g. "en" or "zh-CN". */
38
103
  locale?: string;
104
+ /**
105
+ * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)
106
+ * returns the CRM to its own look. Omitted: unchanged.
107
+ */
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;
39
117
  }
40
118
  /** The message the host posts on the channel port to update {@link CrmHostContext}. */
41
119
  interface CrmHostContextMessage extends CrmHostContext {
42
120
  type: 'crm:host-context';
43
121
  }
122
+ /** Longest `messageSnippet` the CRM sends and the host accepts. */
123
+ declare const HOST_ACTION_SNIPPET_MAX = 280;
124
+ /**
125
+ * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and
126
+ * safe font-family lists. Returns undefined when nothing valid is left.
127
+ */
128
+ declare function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined;
129
+ /** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */
130
+ declare function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null;
44
131
  /**
45
- * Keeps only values the CRM understands: a known theme and a well-formed language tag.
46
- * Anything else is dropped, so a bad value can never reach the iframe URL or the message.
132
+ * Keeps only values the CRM understands: a known theme, a well-formed language tag and a
133
+ * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or
134
+ * the message. `brand: null` is kept so a message can clear an earlier brand.
47
135
  */
48
136
  declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
49
- /** `theme` and `locale` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN"]`). */
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;
143
+ /** `theme`, `locale` and `brand` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN", "brand=eyJ..."]`). */
50
144
  declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
51
145
  interface CrmEmbedHostOptions {
52
146
  /** The <iframe> element that loads the CRM embed URL. */
@@ -69,7 +163,13 @@ interface CrmEmbedHostOptions {
69
163
  onResize?: (height: number) => void;
70
164
  /** Called on any handshake/bearer error. */
71
165
  onError?: (err: unknown) => void;
72
- /** 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()`. */
73
173
  hostContext?: CrmHostContext;
74
174
  /**
75
175
  * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
@@ -124,4 +224,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
124
224
  */
125
225
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
126
226
 
127
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, hostContextQuery, 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 };
@@ -13,10 +13,14 @@
13
13
  * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
14
14
  * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
15
15
  * - on 'session-expired' the host re-fetches a bearer and re-sends it.
16
- * 6. host sends { type: 'crm:host-context', theme?, locale? } on the same port,
16
+ * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,
17
17
  * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.
18
- * The first values also ride on the iframe URL (`?theme=` and `?locale=`), so the
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
  */
@@ -27,6 +31,67 @@ interface CrmBearer {
27
31
  }
28
32
  /** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */
29
33
  type CrmHostTheme = 'light' | 'dark' | 'system';
34
+ /**
35
+ * Brand tokens that make the embedded CRM look like part of the host. All optional.
36
+ * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.
37
+ * Pass the values for the host's CURRENT theme and send a new brand when it toggles.
38
+ * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.
39
+ */
40
+ interface CrmHostBrand {
41
+ /** Buttons, selected tabs, focus rings, chart accent. */
42
+ accent?: string;
43
+ /** Text on the accent. Defaults to white or near-black, whichever reads better. */
44
+ accentForeground?: string;
45
+ /** Page background. */
46
+ background?: string;
47
+ /** Cards, popovers and inputs. Defaults to `background`. */
48
+ surface?: string;
49
+ /** Hairlines and input borders. Derived from background and foreground when omitted. */
50
+ border?: string;
51
+ /** Body text. */
52
+ foreground?: string;
53
+ /** Secondary text. Derived when omitted. */
54
+ mutedForeground?: string;
55
+ /** Corner radius for controls, `0px` to `24px`, e.g. `"6px"`. Larger surfaces scale from it. */
56
+ radius?: string;
57
+ /** UI font family list, e.g. `"Inter, system-ui"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */
58
+ fontFamily?: string;
59
+ /** Font for page titles, same rules as `fontFamily`, e.g. `"Fraunces, Georgia, serif"`. */
60
+ displayFontFamily?: string;
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
+ };
30
95
  /**
31
96
  * Look and language the host passes to the embedded CRM. Both are optional; an omitted
32
97
  * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only
@@ -36,17 +101,46 @@ interface CrmHostContext {
36
101
  theme?: CrmHostTheme;
37
102
  /** BCP 47 language tag, e.g. "en" or "zh-CN". */
38
103
  locale?: string;
104
+ /**
105
+ * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)
106
+ * returns the CRM to its own look. Omitted: unchanged.
107
+ */
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;
39
117
  }
40
118
  /** The message the host posts on the channel port to update {@link CrmHostContext}. */
41
119
  interface CrmHostContextMessage extends CrmHostContext {
42
120
  type: 'crm:host-context';
43
121
  }
122
+ /** Longest `messageSnippet` the CRM sends and the host accepts. */
123
+ declare const HOST_ACTION_SNIPPET_MAX = 280;
124
+ /**
125
+ * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and
126
+ * safe font-family lists. Returns undefined when nothing valid is left.
127
+ */
128
+ declare function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined;
129
+ /** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */
130
+ declare function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null;
44
131
  /**
45
- * Keeps only values the CRM understands: a known theme and a well-formed language tag.
46
- * Anything else is dropped, so a bad value can never reach the iframe URL or the message.
132
+ * Keeps only values the CRM understands: a known theme, a well-formed language tag and a
133
+ * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or
134
+ * the message. `brand: null` is kept so a message can clear an earlier brand.
47
135
  */
48
136
  declare function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext;
49
- /** `theme` and `locale` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN"]`). */
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;
143
+ /** `theme`, `locale` and `brand` as URL query pairs (e.g. `["theme=dark", "locale=zh-CN", "brand=eyJ..."]`). */
50
144
  declare function hostContextQuery(ctx: CrmHostContext | undefined): string[];
51
145
  interface CrmEmbedHostOptions {
52
146
  /** The <iframe> element that loads the CRM embed URL. */
@@ -69,7 +163,13 @@ interface CrmEmbedHostOptions {
69
163
  onResize?: (height: number) => void;
70
164
  /** Called on any handshake/bearer error. */
71
165
  onError?: (err: unknown) => void;
72
- /** 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()`. */
73
173
  hostContext?: CrmHostContext;
74
174
  /**
75
175
  * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
@@ -124,4 +224,4 @@ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): strin
124
224
  */
125
225
  declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
126
226
 
127
- export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, type CrmHostContext, type CrmHostContextMessage, type CrmHostTheme, type CrmSessionResult, buildCrmEmbedUrl, createCrmEmbedHost, crmSession, hostContextQuery, 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 p=["light","dark","system"],y=/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;function m(e){let n={};return e?.theme&&p.includes(e.theme)&&(n.theme=e.theme),typeof e?.locale=="string"&&y.test(e.locale.trim())&&(n.locale=e.locale.trim()),n}function v(e){let n=m(e),s=[];return n.theme&&s.push(`theme=${encodeURIComponent(n.theme)}`),n.locale&&s.push(`locale=${encodeURIComponent(n.locale)}`),s}function x(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function w(e,n){return async()=>{let s=await fetch(e,{method:"POST",...n}),c=await s.json().catch(()=>({}));if(!s.ok){let i=c?.error;throw new Error(i?`CRM session failed: ${i}`:`CRM session failed (HTTP ${s.status})`)}let r=c;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function M(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function H(e){let n=e.windowTarget??window,s=e.createChannel??(()=>new MessageChannel),c=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,i="",d=!1,a=m(e.hostContext);function l(){if(!r||a.theme===void 0&&a.locale===void 0)return;let t={type:"crm:host-context",...a};r.postMessage(t)}async function g(){try{let t=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:t.accessToken,refreshToken:t.refreshToken??""}),l(),!0}catch(t){return e.onError?.(t),!1}}function u(t){let o=t.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==i)return;g()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&g().then(f=>{f&&r?.postMessage({type:"session-refreshed"})})}function h(){r?.close();let t=s();r=t.port1,i=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=u,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:i},c,[t.port2])}function C(t){d||t.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&t.origin!==e.crmOrigin||x(t.data)&&h())}return n.addEventListener("message",C),{navigate(t){r?.postMessage({type:"navigate",path:t})},setContext(t){a={...a,...m(t)},l()},dispose(){d=!0,n.removeEventListener("message",C),r?.close(),r=null}}}export{M as buildCrmEmbedUrl,H as createCrmEmbedHost,w as crmSession,v as hostContextQuery,m 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? } 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=` and `?locale=`), 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 * 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\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\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\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` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\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 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(): void {\n if (!port || (context.theme === undefined && context.locale === 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 context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"m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,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYS,EACjBT,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACc,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9Cb,GACAa,EAAM,SAAWnB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBmB,EAAM,SAAWnB,EAAK,WACjDb,EAAQgC,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAf,EAAO,iBAAiB,UAAWiB,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BhB,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAgB,CAAK,CAAC,CAC9C,EACA,WAAWtC,EAA2B,CACpCyB,EAAU,CAAE,GAAGA,EAAS,GAAG1B,EAAqBC,CAAG,CAAE,EACrD0B,EAAY,CACd,EACA,SAAgB,CACdF,EAAW,GACXL,EAAO,oBAAoB,UAAWiB,CAAgC,EACtEd,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["HOST_THEMES","BCP47_LIKE","normalizeHostContext","ctx","out","hostContextQuery","clean","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
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,EAC3D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ES","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"]}