@first-to-fly/crm-sdk 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.js ADDED
@@ -0,0 +1,2 @@
1
+ var g=class r extends Error{constructor(c,a,o,i,n){super(o),this.name="CrmApiError",this.status=c,this.code=a,this.body=i,n&&"cause"in n&&(this.cause=n.cause),Object.setPrototypeOf(this,r.prototype)}};function w(r){if(!r)return"";let c=new URLSearchParams;for(let[o,i]of Object.entries(r))if(i!=null)if(Array.isArray(i))for(let n of i)n!=null&&c.append(o,String(n));else c.append(o,String(i));let a=c.toString();return a?`?${a}`:""}function v(r){return typeof r=="object"&&r!==null&&"success"in r}function R(r,c){let a=v(r)&&r.success===!1?r:void 0,o=a?.error,i=typeof a?.message=="string"?a.message:void 0,n=o&&typeof o=="object"?o:void 0,f=typeof n?.code=="string"?n.code:void 0,C=typeof n?.message=="string"?n.message:void 0,t=typeof o=="string"?o:void 0,e=f??t??`HTTP_${c}`,s=C??i??t??`CRM request failed with status ${c}`;return{code:e,message:s}}function Q(r){let{crmBaseUrl:c,accessToken:a,apiKey:o}=r;if(!a&&!o)throw new Error("createCrmApiClient: exactly one of `accessToken` or `apiKey` is required (got neither).");if(a&&o)throw new Error("createCrmApiClient: provide only one of `accessToken` or `apiKey` (got both).");let i=r.fetch??globalThis.fetch;if(typeof i!="function")throw new Error("createCrmApiClient: no fetch implementation available. Pass `fetch` explicitly.");let n=c.replace(/\/+$/,""),f=n.endsWith("/api")?n:`${n}/api`,C=a?{Authorization:`Bearer ${a}`}:{"X-API-Key":o};async function t(e,s,p={}){let b=`${f}${s}${w(p.query)}`,k={...C},h=p.body!==void 0;h&&(k["Content-Type"]="application/json");let y=p.timeoutMs??r.timeoutMs,T=y!==void 0?new AbortController:void 0,L=!1,P;T&&y!==void 0&&(P=setTimeout(()=>{L=!0,T.abort()},y));let m;try{m=await i(b,{method:e,headers:k,body:h?JSON.stringify(p.body):void 0,signal:T?.signal})}catch(u){if(L||u instanceof Error&&u.name==="AbortError")throw new g(0,"TIMEOUT",`CRM request timed out after ${y}ms`,u,{cause:u});let E=u instanceof Error?u.message:"CRM request failed (network error)";throw new g(0,"NETWORK_ERROR",E,u,{cause:u})}finally{P!==void 0&&clearTimeout(P)}let l=await m.text(),d=l;if(l)try{d=JSON.parse(l)}catch{d=l}let U=v(d)&&d.success===!1;if(!m.ok||U){let{code:u,message:E}=R(d,m.status);throw new g(m.status,u,E,d)}if(v(d)&&d.success===!0)return d.data;if(l!=="")return d}return{contacts:{list:e=>t("GET","/contacts",{query:e}),get:e=>t("GET",`/contacts/${encodeURIComponent(e)}`),create:e=>t("POST","/contacts",{body:e}),update:(e,s)=>t("PUT",`/contacts/${encodeURIComponent(e)}`,{body:s}),delete:e=>t("DELETE",`/contacts/${encodeURIComponent(e)}`)},leads:{list:e=>t("GET","/leads",{query:e}),get:e=>t("GET",`/leads/${encodeURIComponent(e)}`),create:e=>t("POST","/leads",{body:e}),update:(e,s)=>t("PUT",`/leads/${encodeURIComponent(e)}`,{body:s}),delete:e=>t("DELETE",`/leads/${encodeURIComponent(e)}`)},tasks:{list:e=>t("GET","/tasks",{query:e}),create:(e,s)=>t("POST",`/leads/${encodeURIComponent(e)}/tasks`,{body:s}),update:(e,s,p)=>t("PATCH",`/leads/${encodeURIComponent(e)}/tasks/${encodeURIComponent(s)}`,{body:p})},products:{list:e=>t("GET","/products",{query:e}),get:e=>t("GET",`/products/${encodeURIComponent(e)}`),create:e=>t("POST","/products",{body:e}),update:(e,s)=>t("PUT",`/products/${encodeURIComponent(e)}`,{body:s}),delete:e=>t("DELETE",`/products/${encodeURIComponent(e)}`)},conversations:{list:e=>t("GET","/conversations",{query:e}),get:e=>t("GET",`/conversations/${encodeURIComponent(e)}`),update:(e,s)=>t("PUT",`/conversations/${encodeURIComponent(e)}`,{body:s}),messages:{list:(e,s)=>t("GET",`/conversations/${encodeURIComponent(e)}/messages`,{query:s}),send:(e,s)=>t("POST",`/conversations/${encodeURIComponent(e)}/messages`,{body:s})}},tags:{list:e=>t("GET","/tags",{query:e}),create:e=>t("POST","/tags",{body:e})},request:t}}var $=Q;export{g as CrmApiError,Q as createCrmApiClient,$ as default};
2
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/api.ts"],"sourcesContent":["/**\n * Typed CRM REST API client for SaaS backends.\n *\n * Construct with `createCrmApiClient({ crmBaseUrl, accessToken | apiKey })` and\n * call typed resource methods (contacts, leads, conversations, messages, tasks,\n * products, tags) or the generic `request<T>()` escape hatch. Every method\n * returns the UNWRAPPED `data` from the CRM's `{ success, data }` envelope.\n *\n * Auth:\n * - `accessToken` (from `createEmbedSessionWithKey().data.access_token`) is\n * sent as `Authorization: Bearer <token>` and covers the full API surface.\n * The typed resource methods below hit `/api/*` routes that require this\n * **Bearer** token.\n * - `apiKey` (`crm_live_...`) is sent as `X-API-Key` and today only guards\n * `/api/public/*`. An `apiKey` client should use the generic `request()`\n * against those `/public/*` endpoints, NOT the typed resource methods.\n *\n * Error handling — every failure is thrown as a {@link CrmApiError} so callers\n * can `catch (e) { if (e instanceof CrmApiError) ... }`:\n * - non-2xx responses, AND 2xx responses the server mislabels with an\n * `{ success: false }` envelope, throw with the HTTP `status` and a code\n * derived from the body.\n * - network / DNS / connection failures throw with `status: 0` and\n * `code: 'NETWORK_ERROR'`.\n * - a request that exceeds `timeoutMs` (via `AbortController`) throws with\n * `status: 0` and `code: 'TIMEOUT'`.\n *\n * Timeouts — pass `timeoutMs` on the client (default for all requests) and/or\n * per request. If unset there is no timeout.\n *\n * @packageDocumentation\n */\n\nimport type {\n Contact,\n ContactCreate,\n ContactUpdate,\n ContactQuery,\n ContactList,\n Lead,\n LeadCreate,\n LeadUpdate,\n LeadQuery,\n Task,\n TaskCreate,\n TaskUpdate,\n TaskQuery,\n Conversation,\n ConversationQuery,\n ConversationUpdate,\n Message,\n MessageQuery,\n MessageCreate,\n Product,\n ProductCreate,\n ProductUpdate,\n ProductQuery,\n Tag,\n TagCreate,\n TagQuery,\n TagWithUsage,\n ListEnvelope,\n} from './generated/crm-contracts';\n\nexport type * from './generated/crm-contracts';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype FetchLike = typeof fetch;\n\n/** Options for {@link createCrmApiClient}. Exactly one of accessToken / apiKey. */\nexport interface CrmApiClientOptions {\n /** Base URL of the CRM, e.g. `https://crm.example.com` (no trailing `/api`). */\n crmBaseUrl: string;\n /** Bearer token from `createEmbedSessionWithKey` — full API surface. */\n accessToken?: string;\n /** Server-to-server API key (`crm_live_...`) — `/api/public/*` only today. */\n apiKey?: string;\n /** Custom fetch implementation (e.g. for Node < 18 or testing). */\n fetch?: FetchLike;\n /**\n * Default per-request timeout in milliseconds, enforced via `AbortController`.\n * On timeout the request throws a {@link CrmApiError} (`status: 0`,\n * `code: 'TIMEOUT'`). If unset (default), requests have no timeout.\n */\n timeoutMs?: number;\n}\n\n/** CRM success envelope. */\ninterface SuccessEnvelope<T> {\n success: true;\n data: T;\n message?: string;\n meta?: Record<string, unknown>;\n}\n\n/** CRM error envelope. */\ninterface ErrorEnvelope {\n success: false;\n error: string;\n message?: string;\n details?: string;\n}\n\ntype QueryPrimitive = string | number | boolean;\ntype QueryValue =\n | QueryPrimitive\n | Array<QueryPrimitive>\n | undefined\n | null;\ntype QueryParams = Record<string, QueryValue>;\n\ninterface RequestOptions {\n query?: QueryParams;\n body?: unknown;\n /**\n * Per-request timeout in milliseconds (overrides the client `timeoutMs`).\n * On timeout the request throws a {@link CrmApiError} (`status: 0`,\n * `code: 'TIMEOUT'`).\n */\n timeoutMs?: number;\n}\n\n/**\n * Error thrown for any failed CRM request:\n * - a non-2xx HTTP response,\n * - a 2xx response carrying an `{ success: false }` envelope (server mislabel),\n * - a network/DNS/connection failure (`status: 0`, `code: 'NETWORK_ERROR'`),\n * - a timeout / abort (`status: 0`, `code: 'TIMEOUT'`).\n */\nexport class CrmApiError extends Error {\n /** HTTP status code (0 for network errors / timeouts). */\n readonly status: number;\n /**\n * Machine-readable code. For envelope errors: the object `error.code`, else\n * the string `error`, else `HTTP_<status>`. For transport failures:\n * `NETWORK_ERROR` or `TIMEOUT`.\n */\n readonly code: string;\n /** Parsed response body, or the underlying error for transport failures. */\n readonly body: unknown;\n\n constructor(\n status: number,\n code: string,\n message: string,\n body: unknown,\n options?: { cause?: unknown },\n ) {\n super(message);\n this.name = 'CrmApiError';\n this.status = status;\n this.code = code;\n this.body = body;\n // Preserve the underlying error (network/abort) without requiring the\n // ES2022 `cause` constructor option.\n if (options && 'cause' in options) {\n (this as { cause?: unknown }).cause = options.cause;\n }\n Object.setPrototypeOf(this, CrmApiError.prototype);\n }\n}\n\n/** The client returned by {@link createCrmApiClient}. */\nexport interface CrmApiClient {\n contacts: {\n list(query?: ContactQuery): Promise<ContactList>;\n get(id: string): Promise<Contact>;\n create(body: ContactCreate): Promise<Contact>;\n update(id: string, body: ContactUpdate): Promise<Contact>;\n delete(id: string): Promise<void>;\n };\n leads: {\n list(query?: LeadQuery): Promise<ListEnvelope<Lead>>;\n get(id: string): Promise<Lead>;\n create(body: LeadCreate): Promise<Lead>;\n update(id: string, body: LeadUpdate): Promise<Lead>;\n delete(id: string): Promise<void>;\n };\n tasks: {\n list(query?: TaskQuery): Promise<ListEnvelope<Task>>;\n create(leadId: string, body: TaskCreate): Promise<Task>;\n update(leadId: string, taskId: string, body: TaskUpdate): Promise<Task>;\n };\n products: {\n list(query?: ProductQuery): Promise<ListEnvelope<Product>>;\n get(id: string): Promise<Product>;\n create(body: ProductCreate): Promise<Product>;\n update(id: string, body: ProductUpdate): Promise<Product>;\n delete(id: string): Promise<void>;\n };\n conversations: {\n list(query?: ConversationQuery): Promise<ListEnvelope<Conversation>>;\n get(id: string): Promise<Conversation>;\n update(id: string, body: ConversationUpdate): Promise<Conversation>;\n messages: {\n list(\n conversationId: string,\n query?: MessageQuery,\n ): Promise<ListEnvelope<Message>>;\n send(conversationId: string, body: MessageCreate): Promise<Message>;\n };\n };\n tags: {\n list(query?: TagQuery): Promise<ListEnvelope<TagWithUsage>>;\n create(body: TagCreate): Promise<Tag>;\n };\n /** Generic escape hatch — returns the unwrapped `data` typed as `T`. */\n request<T>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize query params. Array values are appended as repeated params\n * (`?tag=a&tag=b`); `undefined`/`null` values (and array elements) are skipped.\n *\n * NOTE on the CRM's `tags` filter: the CRM's contacts/leads query schemas expect\n * `tags` as a single comma-separated string (`?tags=a,b`), which the server\n * splits on `,`. If you pass `tags` as an array here it becomes repeated params\n * (`?tags=a&tags=b`), which those endpoints will NOT parse as multiple tags —\n * pass a comma-joined string for that specific field. All other core query\n * fields are primitives. No core query field is a nested object.\n */\nfunction serializeQuery(query?: QueryParams): string {\n if (!query) return '';\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const el of value) {\n if (el === undefined || el === null) continue;\n params.append(key, String(el));\n }\n } else {\n params.append(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : '';\n}\n\nfunction isEnvelope(v: unknown): v is SuccessEnvelope<unknown> | ErrorEnvelope {\n return typeof v === 'object' && v !== null && 'success' in v;\n}\n\n/** Derive `{ code, message }` from a parsed CRM error envelope + HTTP status. */\nfunction deriveError(parsed: unknown, status: number): { code: string; message: string } {\n const envelope =\n isEnvelope(parsed) && parsed.success === false\n ? (parsed as ErrorEnvelope & { error?: unknown })\n : undefined;\n const rawError: unknown = envelope?.error;\n const envMessage =\n typeof envelope?.message === 'string' ? envelope.message : undefined;\n\n // error can be a string (\"human string\" or a code) OR an object { code, message }.\n const errorObj =\n rawError && typeof rawError === 'object'\n ? (rawError as { code?: unknown; message?: unknown })\n : undefined;\n const errorObjCode =\n typeof errorObj?.code === 'string' ? errorObj.code : undefined;\n const errorObjMessage =\n typeof errorObj?.message === 'string' ? errorObj.message : undefined;\n const errorStr = typeof rawError === 'string' ? rawError : undefined;\n\n const code = errorObjCode ?? errorStr ?? `HTTP_${status}`;\n const message =\n errorObjMessage ??\n envMessage ??\n errorStr ??\n `CRM request failed with status ${status}`;\n\n return { code, message };\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport function createCrmApiClient(opts: CrmApiClientOptions): CrmApiClient {\n const { crmBaseUrl, accessToken, apiKey } = opts;\n\n if (!accessToken && !apiKey) {\n throw new Error(\n 'createCrmApiClient: exactly one of `accessToken` or `apiKey` is required (got neither).',\n );\n }\n if (accessToken && apiKey) {\n throw new Error(\n 'createCrmApiClient: provide only one of `accessToken` or `apiKey` (got both).',\n );\n }\n\n const fetchImpl: FetchLike = opts.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== 'function') {\n throw new Error(\n 'createCrmApiClient: no fetch implementation available. Pass `fetch` explicitly.',\n );\n }\n\n // Normalize base: strip trailing slash, then ensure it ends with `/api`.\n const trimmed = crmBaseUrl.replace(/\\/+$/, '');\n const apiBase = trimmed.endsWith('/api') ? trimmed : `${trimmed}/api`;\n\n const authHeaders: Record<string, string> = accessToken\n ? { Authorization: `Bearer ${accessToken}` }\n : { 'X-API-Key': apiKey as string };\n\n async function request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n const url = `${apiBase}${path}${serializeQuery(options.query)}`;\n const headers: Record<string, string> = { ...authHeaders };\n const hasBody = options.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n\n const timeoutMs = options.timeoutMs ?? opts.timeoutMs;\n const controller =\n timeoutMs !== undefined ? new AbortController() : undefined;\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (controller && timeoutMs !== undefined) {\n timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n }\n\n let res: Response;\n try {\n res = await fetchImpl(url, {\n method,\n headers,\n body: hasBody ? JSON.stringify(options.body) : undefined,\n signal: controller?.signal,\n });\n } catch (err) {\n // Network error, DNS failure, connection refused, or abort/timeout.\n if (\n timedOut ||\n (err instanceof Error && err.name === 'AbortError')\n ) {\n throw new CrmApiError(\n 0,\n 'TIMEOUT',\n `CRM request timed out after ${timeoutMs}ms`,\n err,\n { cause: err },\n );\n }\n const message =\n err instanceof Error ? err.message : 'CRM request failed (network error)';\n throw new CrmApiError(0, 'NETWORK_ERROR', message, err, { cause: err });\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n\n // Parse body (JSON when possible, else raw text).\n const text = await res.text();\n let parsed: unknown = text;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = text;\n }\n }\n\n // Treat an `{ success: false }` envelope as an error regardless of HTTP\n // status — a server can mislabel an error as 2xx.\n const isEnvelopeError = isEnvelope(parsed) && parsed.success === false;\n if (!res.ok || isEnvelopeError) {\n const { code, message } = deriveError(parsed, res.status);\n throw new CrmApiError(res.status, code, message, parsed);\n }\n\n // Unwrap `{ success, data }`.\n if (isEnvelope(parsed) && parsed.success === true) {\n return parsed.data as T;\n }\n\n // Empty 2xx body (e.g. 204 / empty DELETE) → undefined, not \"\".\n if (text === '') {\n return undefined as T;\n }\n\n // Non-enveloped 2xx response — return the raw parsed body.\n return parsed as T;\n }\n\n return {\n contacts: {\n list: (query) => request<ContactList>('GET', '/contacts', { query: query as QueryParams }),\n get: (id) => request<Contact>('GET', `/contacts/${encodeURIComponent(id)}`),\n create: (body) => request<Contact>('POST', '/contacts', { body }),\n update: (id, body) => request<Contact>('PUT', `/contacts/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/contacts/${encodeURIComponent(id)}`),\n },\n leads: {\n list: (query) => request<ListEnvelope<Lead>>('GET', '/leads', { query: query as QueryParams }),\n get: (id) => request<Lead>('GET', `/leads/${encodeURIComponent(id)}`),\n create: (body) => request<Lead>('POST', '/leads', { body }),\n update: (id, body) => request<Lead>('PUT', `/leads/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/leads/${encodeURIComponent(id)}`),\n },\n tasks: {\n list: (query) => request<ListEnvelope<Task>>('GET', '/tasks', { query: query as QueryParams }),\n create: (leadId, body) =>\n request<Task>('POST', `/leads/${encodeURIComponent(leadId)}/tasks`, { body }),\n update: (leadId, taskId, body) =>\n request<Task>(\n 'PATCH',\n `/leads/${encodeURIComponent(leadId)}/tasks/${encodeURIComponent(taskId)}`,\n { body },\n ),\n },\n products: {\n list: (query) => request<ListEnvelope<Product>>('GET', '/products', { query: query as QueryParams }),\n get: (id) => request<Product>('GET', `/products/${encodeURIComponent(id)}`),\n create: (body) => request<Product>('POST', '/products', { body }),\n update: (id, body) => request<Product>('PUT', `/products/${encodeURIComponent(id)}`, { body }),\n delete: (id) => request<void>('DELETE', `/products/${encodeURIComponent(id)}`),\n },\n conversations: {\n list: (query) =>\n request<ListEnvelope<Conversation>>('GET', '/conversations', { query: query as QueryParams }),\n get: (id) => request<Conversation>('GET', `/conversations/${encodeURIComponent(id)}`),\n update: (id, body) =>\n request<Conversation>('PUT', `/conversations/${encodeURIComponent(id)}`, { body }),\n messages: {\n list: (conversationId, query) =>\n request<ListEnvelope<Message>>(\n 'GET',\n `/conversations/${encodeURIComponent(conversationId)}/messages`,\n { query: query as QueryParams },\n ),\n send: (conversationId, body) =>\n request<Message>(\n 'POST',\n `/conversations/${encodeURIComponent(conversationId)}/messages`,\n { body },\n ),\n },\n },\n tags: {\n list: (query) => request<ListEnvelope<TagWithUsage>>('GET', '/tags', { query: query as QueryParams }),\n create: (body) => request<Tag>('POST', '/tags', { body }),\n },\n request,\n };\n}\n\nexport default createCrmApiClient;\n"],"mappings":"AAoIO,IAAMA,EAAN,MAAMC,UAAoB,KAAM,CAYrC,YACEC,EACAC,EACAC,EACAC,EACAC,EACA,CACA,MAAMF,CAAO,EACb,KAAK,KAAO,cACZ,KAAK,O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,IACrB0B,EACE,MACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,MAAO3C,CAAqB,CAChC,EACF,KAAM,CAAC2C,EAAgB9C,IACrB6B,EACE,OACA,kBAAkB,mBAAmBiB,CAAc,CAAC,YACpD,CAAE,KAAA9C,CAAK,CACT,CACJ,CACF,EACA,KAAM,CACJ,KAAOG,GAAU0B,EAAoC,MAAO,QAAS,CAAE,MAAO1B,CAAqB,CAAC,EACpG,OAASH,GAAS6B,EAAa,OAAQ,QAAS,CAAE,KAAA7B,CAAK,CAAC,CAC1D,EACA,QAAA6B,CACF,CACF,CAEA,IAAOkB,EAAQ3B","names":["CrmApiError","_CrmApiError","status","code","message","body","options","serializeQuery","query","params","key","value","el","qs","isEnvelope","v","deriveError","parsed","envelope","rawError","envMessage","errorObj","errorObjCode","errorObjMessage","errorStr","createCrmApiClient","opts","crmBaseUrl","accessToken","apiKey","fetchImpl","trimmed","apiBase","authHeaders","request","method","path","url","headers","hasBody","timeoutMs","controller","timedOut","timer","res","err","text","isEnvelopeError","id","leadId","taskId","conversationId","api_default"]}
@@ -0,0 +1,2 @@
1
+ "use strict";var M=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var W=(e,n)=>{for(var i in n)M(e,i,{get:n[i],enumerable:!0})},z=(e,n,i,u)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of N(n))!U.call(e,t)&&t!==i&&M(e,t,{get:()=>n[t],enumerable:!(u=B(n,t))||u.enumerable});return e};var D=e=>z(M({},"__esModule",{value:!0}),e);var q={};W(q,{CrmEmbed:()=>H,default:()=>j});module.exports=D(q);var o=require("react");function F(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function O(e,n){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(n)}`}function x(e){let n=e.windowTarget??window,i=e.createChannel??(()=>new MessageChannel),u=e.devAllowAnyOrigin?"*":e.crmOrigin,t=null,g="",f=!1;async function p(){try{let r=await e.getBearer();t?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""})}catch(r){e.onError?.(r)}}function y(r){let a=r.data;if(a)if(a.type==="channel-ack"){if(a.nonce!==g)return;p()}else a.type==="route-change"?e.onRouteChange?.(a.path):a.type==="resize"?e.onResize?.(a.height):a.type==="session-expired"&&(p(),t?.postMessage({type:"session-refreshed"}))}function C(){t?.close();let r=i();t=r.port1,g=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,t.onmessage=y,t.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:g},u,[r.port2])}function E(r){f||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||F(r.data)&&C())}return n.addEventListener("message",E),{navigate(r){t?.postMessage({type:"navigate",path:r})},dispose(){f=!0,n.removeEventListener("message",E),t?.close(),t=null}}}var s=require("react/jsx-runtime"),$={width:"100%",height:"100%",border:0};function T(e){return e instanceof Error?e:new Error(String(e))}function _(){return(0,s.jsx)("div",{children:"Loading CRM\u2026"})}function Y(e,n){return(0,s.jsxs)("div",{children:[(0,s.jsxs)("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),(0,s.jsx)("button",{type:"button",onClick:n,children:"Try again"})]})}function H(e){let{getSession:n,crmEmbedOrigin:i,className:u,style:t,title:g="CRM",onReady:f,onError:p,renderLoading:y,renderError:C}=e,E=(0,o.useRef)(null),[r,a]=(0,o.useState)(null),[R,S]=(0,o.useState)(null),[k,h]=(0,o.useState)(null),[P,A]=(0,o.useState)(0),v=(0,o.useRef)(null),w=(0,o.useRef)(n),L=(0,o.useRef)(f),b=(0,o.useRef)(p);(0,o.useEffect)(()=>{w.current=n,L.current=f,b.current=p});let I=(0,o.useCallback)(()=>{v.current=null,h(null),a(null),S(null),A(d=>d+1)},[]);return(0,o.useEffect)(()=>{let d=!1;return(async()=>{try{let l=await w.current();if(d)return;v.current={accessToken:l.accessToken},S(l.workspaceId),a(O(i,l.workspaceId))}catch(l){if(d)return;let c=T(l);h(c),b.current?.(c)}})(),()=>{d=!0}},[i,P]),(0,o.useEffect)(()=>{let d=E.current;if(!d||!r||!R)return;let l=null;try{l=x({iframe:d,crmOrigin:i,getBearer:async()=>{let c=v.current;return c?(v.current=null,c):{accessToken:(await w.current()).accessToken}},onError:c=>{let m=T(c);h(m),b.current?.(m)}})}catch(c){let m=T(c);h(m),b.current?.(m);return}return L.current?.({workspaceId:R}),()=>{l?.dispose()}},[r,R,i]),k?(0,s.jsx)(s.Fragment,{children:C?C(k,I):Y(k,I)}):r?(0,s.jsx)("iframe",{ref:E,src:r,title:g,className:u,style:{...$,...t}}):(0,s.jsx)(s.Fragment,{children:y?y():_()})}var j=H;0&&(module.exports={CrmEmbed});
2
+ //# sourceMappingURL=embed-react.cjs.map
@@ -0,0 +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,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ACA,QAAUzB,GAAQ,CAChB,IAAMgC,EAAIjC,EAAQC,CAAG,EACrBqB,EAASW,CAAC,EACVL,EAAW,UAAUK,CAAC,CACxB,CACF,CAAC,CACH,OAAShC,EAAK,CACZ,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"]}
@@ -0,0 +1,66 @@
1
+ import { CSSProperties, ReactNode } from 'react';
2
+
3
+ /**
4
+ * Drop-in React component that embeds the First To Fly CRM as a cross-origin
5
+ * iframe, authenticated WITHOUT cookies.
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.
15
+ *
16
+ * `react` is an OPTIONAL peer dependency — only pull in this entry if you use
17
+ * React. Non-React consumers can keep using `./embed-host` directly.
18
+ *
19
+ * @packageDocumentation
20
+ */
21
+
22
+ /** What a partner's `getSession()` must resolve to. */
23
+ interface CrmEmbedSession {
24
+ /** Short-lived CRM bearer (access token) to hand to the iframe. */
25
+ accessToken: string;
26
+ /** The workspace to embed; used to build the iframe URL. */
27
+ workspaceId: string;
28
+ /** Optional TTL hint (seconds). Not required by the component today. */
29
+ expiresIn?: number;
30
+ }
31
+ interface CrmEmbedProps {
32
+ /**
33
+ * Resolves a CRM bearer + the workspace to embed. Called once on mount (and
34
+ * again on retry / session expiry). Typically calls your own backend endpoint
35
+ * that runs `createEmbedSessionWithKey`.
36
+ */
37
+ getSession: () => Promise<CrmEmbedSession>;
38
+ /**
39
+ * The CRM embed base origin, e.g. "https://crm.example.com". The iframe URL
40
+ * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also
41
+ * used as the postMessage targetOrigin.
42
+ */
43
+ crmEmbedOrigin: string;
44
+ /** Class applied to the iframe. */
45
+ className?: string;
46
+ /** Inline style merged onto the iframe (overrides the fill-container default). */
47
+ style?: CSSProperties;
48
+ /** Iframe title (accessibility). Defaults to "CRM". */
49
+ title?: string;
50
+ /** Called after the iframe URL is built and mounted. */
51
+ onReady?: (info: {
52
+ workspaceId: string;
53
+ }) => void;
54
+ /** Called on any session / handshake error. */
55
+ onError?: (error: Error) => void;
56
+ /** Custom loading UI. Defaults to a minimal message. */
57
+ renderLoading?: () => ReactNode;
58
+ /** Custom error UI. Defaults to the message + a Retry button. */
59
+ renderError?: (error: Error, retry: () => void) => ReactNode;
60
+ }
61
+ /**
62
+ * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.
63
+ */
64
+ declare function CrmEmbed(props: CrmEmbedProps): ReactNode;
65
+
66
+ export { CrmEmbed, type CrmEmbedProps, type CrmEmbedSession, CrmEmbed as default };
@@ -0,0 +1,66 @@
1
+ import { CSSProperties, ReactNode } from 'react';
2
+
3
+ /**
4
+ * Drop-in React component that embeds the First To Fly CRM as a cross-origin
5
+ * iframe, authenticated WITHOUT cookies.
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.
15
+ *
16
+ * `react` is an OPTIONAL peer dependency — only pull in this entry if you use
17
+ * React. Non-React consumers can keep using `./embed-host` directly.
18
+ *
19
+ * @packageDocumentation
20
+ */
21
+
22
+ /** What a partner's `getSession()` must resolve to. */
23
+ interface CrmEmbedSession {
24
+ /** Short-lived CRM bearer (access token) to hand to the iframe. */
25
+ accessToken: string;
26
+ /** The workspace to embed; used to build the iframe URL. */
27
+ workspaceId: string;
28
+ /** Optional TTL hint (seconds). Not required by the component today. */
29
+ expiresIn?: number;
30
+ }
31
+ interface CrmEmbedProps {
32
+ /**
33
+ * Resolves a CRM bearer + the workspace to embed. Called once on mount (and
34
+ * again on retry / session expiry). Typically calls your own backend endpoint
35
+ * that runs `createEmbedSessionWithKey`.
36
+ */
37
+ getSession: () => Promise<CrmEmbedSession>;
38
+ /**
39
+ * The CRM embed base origin, e.g. "https://crm.example.com". The iframe URL
40
+ * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also
41
+ * used as the postMessage targetOrigin.
42
+ */
43
+ crmEmbedOrigin: string;
44
+ /** Class applied to the iframe. */
45
+ className?: string;
46
+ /** Inline style merged onto the iframe (overrides the fill-container default). */
47
+ style?: CSSProperties;
48
+ /** Iframe title (accessibility). Defaults to "CRM". */
49
+ title?: string;
50
+ /** Called after the iframe URL is built and mounted. */
51
+ onReady?: (info: {
52
+ workspaceId: string;
53
+ }) => void;
54
+ /** Called on any session / handshake error. */
55
+ onError?: (error: Error) => void;
56
+ /** Custom loading UI. Defaults to a minimal message. */
57
+ renderLoading?: () => ReactNode;
58
+ /** Custom error UI. Defaults to the message + a Retry button. */
59
+ renderError?: (error: Error, retry: () => void) => ReactNode;
60
+ }
61
+ /**
62
+ * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.
63
+ */
64
+ declare function CrmEmbed(props: CrmEmbedProps): ReactNode;
65
+
66
+ export { CrmEmbed, type CrmEmbedProps, type CrmEmbedSession, CrmEmbed as default };
@@ -0,0 +1,2 @@
1
+ import{useCallback as W,useEffect as T,useRef as f,useState as b}from"react";function U(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function x(e,o){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(o)}`}function H(e){let o=e.windowTarget??window,c=e.createChannel??(()=>new MessageChannel),R=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,l="",u=!1;async function m(){try{let r=await e.getBearer();n?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""})}catch(r){e.onError?.(r)}}function E(r){let t=r.data;if(t)if(t.type==="channel-ack"){if(t.nonce!==l)return;m()}else t.type==="route-change"?e.onRouteChange?.(t.path):t.type==="resize"?e.onResize?.(t.height):t.type==="session-expired"&&(m(),n?.postMessage({type:"session-refreshed"}))}function y(){n?.close();let r=c();n=r.port1,l=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=E,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:l},R,[r.port2])}function g(r){u||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||U(r.data)&&y())}return o.addEventListener("message",g),{navigate(r){n?.postMessage({type:"navigate",path:r})},dispose(){u=!0,o.removeEventListener("message",g),n?.close(),n=null}}}import{Fragment as A,jsx as p,jsxs as P}from"react/jsx-runtime";var z={width:"100%",height:"100%",border:0};function S(e){return e instanceof Error?e:new Error(String(e))}function D(){return p("div",{children:"Loading CRM\u2026"})}function F(e,o){return P("div",{children:[P("p",{children:["Couldn\u2019t load the CRM: ",e.message]}),p("button",{type:"button",onClick:o,children:"Try again"})]})}function $(e){let{getSession:o,crmEmbedOrigin:c,className:R,style:n,title:l="CRM",onReady:u,onError:m,renderLoading:E,renderError:y}=e,g=f(null),[r,t]=b(null),[k,L]=b(null),[w,C]=b(null),[B,N]=b(0),h=f(null),M=f(o),I=f(u),v=f(m);T(()=>{M.current=o,I.current=u,v.current=m});let O=W(()=>{h.current=null,C(null),t(null),L(null),N(i=>i+1)},[]);return T(()=>{let i=!1;return(async()=>{try{let a=await M.current();if(i)return;h.current={accessToken:a.accessToken},L(a.workspaceId),t(x(c,a.workspaceId))}catch(a){if(i)return;let s=S(a);C(s),v.current?.(s)}})(),()=>{i=!0}},[c,B]),T(()=>{let i=g.current;if(!i||!r||!k)return;let a=null;try{a=H({iframe:i,crmOrigin:c,getBearer:async()=>{let s=h.current;return s?(h.current=null,s):{accessToken:(await M.current()).accessToken}},onError:s=>{let d=S(s);C(d),v.current?.(d)}})}catch(s){let d=S(s);C(d),v.current?.(d);return}return I.current?.({workspaceId:k}),()=>{a?.dispose()}},[r,k,c]),w?p(A,{children:y?y(w,O):F(w,O)}):r?p("iframe",{ref:g,src:r,title:l,className:R,style:{...z,...n}}):p(A,{children:E?E():D()})}var q=$;export{$ as CrmEmbed,q as default};
2
+ //# sourceMappingURL=embed-react.js.map
@@ -0,0 +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,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KHtB,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@first-to-fly/crm-sdk",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion or API-key auth)",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -29,6 +29,16 @@
29
29
  "default": "./dist/embed-host.cjs"
30
30
  }
31
31
  },
32
+ "./embed-react": {
33
+ "import": {
34
+ "types": "./dist/embed-react.d.ts",
35
+ "default": "./dist/embed-react.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/embed-react.d.cts",
39
+ "default": "./dist/embed-react.cjs"
40
+ }
41
+ },
32
42
  "./embed-server": {
33
43
  "import": {
34
44
  "types": "./dist/embed-server.d.ts",
@@ -38,6 +48,16 @@
38
48
  "types": "./dist/embed-server.d.cts",
39
49
  "default": "./dist/embed-server.cjs"
40
50
  }
51
+ },
52
+ "./api": {
53
+ "import": {
54
+ "types": "./dist/api.d.ts",
55
+ "default": "./dist/api.js"
56
+ },
57
+ "require": {
58
+ "types": "./dist/api.d.cts",
59
+ "default": "./dist/api.cjs"
60
+ }
41
61
  }
42
62
  },
43
63
  "files": [
@@ -65,17 +85,26 @@
65
85
  "author": "First to Fly",
66
86
  "license": "MIT",
67
87
  "peerDependencies": {
68
- "jose": ">=5"
88
+ "jose": ">=5",
89
+ "react": ">=17"
69
90
  },
70
91
  "peerDependenciesMeta": {
71
92
  "jose": {
72
93
  "optional": true
94
+ },
95
+ "react": {
96
+ "optional": true
73
97
  }
74
98
  },
75
99
  "devDependencies": {
76
100
  "jose": "^5.9.6",
101
+ "@testing-library/react": "^16.1.0",
77
102
  "@types/jsdom": "^28.0.0",
103
+ "@types/react": "^18.3.12",
104
+ "@types/react-dom": "^18.3.1",
78
105
  "jsdom": "^28.1.0",
106
+ "react": "^18.3.1",
107
+ "react-dom": "^18.3.1",
79
108
  "tsup": "^8.5.1",
80
109
  "typescript": "^5.9.3",
81
110
  "vitest": "^4.0.18"