@first-to-fly/crm-sdk 1.4.0 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +232 -104
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +21 -3
- package/dist/embed-host.d.ts +21 -3
- package/dist/embed-host.js +1 -1
- package/dist/embed-host.js.map +1 -1
- package/dist/embed-react.cjs +1 -1
- package/dist/embed-react.cjs.map +1 -1
- package/dist/embed-react.d.cts +49 -24
- package/dist/embed-react.d.ts +49 -24
- package/dist/embed-react.js +1 -1
- package/dist/embed-react.js.map +1 -1
- package/dist/embed-server.cjs +1 -1
- package/dist/embed-server.cjs.map +1 -1
- package/dist/embed-server.d.cts +64 -82
- package/dist/embed-server.d.ts +64 -82
- package/dist/embed-server.js +1 -1
- package/dist/embed-server.js.map +1 -1
- package/package.json +2 -9
package/dist/embed-host.js.map
CHANGED
|
@@ -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 *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the assertion exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\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 createEmbedSession() (see ./embed-server).\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 * 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 /** 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/**\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\n async function deliverBearer(): Promise<void> {\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 } catch (err) {\n opts.onError?.(err);\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).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\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 dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAsEA,SAASA,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CASO,SAASC,EAAiBC,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASC,EAAmBC,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAA+B,CAC5C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpCI,GAAM,YAAY,CAChB,KAAM,cACN,YAAaI,EAAO,YACpB,aAAcA,EAAO,cAAgB,EACvC,CAAC,CACH,OAASC,EAAK,CACZT,EAAK,UAAUS,CAAG,CACpB,CACF,CAEA,SAASC,EAAcC,EAAqC,CAC1D,IAAMhB,EAAOgB,EAAE,KACf,GAAKhB,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUU,EAAO,OACrBE,EAAc,CACrB,MAAWZ,EAAK,OAAS,eACvBK,EAAK,gBAAgBL,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBK,EAAK,WAAWL,EAAK,MAAM,EAClBA,EAAK,OAAS,oBAElBY,EAAc,EACnBH,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,EAEnD,CAEA,SAASQ,GAAuB,CAC9BR,GAAM,MAAM,EACZ,IAAMS,EAAUX,EAAY,EAC5BE,EAAOS,EAAQ,MACfR,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYM,EACjBN,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACU,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9CT,GACAS,EAAM,SAAWf,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBe,EAAM,SAAWf,EAAK,WACjDN,EAAQqB,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAX,EAAO,iBAAiB,UAAWa,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BZ,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAY,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdV,EAAW,GACXL,EAAO,oBAAoB,UAAWa,CAAgC,EACtEV,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["isReady","data","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","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 *\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\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 * 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 /** 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\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 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 dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAuEA,SAASA,EAAQC,EAAwC,CACvD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B,EAAO,OACrBE,EAAc,CACrB,MAAWnB,EAAK,OAAS,eACvBY,EAAK,gBAAgBZ,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBY,EAAK,WAAWZ,EAAK,MAAM,EAClBA,EAAK,OAAS,mBAIlBmB,EAAc,EAAE,KAAMK,GAAO,CAC5BA,GAAIR,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,CACzD,CAAC,CAEL,CAEA,SAASS,GAAuB,CAC9BT,GAAM,MAAM,EACZ,IAAMU,EAAUZ,EAAY,EAC5BE,EAAOU,EAAQ,MACfT,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYM,EACjBN,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACW,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9CV,GACAU,EAAM,SAAWhB,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBgB,EAAM,SAAWhB,EAAK,WACjDb,EAAQ6B,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAZ,EAAO,iBAAiB,UAAWc,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3Bb,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAa,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdX,EAAW,GACXL,EAAO,oBAAoB,UAAWc,CAAgC,EACtEX,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path"]}
|
package/dist/embed-react.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var P=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var G=(e,t)=>{for(var o in t)P(e,o,{get:t[o],enumerable:!0})},J=(e,t,o,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of q(t))!Y.call(e,r)&&r!==o&&P(e,r,{get:()=>t[r],enumerable:!(c=j(t,r))||c.enumerable});return e};var K=e=>J(P({},"__esModule",{value:!0}),e);var re={};G(re,{CrmEmbed:()=>z,crmSession:()=>U,default:()=>ee});module.exports=K(re);var n=require("react");function Q(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function U(e,t){return async()=>{let o=await fetch(e,{method:"POST",...t}),c=await o.json().catch(()=>({}));if(!o.ok){let m=c?.error;throw new Error(m?`CRM session failed: ${m}`:`CRM session failed (HTTP ${o.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 $(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function W(e){let t=e.windowTarget??window,o=e.createChannel??(()=>new MessageChannel),c=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,m="",p=!1;async function C(){try{let s=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:s.accessToken,refreshToken:s.refreshToken??""}),!0}catch(s){return e.onError?.(s),!1}}function h(s){let d=s.data;if(d)if(d.type==="channel-ack"){if(d.nonce!==m)return;C()}else d.type==="route-change"?e.onRouteChange?.(d.path):d.type==="resize"?e.onResize?.(d.height):d.type==="session-expired"&&C().then(y=>{y&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let s=o();r=s.port1,m=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=h,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:m},c,[s.port2])}function f(s){p||s.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&s.origin!==e.crmOrigin||Q(s.data)&&E())}return t.addEventListener("message",f),{navigate(s){r?.postMessage({type:"navigate",path:s})},dispose(){p=!0,t.removeEventListener("message",f),r?.close(),r=null}}}var a=require("react/jsx-runtime");var V={width:"100%",height:"100%",border:0};function H(e){return e instanceof Error?e:new Error(String(e))}function X(){return(0,a.jsx)("div",{children:"Loading CRM\u2026"})}function Z(e,t){return(0,a.jsxs)("div",{children:[(0,a.jsxs)("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),(0,a.jsx)("button",{type:"button",onClick:t,children:"Try again"})]})}var z=(0,n.forwardRef)(function(t,o){let{getSession:c,crmEmbedOrigin:r,className:m,style:p,title:C="CRM",onReady:h,onError:E,onRouteChange:f,hostProvidesNav:s,initialPath:d,renderLoading:y,renderError:I}=t,x=(0,n.useRef)(null),[R,L]=(0,n.useState)(null),[k,O]=(0,n.useState)(null),[M,v]=(0,n.useState)(null),[D,F]=(0,n.useState)(0),b=(0,n.useRef)(null),S=(0,n.useRef)(null);(0,n.useImperativeHandle)(o,()=>({navigate:l=>{S.current?.navigate(l)}}),[]);let T=(0,n.useRef)(c),N=(0,n.useRef)(h),w=(0,n.useRef)(E),A=(0,n.useRef)(f);(0,n.useEffect)(()=>{T.current=c,N.current=h,w.current=E,A.current=f});let _=(0,n.useRef)(d),B=(0,n.useCallback)(()=>{b.current=null,v(null),L(null),O(null),F(l=>l+1)},[]);return(0,n.useEffect)(()=>{let l=!1;return(async()=>{try{let u=await T.current();if(l)return;b.current={accessToken:u.accessToken},O(u.workspaceId);let g=$(r,u.workspaceId)+(_.current??"")+(s?"?hostnav=1":"");L(g)}catch(u){if(l)return;let i=H(u);v(i),w.current?.(i)}})(),()=>{l=!0}},[r,s,D]),(0,n.useEffect)(()=>{let l=x.current;if(!l||!R||!k)return;let u=null;try{u=W({iframe:l,crmOrigin:r,getBearer:async()=>{let i=b.current;return i?(b.current=null,i):{accessToken:(await T.current()).accessToken}},onRouteChange:i=>{A.current?.(i)},onError:i=>{let g=H(i);v(g),w.current?.(g)}})}catch(i){let g=H(i);v(g),w.current?.(g);return}return S.current=u,N.current?.({workspaceId:k}),()=>{u?.dispose(),S.current=null}},[R,k,r]),M?(0,a.jsx)(a.Fragment,{children:I?I(M,B):Z(M,B)}):R?(0,a.jsx)("iframe",{ref:x,src:R,title:C,className:m,style:{...V,...p}}):(0,a.jsx)(a.Fragment,{children:y?y():X()})}),ee=z;0&&(module.exports={CrmEmbed,crmSession});
|
|
2
2
|
//# sourceMappingURL=embed-react.cjs.map
|
package/dist/embed-react.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n useCallback, useEffect, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n type CrmBearer,\n type CrmEmbedHost,\n} from './embed-host';\n\n/** What a partner's `getSession()` must resolve to. */\nexport interface CrmEmbedSession {\n /** Short-lived CRM bearer (access token) to hand to the iframe. */\n accessToken: string;\n /** The workspace to embed; used to build the iframe URL. */\n workspaceId: string;\n /** Optional TTL hint (seconds). Not required by the component today. */\n expiresIn?: number;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n */\nexport function CrmEmbed(props: CrmEmbedProps): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`;\n // depending on them directly would re-run Phase 1 (re-fetch the session) and\n // tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n });\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin — never on unrelated\n // parent re-renders (callbacks are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n setEmbedUrl(buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId));\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => { host?.dispose(); };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n}\n\nexport default CrmEmbed;\n","/**\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 *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the assertion exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\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 createEmbedSession() (see ./embed-server).\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 * 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 /** 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/**\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\n async function deliverBearer(): Promise<void> {\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 } catch (err) {\n opts.onError?.(err);\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).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\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 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,cAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAmBA,IAAAK,EAEO,iBCiDP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACp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,IAAMgC,EAAIjC,EAAQC,CAAG,EACrBqB,EAASW,CAAC,EACVL,EAAW,UAAUK,CAAC,EACtB,MACF,CAGA,OAAAN,EAAW,UAAU,CAAE,YAAAP,CAAY,CAAC,EAE7B,IAAM,CAAEe,GAAM,QAAQ,CAAG,CAClC,EAAG,CAACjB,EAAUE,EAAaX,CAAc,CAAC,EAEtCL,KACK,mBAAG,SAAAY,EAAcA,EAAYZ,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5Ea,KAKH,OAAC,UACC,IAAKD,EACL,IAAKC,EACL,MAAON,EACP,UAAWF,EACX,MAAO,CAAE,GAAGX,EAAsB,GAAGY,CAAM,EAC7C,KAVO,mBAAG,SAAAI,EAAgBA,EAAc,EAAIb,EAAe,EAAE,CAYjE,CAEA,IAAOoC,EAAQhC","names":["embed_react_exports","__export","CrmEmbed","embed_react_default","__toCommonJS","import_react","isReady","data","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","getSession","crmEmbedOrigin","className","style","title","onReady","onError","renderLoading","renderError","iframeRef","embedUrl","setEmbedUrl","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","getSessionRef","onReadyRef","onErrorRef","n","cancelled","session","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","embed_react_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport { crmSession, type CrmSessionResult };\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\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 *\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\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 * 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 /** 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\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 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 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,GAAA,GAAAC,EAAAD,GAAA,cAAAE,EAAA,eAAAC,EAAA,YAAAC,KAAA,eAAAC,EAAAL,IAwBA,IAAAM,EAEO,iBC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,IAAMG,EAASF,EAGf,GAAI,OAAOE,GAAQ,aAAgB,UAAY,OAAOA,GAAQ,aAAgB,SAC5E,MAAM,IAAI,MAAM,yDAAyD,EAE3E,OAAOA,CACT,CACF,CASO,SAASC,EAAiBC,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASC,EAAmBC,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBA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AAU,KACnBiB,GAGF,CAAE,aADO,MAAMd,EAAc,QAAQ,GACd,WAAY,CAC5C,EACA,cAAgBD,GAAS,CAAEI,EAAiB,UAAUJ,CAAI,CAAG,EAC7D,QAAU9B,GAAQ,CAChB,IAAMyC,EAAI1C,EAAQC,CAAG,EACrByB,EAASgB,CAAC,EACVR,EAAW,UAAUQ,CAAC,CACxB,CACF,CAAC,CACH,OAASzC,EAAK,CACZ,IAAMyC,EAAI1C,EAAQC,CAAG,EACrByB,EAASgB,CAAC,EACVR,EAAW,UAAUQ,CAAC,EACtB,MACF,CAEA,OAAAZ,EAAQ,QAAUc,EAGlBX,EAAW,UAAU,CAAE,YAAAT,CAAY,CAAC,EAE7B,IAAM,CACXoB,GAAM,QAAQ,EACdd,EAAQ,QAAU,IACpB,CACF,EAAG,CAACR,EAAUE,EAAad,CAAc,CAAC,EAEtCN,KACK,mBAAG,SAAAgB,EAAcA,EAAYhB,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5EiB,KAKH,OAAC,UACC,IAAKD,EACL,IAAKC,EACL,MAAOT,EACP,UAAWF,EACX,MAAO,CAAE,GAAGZ,EAAsB,GAAGa,CAAM,EAC7C,KAVO,mBAAG,SAAAO,EAAgBA,EAAc,EAAIjB,EAAe,EAAE,CAYjE,CACF,EAEO6C,GAAQzC","names":["embed_react_exports","__export","CrmEmbed","crmSession","embed_react_default","__toCommonJS","import_react","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","import_jsx_runtime","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","renderLoading","renderError","iframeRef","embedUrl","setEmbedUrl","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","initialPathRef","n","cancelled","session","url","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","embed_react_default"]}
|
package/dist/embed-react.d.cts
CHANGED
|
@@ -1,32 +1,37 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
1
2
|
import { CSSProperties, ReactNode } from 'react';
|
|
2
3
|
|
|
4
|
+
/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
|
|
5
|
+
interface CrmSessionResult {
|
|
6
|
+
accessToken: string;
|
|
7
|
+
workspaceId: string;
|
|
8
|
+
expiresIn?: number;
|
|
9
|
+
}
|
|
3
10
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* This wraps the low-level {@link ./embed-host | embed-host} helpers into a
|
|
8
|
-
* single component. You supply a `getSession()` that returns a CRM bearer plus
|
|
9
|
-
* the workspace to embed (typically by calling your own backend endpoint that
|
|
10
|
-
* runs `createEmbedSessionWithKey`), and the component handles:
|
|
11
|
-
* - resolving the session and building the iframe URL,
|
|
12
|
-
* - rendering the iframe and running the MessageChannel handshake,
|
|
13
|
-
* - reusing the initial bearer (no double-mint) and re-minting on expiry,
|
|
14
|
-
* - loading / error / retry states.
|
|
11
|
+
* Build a `getSession()` that POSTs to your own session endpoint and returns
|
|
12
|
+
* `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`
|
|
13
|
+
* on the server, so you don't hand-write the fetch/parse.
|
|
15
14
|
*
|
|
16
|
-
*
|
|
17
|
-
* React. Non-React consumers can keep using `./embed-host` directly.
|
|
15
|
+
* <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />
|
|
18
16
|
*
|
|
19
|
-
*
|
|
17
|
+
* On a non-2xx response it throws an Error carrying the server's `error` code.
|
|
18
|
+
* Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).
|
|
20
19
|
*/
|
|
20
|
+
declare function crmSession(url: string, init?: RequestInit): () => Promise<CrmSessionResult>;
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
22
|
+
/**
|
|
23
|
+
* What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}
|
|
24
|
+
* (the browser-side session shape) — kept as a named export for back-compat; both
|
|
25
|
+
* are `{ accessToken, workspaceId, expiresIn? }`.
|
|
26
|
+
*/
|
|
27
|
+
type CrmEmbedSession = CrmSessionResult;
|
|
28
|
+
/**
|
|
29
|
+
* Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's
|
|
30
|
+
* navigation without re-rendering the iframe.
|
|
31
|
+
*/
|
|
32
|
+
interface CrmEmbedHandle {
|
|
33
|
+
/** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
|
|
34
|
+
navigate: (path: string) => void;
|
|
30
35
|
}
|
|
31
36
|
interface CrmEmbedProps {
|
|
32
37
|
/**
|
|
@@ -53,6 +58,23 @@ interface CrmEmbedProps {
|
|
|
53
58
|
}) => void;
|
|
54
59
|
/** Called on any session / handshake error. */
|
|
55
60
|
onError?: (error: Error) => void;
|
|
61
|
+
/**
|
|
62
|
+
* Called when the CRM navigates internally (e.g. "/contacts"). Use this to
|
|
63
|
+
* keep a host-supplied nav in sync with the embedded CRM's current section.
|
|
64
|
+
*/
|
|
65
|
+
onRouteChange?: (path: string) => void;
|
|
66
|
+
/**
|
|
67
|
+
* When true, the CRM hides its own in-iframe nav (the host supplies it).
|
|
68
|
+
* Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive
|
|
69
|
+
* navigation yourself via the ref's `navigate()`.
|
|
70
|
+
*/
|
|
71
|
+
hostProvidesNav?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Initial CRM sub-path to deep-link on FIRST load (e.g. "/contacts").
|
|
74
|
+
* Only applied to the initial iframe URL — later changes do NOT reload the
|
|
75
|
+
* iframe; use the ref's `navigate()` for in-session navigation.
|
|
76
|
+
*/
|
|
77
|
+
initialPath?: string;
|
|
56
78
|
/** Custom loading UI. Defaults to a minimal message. */
|
|
57
79
|
renderLoading?: () => ReactNode;
|
|
58
80
|
/** Custom error UI. Defaults to the message + a Retry button. */
|
|
@@ -60,7 +82,10 @@ interface CrmEmbedProps {
|
|
|
60
82
|
}
|
|
61
83
|
/**
|
|
62
84
|
* Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.
|
|
85
|
+
*
|
|
86
|
+
* Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a
|
|
87
|
+
* host can drive the embedded CRM's section navigation.
|
|
63
88
|
*/
|
|
64
|
-
declare
|
|
89
|
+
declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
|
|
65
90
|
|
|
66
|
-
export { CrmEmbed, type CrmEmbedProps, type CrmEmbedSession, CrmEmbed as default };
|
|
91
|
+
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmSessionResult, crmSession, CrmEmbed as default };
|
package/dist/embed-react.d.ts
CHANGED
|
@@ -1,32 +1,37 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
1
2
|
import { CSSProperties, ReactNode } from 'react';
|
|
2
3
|
|
|
4
|
+
/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */
|
|
5
|
+
interface CrmSessionResult {
|
|
6
|
+
accessToken: string;
|
|
7
|
+
workspaceId: string;
|
|
8
|
+
expiresIn?: number;
|
|
9
|
+
}
|
|
3
10
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* This wraps the low-level {@link ./embed-host | embed-host} helpers into a
|
|
8
|
-
* single component. You supply a `getSession()` that returns a CRM bearer plus
|
|
9
|
-
* the workspace to embed (typically by calling your own backend endpoint that
|
|
10
|
-
* runs `createEmbedSessionWithKey`), and the component handles:
|
|
11
|
-
* - resolving the session and building the iframe URL,
|
|
12
|
-
* - rendering the iframe and running the MessageChannel handshake,
|
|
13
|
-
* - reusing the initial bearer (no double-mint) and re-minting on expiry,
|
|
14
|
-
* - loading / error / retry states.
|
|
11
|
+
* Build a `getSession()` that POSTs to your own session endpoint and returns
|
|
12
|
+
* `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`
|
|
13
|
+
* on the server, so you don't hand-write the fetch/parse.
|
|
15
14
|
*
|
|
16
|
-
*
|
|
17
|
-
* React. Non-React consumers can keep using `./embed-host` directly.
|
|
15
|
+
* <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />
|
|
18
16
|
*
|
|
19
|
-
*
|
|
17
|
+
* On a non-2xx response it throws an Error carrying the server's `error` code.
|
|
18
|
+
* Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).
|
|
20
19
|
*/
|
|
20
|
+
declare function crmSession(url: string, init?: RequestInit): () => Promise<CrmSessionResult>;
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
22
|
+
/**
|
|
23
|
+
* What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}
|
|
24
|
+
* (the browser-side session shape) — kept as a named export for back-compat; both
|
|
25
|
+
* are `{ accessToken, workspaceId, expiresIn? }`.
|
|
26
|
+
*/
|
|
27
|
+
type CrmEmbedSession = CrmSessionResult;
|
|
28
|
+
/**
|
|
29
|
+
* Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's
|
|
30
|
+
* navigation without re-rendering the iframe.
|
|
31
|
+
*/
|
|
32
|
+
interface CrmEmbedHandle {
|
|
33
|
+
/** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
|
|
34
|
+
navigate: (path: string) => void;
|
|
30
35
|
}
|
|
31
36
|
interface CrmEmbedProps {
|
|
32
37
|
/**
|
|
@@ -53,6 +58,23 @@ interface CrmEmbedProps {
|
|
|
53
58
|
}) => void;
|
|
54
59
|
/** Called on any session / handshake error. */
|
|
55
60
|
onError?: (error: Error) => void;
|
|
61
|
+
/**
|
|
62
|
+
* Called when the CRM navigates internally (e.g. "/contacts"). Use this to
|
|
63
|
+
* keep a host-supplied nav in sync with the embedded CRM's current section.
|
|
64
|
+
*/
|
|
65
|
+
onRouteChange?: (path: string) => void;
|
|
66
|
+
/**
|
|
67
|
+
* When true, the CRM hides its own in-iframe nav (the host supplies it).
|
|
68
|
+
* Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive
|
|
69
|
+
* navigation yourself via the ref's `navigate()`.
|
|
70
|
+
*/
|
|
71
|
+
hostProvidesNav?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Initial CRM sub-path to deep-link on FIRST load (e.g. "/contacts").
|
|
74
|
+
* Only applied to the initial iframe URL — later changes do NOT reload the
|
|
75
|
+
* iframe; use the ref's `navigate()` for in-session navigation.
|
|
76
|
+
*/
|
|
77
|
+
initialPath?: string;
|
|
56
78
|
/** Custom loading UI. Defaults to a minimal message. */
|
|
57
79
|
renderLoading?: () => ReactNode;
|
|
58
80
|
/** Custom error UI. Defaults to the message + a Retry button. */
|
|
@@ -60,7 +82,10 @@ interface CrmEmbedProps {
|
|
|
60
82
|
}
|
|
61
83
|
/**
|
|
62
84
|
* Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.
|
|
85
|
+
*
|
|
86
|
+
* Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a
|
|
87
|
+
* host can drive the embedded CRM's section navigation.
|
|
63
88
|
*/
|
|
64
|
-
declare
|
|
89
|
+
declare const CrmEmbed: react.ForwardRefExoticComponent<CrmEmbedProps & react.RefAttributes<CrmEmbedHandle>>;
|
|
65
90
|
|
|
66
|
-
export { CrmEmbed, type CrmEmbedProps, type CrmEmbedSession, CrmEmbed as default };
|
|
91
|
+
export { CrmEmbed, type CrmEmbedHandle, type CrmEmbedProps, type CrmEmbedSession, type CrmSessionResult, crmSession, CrmEmbed as default };
|
package/dist/embed-react.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useCallback as
|
|
1
|
+
import{forwardRef as G,useCallback as J,useEffect as H,useImperativeHandle as K,useRef as l,useState as k}from"react";function q(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function Y(e,s){return async()=>{let u=await fetch(e,{method:"POST",...s}),m=await u.json().catch(()=>({}));if(!u.ok){let c=m?.error;throw new Error(c?`CRM session failed: ${c}`:`CRM session failed (HTTP ${u.status})`)}let r=m;if(typeof r?.accessToken!="string"||typeof r?.workspaceId!="string")throw new Error("CRM session response is missing accessToken/workspaceId");return r}}function $(e,s){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(s)}`}function W(e){let s=e.windowTarget??window,u=e.createChannel??(()=>new MessageChannel),m=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,c="",p=!1;async function C(){try{let n=await e.getBearer();return r?.postMessage({type:"auth-tokens",accessToken:n.accessToken,refreshToken:n.refreshToken??""}),!0}catch(n){return e.onError?.(n),!1}}function h(n){let o=n.data;if(o)if(o.type==="channel-ack"){if(o.nonce!==c)return;C()}else o.type==="route-change"?e.onRouteChange?.(o.path):o.type==="resize"?e.onResize?.(o.height):o.type==="session-expired"&&C().then(y=>{y&&r?.postMessage({type:"session-refreshed"})})}function E(){r?.close();let n=u();r=n.port1,c=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=h,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:c},m,[n.port2])}function g(n){p||n.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&n.origin!==e.crmOrigin||q(n.data)&&E())}return s.addEventListener("message",g),{navigate(n){r?.postMessage({type:"navigate",path:n})},dispose(){p=!0,s.removeEventListener("message",g),r?.close(),r=null}}}import{Fragment as D,jsx as f,jsxs as z}from"react/jsx-runtime";var Q={width:"100%",height:"100%",border:0};function I(e){return e instanceof Error?e:new Error(String(e))}function V(){return f("div",{children:"Loading CRM\u2026"})}function X(e,s){return z("div",{children:[z("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),f("button",{type:"button",onClick:s,children:"Try again"})]})}var Z=G(function(s,u){let{getSession:m,crmEmbedOrigin:r,className:c,style:p,title:C="CRM",onReady:h,onError:E,onRouteChange:g,hostProvidesNav:n,initialPath:o,renderLoading:y,renderError:x}=s,L=l(null),[R,O]=k(null),[M,N]=k(null),[S,v]=k(null),[F,_]=k(0),b=l(null),T=l(null);K(u,()=>({navigate:i=>{T.current?.navigate(i)}}),[]);let P=l(m),A=l(h),w=l(E),B=l(g);H(()=>{P.current=m,A.current=h,w.current=E,B.current=g});let j=l(o),U=J(()=>{b.current=null,v(null),O(null),N(null),_(i=>i+1)},[]);return H(()=>{let i=!1;return(async()=>{try{let a=await P.current();if(i)return;b.current={accessToken:a.accessToken},N(a.workspaceId);let d=$(r,a.workspaceId)+(j.current??"")+(n?"?hostnav=1":"");O(d)}catch(a){if(i)return;let t=I(a);v(t),w.current?.(t)}})(),()=>{i=!0}},[r,n,F]),H(()=>{let i=L.current;if(!i||!R||!M)return;let a=null;try{a=W({iframe:i,crmOrigin:r,getBearer:async()=>{let t=b.current;return t?(b.current=null,t):{accessToken:(await P.current()).accessToken}},onRouteChange:t=>{B.current?.(t)},onError:t=>{let d=I(t);v(d),w.current?.(d)}})}catch(t){let d=I(t);v(d),w.current?.(d);return}return T.current=a,A.current?.({workspaceId:M}),()=>{a?.dispose(),T.current=null}},[R,M,r]),S?f(D,{children:x?x(S,U):X(S,U)}):R?f("iframe",{ref:L,src:R,title:C,className:c,style:{...Q,...p}}):f(D,{children:y?y():V()})}),te=Z;export{Z as CrmEmbed,Y as crmSession,te as default};
|
|
2
2
|
//# sourceMappingURL=embed-react.js.map
|
package/dist/embed-react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n useCallback, useEffect, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n type CrmBearer,\n type CrmEmbedHost,\n} from './embed-host';\n\n/** What a partner's `getSession()` must resolve to. */\nexport interface CrmEmbedSession {\n /** Short-lived CRM bearer (access token) to hand to the iframe. */\n accessToken: string;\n /** The workspace to embed; used to build the iframe URL. */\n workspaceId: string;\n /** Optional TTL hint (seconds). Not required by the component today. */\n expiresIn?: number;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n */\nexport function CrmEmbed(props: CrmEmbedProps): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`;\n // depending on them directly would re-run Phase 1 (re-fetch the session) and\n // tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n });\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin — never on unrelated\n // parent re-renders (callbacks are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n setEmbedUrl(buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId));\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => { host?.dispose(); };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n}\n\nexport default CrmEmbed;\n","/**\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 *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the assertion exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\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 createEmbedSession() (see ./embed-server).\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 * 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 /** 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/**\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\n async function deliverBearer(): Promise<void> {\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 } catch (err) {\n opts.onError?.(err);\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).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\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 dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAmBA,OACE,eAAAA,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAC3B,QCiDP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CASO,SAASC,EAAiBC,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASC,EAAmBC,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAA+B,CAC5C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpCI,GAAM,YA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tB,EAAC,UACC,IAAKoB,EACL,IAAKE,EACL,MAAOP,EACP,UAAWF,EACX,MAAO,CAAE,GAAGX,EAAsB,GAAGY,CAAM,EAC7C,EAVOd,EAAAD,EAAA,CAAG,SAAAmB,EAAgBA,EAAc,EAAIb,EAAe,EAAE,CAYjE,CAEA,IAAOwC,EAAQpC","names":["useCallback","useEffect","useRef","useState","isReady","data","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","DefaultError","error","retry","CrmEmbed","props","getSession","crmEmbedOrigin","className","style","title","onReady","onError","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","getSessionRef","onReadyRef","onErrorRef","useEffect","useCallback","n","cancelled","session","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","embed_react_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport { crmSession, type CrmSessionResult };\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\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 *\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\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 * 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 /** 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\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 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 dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAwBA,OACE,cAA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K,CACZ,IAAMiD,EAAIlD,EAAQC,CAAG,EACrB8B,EAASmB,CAAC,EACVV,EAAW,UAAUU,CAAC,EACtB,MACF,CAEA,OAAAf,EAAQ,QAAUiB,EAGlBb,EAAW,UAAU,CAAE,YAAAV,CAAY,CAAC,EAE7B,IAAM,CACXuB,GAAM,QAAQ,EACdjB,EAAQ,QAAU,IACpB,CACF,EAAG,CAACT,EAAUG,EAAahB,CAAc,CAAC,EAEtCR,EACKF,EAAAoD,EAAA,CAAG,SAAAhC,EAAcA,EAAYlB,EAAOC,CAAK,EAAIF,EAAaC,EAAOC,CAAK,EAAE,EAG5EoB,EAKHvB,EAAC,UACC,IAAKqB,EACL,IAAKE,EACL,MAAOV,EACP,UAAWF,EACX,MAAO,CAAE,GAAGf,EAAsB,GAAGgB,CAAM,EAC7C,EAVOZ,EAAAoD,EAAA,CAAG,SAAAjC,EAAgBA,EAAc,EAAIpB,EAAe,EAAE,CAYjE,CACF,EAEOsD,GAAQhD","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useRef","useState","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","jsx","DefaultError","error","retry","jsxs","CrmEmbed","forwardRef","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","useEffect","initialPathRef","useCallback","n","cancelled","session","url","buildCrmEmbedUrl","e","iframe","host","createCrmEmbedHost","primed","Fragment","embed_react_default"]}
|
package/dist/embed-server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var f=(e,r)=>{for(var s in r)c(e,s,{get:r[s],enumerable:!0})},h=(e,r,s,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of l(r))!g.call(e,n)&&n!==s&&c(e,n,{get:()=>r[n],enumerable:!(t=m(r,n))||t.enumerable});return e};var S=e=>h(c({},"__esModule",{value:!0}),e);var R={};f(R,{CrmExchangeError:()=>i,createCrmSessionHandler:()=>y,createEmbedSessionWithKey:()=>p});module.exports=S(R);var i=class extends Error{constructor(s,t,n,o){super(s);this.status=t;this.code=n;this.detail=o;this.name="CrmExchangeError"}},b=e=>e.replace(/\/$/,"");function E(e){let r=e.access_token,s=e.workspace?.id;if(typeof r!="string"||r.length===0)throw new i("CRM response missing access_token",502,"MALFORMED_RESPONSE",e);if(typeof s!="string"||s.length===0)throw new i("CRM response missing workspace id",502,"MALFORMED_RESPONSE",e);return{accessToken:r,expiresIn:e.expires_in,workspaceId:s,user:e.user,role:e.role}}async function p(e,r){let s=r.fetch??fetch,t=`${b(r.crmBaseUrl)}/api/auth/exchange`,n=await s(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),o=await n.json().catch(()=>({}));if(!n.ok){let u=o?.error?.code??`HTTP_${n.status}`,d=o?.error?.message??"CRM exchange failed";throw new i(d,n.status,u,o)}return E(o?.data??{})}var a=(e,r)=>new Response(JSON.stringify(e),{status:r,headers:{"content-type":"application/json"}});function y(e){return async r=>{let s;try{s=await e.authenticate(r)}catch(t){let n=typeof t?.status=="number"?t.status:401,o=t?.code??"UNAUTHORIZED";return a({error:o},n)}if(!s)return a({error:"UNAUTHORIZED"},401);try{let t=await p({appId:e.appId,appSecret:e.appSecret,user:s},{crmBaseUrl:e.crmBaseUrl,fetch:e.fetch});return a(t,200)}catch(t){return t instanceof i?a({error:t.code},t.status):(console.error("[crm-sdk] createCrmSessionHandler: session exchange failed",t),a({error:"CRM_SESSION_FAILED"},502))}}}0&&(module.exports={CrmExchangeError,createCrmSessionHandler,createEmbedSessionWithKey});
|
|
2
2
|
//# sourceMappingURL=embed-server.cjs.map
|