@first-to-fly/crm-sdk 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 First to Fly
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # @first-to-fly/crm-sdk
2
+
3
+ CRM Embeddable App SDK — enables communication between third-party iframes and the CRM host.
4
+
5
+ ## Installation
6
+
7
+ ### npm / bun
8
+
9
+ ```bash
10
+ npm install @first-to-fly/crm-sdk
11
+ # or
12
+ bun add @first-to-fly/crm-sdk
13
+ ```
14
+
15
+ ### Script tag
16
+
17
+ ```html
18
+ <script src="https://your-crm-domain.com/sdk/v1/app.js"></script>
19
+ ```
20
+
21
+ When loaded via script tag, `window.CrmApp` is available globally.
22
+
23
+ ## Quick Start
24
+
25
+ ### ESM / TypeScript
26
+
27
+ ```typescript
28
+ import { CrmApp } from '@first-to-fly/crm-sdk';
29
+
30
+ CrmApp.on('ready', (context) => {
31
+ console.log('Connected!', context.workspace_id);
32
+ console.log('Conversation:', context.conversation_id);
33
+ console.log('Contact:', context.contact_id);
34
+ });
35
+
36
+ CrmApp.on('context_update', (context) => {
37
+ console.log('Context changed:', context);
38
+ });
39
+
40
+ // Signal readiness to the CRM host
41
+ CrmApp.init();
42
+ ```
43
+
44
+ ### Script tag
45
+
46
+ ```html
47
+ <script src="https://your-crm-domain.com/sdk/v1/app.js"></script>
48
+ <script>
49
+ CrmApp.on('ready', function (context) {
50
+ document.getElementById('info').textContent =
51
+ 'Workspace: ' + context.workspace_id;
52
+ });
53
+
54
+ CrmApp.init();
55
+ </script>
56
+ ```
57
+
58
+ ## API Reference
59
+
60
+ ### `CrmApp.init()`
61
+
62
+ Signals to the CRM host that your app is ready to receive context. Must be called once after setting up event listeners.
63
+
64
+ ### `CrmApp.on(event, listener)`
65
+
66
+ Register an event listener.
67
+
68
+ | Event | Description |
69
+ |-------|-------------|
70
+ | `'ready'` | Fired once after `init()` when the host sends the initial context |
71
+ | `'context_update'` | Fired when the user switches conversations or the context changes |
72
+
73
+ The listener receives a `CrmContext` object:
74
+
75
+ ```typescript
76
+ interface CrmContext {
77
+ token: string | null; // Short-lived JWT for authenticated API calls
78
+ workspace_id: string; // Current workspace ID
79
+ conversation_id: string | null; // Current conversation (if in conversation sidebar)
80
+ contact_id: string | null; // Current contact (if available)
81
+ }
82
+ ```
83
+
84
+ ### `CrmApp.off(event, listener)`
85
+
86
+ Remove a previously registered event listener.
87
+
88
+ ### `CrmApp.getContext()`
89
+
90
+ Returns the current `CrmContext` synchronously, or `null` if `init()` hasn't completed yet.
91
+
92
+ ### `CrmApp.invoke(action, data?)`
93
+
94
+ Request an action from the CRM host. Returns a `Promise` that resolves with the result or rejects on error/timeout (30s).
95
+
96
+ ```typescript
97
+ // Example: request iframe resize
98
+ const result = await CrmApp.invoke('resize', { height: 500 });
99
+ ```
100
+
101
+ ## PostMessage Protocol
102
+
103
+ For advanced use cases, the SDK communicates with the CRM host via `window.postMessage`.
104
+
105
+ ### iframe → Host
106
+
107
+ Messages include `{ source: 'crm-app', type, ... }`:
108
+
109
+ | Type | Description |
110
+ |------|-------------|
111
+ | `app_ready` | Sent by `init()` to signal the app is ready |
112
+ | `invoke` | Sent by `invoke()` with `invoke_id`, `action`, `data` |
113
+
114
+ ### Host → iframe
115
+
116
+ Messages include `{ source: 'crm-host', type, ... }`:
117
+
118
+ | Type | Description |
119
+ |------|-------------|
120
+ | `init` | Sent after `app_ready`, contains `context` |
121
+ | `context_update` | Sent when context changes, contains updated `context` |
122
+ | `response` | Response to an `invoke`, contains `invoke_id` and `result` or `error` |
123
+
124
+ ## License
125
+
126
+ MIT
@@ -0,0 +1,34 @@
1
+ /**
2
+ * CRM Embeddable App SDK
3
+ * Enables communication between third-party iframes and the CRM host.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ /** Context provided by the CRM host after initialization */
8
+ interface CrmContext {
9
+ token: string | null;
10
+ workspace_id: string;
11
+ conversation_id: string | null;
12
+ contact_id: string | null;
13
+ conversation_metadata?: Record<string, unknown>;
14
+ }
15
+ /** Supported SDK event types */
16
+ type CrmEventType = 'ready' | 'context_update';
17
+ /** Event listener callback */
18
+ type CrmEventListener = (data: CrmContext) => void;
19
+ /** Public SDK interface */
20
+ interface CrmAppSDK {
21
+ /** Signal readiness to the CRM host and start the handshake */
22
+ init(): void;
23
+ /** Register an event listener */
24
+ on(event: CrmEventType, fn: CrmEventListener): void;
25
+ /** Remove an event listener */
26
+ off(event: CrmEventType, fn: CrmEventListener): void;
27
+ /** Get the current context (null before initialization) */
28
+ getContext(): CrmContext | null;
29
+ /** Request an action from the CRM host. Returns a Promise that resolves with the result. */
30
+ invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;
31
+ }
32
+ declare const CrmApp: CrmAppSDK;
33
+
34
+ export { CrmApp, type CrmAppSDK, type CrmContext, type CrmEventListener, type CrmEventType, CrmApp as default };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * CRM Embeddable App SDK
3
+ * Enables communication between third-party iframes and the CRM host.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ /** Context provided by the CRM host after initialization */
8
+ interface CrmContext {
9
+ token: string | null;
10
+ workspace_id: string;
11
+ conversation_id: string | null;
12
+ contact_id: string | null;
13
+ conversation_metadata?: Record<string, unknown>;
14
+ }
15
+ /** Supported SDK event types */
16
+ type CrmEventType = 'ready' | 'context_update';
17
+ /** Event listener callback */
18
+ type CrmEventListener = (data: CrmContext) => void;
19
+ /** Public SDK interface */
20
+ interface CrmAppSDK {
21
+ /** Signal readiness to the CRM host and start the handshake */
22
+ init(): void;
23
+ /** Register an event listener */
24
+ on(event: CrmEventType, fn: CrmEventListener): void;
25
+ /** Remove an event listener */
26
+ off(event: CrmEventType, fn: CrmEventListener): void;
27
+ /** Get the current context (null before initialization) */
28
+ getContext(): CrmContext | null;
29
+ /** Request an action from the CRM host. Returns a Promise that resolves with the result. */
30
+ invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;
31
+ }
32
+ declare const CrmApp: CrmAppSDK;
33
+
34
+ export { CrmApp, type CrmAppSDK, type CrmContext, type CrmEventListener, type CrmEventType, CrmApp as default };
@@ -0,0 +1,3 @@
1
+ "use strict";var CrmAppSDK=(()=>{var a=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var m=(n,e)=>{for(var t in e)a(n,t,{get:e[t],enumerable:!0})},C=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of l(e))!f.call(n,r)&&r!==t&&a(n,r,{get:()=>e[r],enumerable:!(d=v(e,r))||d.enumerable});return n};var w=n=>C(a({},"__esModule",{value:!0}),n);var y={};m(y,{CrmApp:()=>p,default:()=>g});var i=null,s={},o={},k=0;function c(n,e){let t=s[n]||[];for(let d of t)try{d(e)}catch(r){console.error("[CrmApp] Listener error:",r)}}function u(n){typeof window<"u"&&window.parent&&window.parent!==window&&window.parent.postMessage({source:"crm-app",...n},"*")}function x(n){let{data:e}=n;if(!(!e||e.source!=="crm-host"))switch(e.type){case"init":i=e.context??null,i&&c("ready",i);break;case"context_update":i=e.context??null,i&&c("context_update",i);break;case"response":{let t=e.invoke_id;t!=null&&o[t]&&(e.error?o[t].reject(new Error(e.error)):o[t].resolve(e.result),delete o[t]);break}}}typeof window<"u"&&window.addEventListener("message",x,!1);var p={init(){u({type:"app_ready"})},on(n,e){s[n]||(s[n]=[]),s[n].push(e)},off(n,e){s[n]&&(s[n]=s[n].filter(t=>t!==e))},getContext(){return i},invoke(n,e){let t=++k;return u({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((d,r)=>{o[t]={resolve:d,reject:r},setTimeout(()=>{o[t]&&(o[t].reject(new Error("Invoke timeout")),delete o[t])},3e4)})}},g=p;return w(y);})();
2
+ if(typeof window!=="undefined"&&CrmAppSDK&&CrmAppSDK.CrmApp){window.CrmApp=CrmAppSDK.CrmApp;}
3
+ //# sourceMappingURL=index.global.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n window.parent.postMessage({ source: 'crm-app', ...msg }, '*');\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"6bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,YAAAC,IAwCA,IAAIC,EAA6B,KAC3BC,EAAgD,CAAC,EACjDC,EAGF,CAAC,EACDC,EAAgB,EAMpB,SAASC,EAAKC,EAAeC,EAAwB,CACnD,IAAMC,EAAMN,EAAUI,CAAK,GAAK,CAAC,EACjC,QAAWG,KAAMD,EACf,GAAI,CACFC,EAAGF,CAAI,CACT,OAASG,EAAG,CACV,QAAQ,MAAM,2BAA4BA,CAAC,CAC7C,CAEJ,CAEA,SAASC,EAAWC,EAAoC,CAEpD,OAAO,OAAW,KAClB,OAAO,QACP,OAAO,SAAW,QAElB,OAAO,OAAO,YAAY,CAAE,OAAQ,UAAW,GAAGA,CAAI,EAAG,GAAG,CAEhE,CAEA,SAASC,EAAcP,EAA2B,CAChD,GAAM,CAAE,KAAAC,CAAK,EAAID,EACjB,GAAI,GAACC,GAAQA,EAAK,SAAW,YAE7B,OAAQA,EAAK,KAAM,CACjB,IAAK,OACHN,EAAUM,EAAK,SAAW,KACtBN,GAASI,EAAK,QAASJ,CAAO,EAClC,MAEF,IAAK,iBACHA,EAAUM,EAAK,SAAW,KACtBN,GAASI,EAAK,iBAAkBJ,CAAO,EAC3C,MAEF,IAAK,WAAY,CACf,IAAMa,EAAyBP,EAAK,UAChCO,GAAM,MAAQX,EAAeW,CAAE,IAC7BP,EAAK,MACPJ,EAAeW,CAAE,EAAE,OAAO,IAAI,MAAMP,EAAK,KAAK,CAAC,EAE/CJ,EAAeW,CAAE,EAAE,QAAQP,EAAK,MAAM,EAExC,OAAOJ,EAAeW,CAAE,GAE1B,KACF,CACF,CACF,CAGI,OAAO,OAAW,KACpB,OAAO,iBAAiB,UAAWD,EAAe,EAAK,EAOlD,IAAMd,EAAoB,CAC/B,MAAa,CACXY,EAAW,CAAE,KAAM,WAAY,CAAC,CAClC,EAEA,GAAGL,EAAqBG,EAA4B,CAC7CP,EAAUI,CAAK,IAAGJ,EAAUI,CAAK,EAAI,CAAC,GAC3CJ,EAAUI,CAAK,EAAE,KAAKG,CAAE,CAC1B,EAEA,IAAIH,EAAqBG,EAA4B,CAC9CP,EAAUI,CAAK,IACpBJ,EAAUI,CAAK,EAAIJ,EAAUI,CAAK,EAAE,OAAQS,GAAMA,IAAMN,CAAE,EAC5D,EAEA,YAAgC,CAC9B,OAAOR,CACT,EAEA,OACEe,EACAT,EACY,CACZ,IAAMO,EAAK,EAAEV,EACb,OAAAO,EAAW,CACT,KAAM,SACN,UAAWG,EACX,OAAAE,EACA,KAAMT,GAAQ,CAAC,CACjB,CAAC,EAEM,IAAI,QAAW,CAACU,EAASC,IAAW,CACzCf,EAAeW,CAAE,EAAI,CACnB,QAASG,EACT,OAAAC,CACF,EACA,WAAW,IAAM,CACXf,EAAeW,CAAE,IACnBX,EAAeW,CAAE,EAAE,OAAO,IAAI,MAAM,gBAAgB,CAAC,EACrD,OAAOX,EAAeW,CAAE,EAE5B,EAAG,GAAK,CACV,CAAC,CACH,CACF,EAGOd,EAAQD","names":["index_exports","__export","CrmApp","index_default","context","listeners","pendingInvokes","invokeCounter","emit","event","data","fns","fn","e","postToHost","msg","handleMessage","id","f","action","resolve","reject"]}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var a=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var m=(n,e)=>{for(var t in e)a(n,t,{get:e[t],enumerable:!0})},C=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of l(e))!f.call(n,r)&&r!==t&&a(n,r,{get:()=>e[r],enumerable:!(d=v(e,r))||d.enumerable});return n};var w=n=>C(a({},"__esModule",{value:!0}),n);var y={};m(y,{CrmApp:()=>p,default:()=>g});module.exports=w(y);var i=null,s={},o={},k=0;function c(n,e){let t=s[n]||[];for(let d of t)try{d(e)}catch(r){console.error("[CrmApp] Listener error:",r)}}function u(n){typeof window<"u"&&window.parent&&window.parent!==window&&window.parent.postMessage({source:"crm-app",...n},"*")}function x(n){let{data:e}=n;if(!(!e||e.source!=="crm-host"))switch(e.type){case"init":i=e.context??null,i&&c("ready",i);break;case"context_update":i=e.context??null,i&&c("context_update",i);break;case"response":{let t=e.invoke_id;t!=null&&o[t]&&(e.error?o[t].reject(new Error(e.error)):o[t].resolve(e.result),delete o[t]);break}}}typeof window<"u"&&window.addEventListener("message",x,!1);var p={init(){u({type:"app_ready"})},on(n,e){s[n]||(s[n]=[]),s[n].push(e)},off(n,e){s[n]&&(s[n]=s[n].filter(t=>t!==e))},getContext(){return i},invoke(n,e){let t=++k;return u({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((d,r)=>{o[t]={resolve:d,reject:r},setTimeout(()=>{o[t]&&(o[t].reject(new Error("Invoke timeout")),delete o[t])},3e4)})}},g=p;0&&(module.exports={CrmApp});
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n window.parent.postMessage({ source: 'crm-app', ...msg }, '*');\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAwCA,IAAIK,EAA6B,KAC3BC,EAAgD,CAAC,EACjDC,EAGF,CAAC,EACDC,EAAgB,EAMpB,SAASC,EAAKC,EAAeC,EAAwB,CACnD,IAAMC,EAAMN,EAAUI,CAAK,GAAK,CAAC,EACjC,QAAWG,KAAMD,EACf,GAAI,CACFC,EAAGF,CAAI,CACT,OAASG,EAAG,CACV,QAAQ,MAAM,2BAA4BA,CAAC,CAC7C,CAEJ,CAEA,SAASC,EAAWC,EAAoC,CAEpD,OAAO,OAAW,KAClB,OAAO,QACP,OAAO,SAAW,QAElB,OAAO,OAAO,YAAY,CAAE,OAAQ,UAAW,GAAGA,CAAI,EAAG,GAAG,CAEhE,CAEA,SAASC,EAAcP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AAeW,CAAE,EAAE,OAAO,IAAI,MAAM,gBAAgB,CAAC,EACrD,OAAOX,EAAeW,CAAE,EAE5B,EAAG,GAAK,CACV,CAAC,CACH,CACF,EAGOf,EAAQD","names":["index_exports","__export","CrmApp","index_default","__toCommonJS","context","listeners","pendingInvokes","invokeCounter","emit","event","data","fns","fn","e","postToHost","msg","handleMessage","id","f","action","resolve","reject"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ var o=null,i={},r={},u=0;function a(n,e){let t=i[n]||[];for(let s of t)try{s(e)}catch(d){console.error("[CrmApp] Listener error:",d)}}function c(n){typeof window<"u"&&window.parent&&window.parent!==window&&window.parent.postMessage({source:"crm-app",...n},"*")}function p(n){let{data:e}=n;if(!(!e||e.source!=="crm-host"))switch(e.type){case"init":o=e.context??null,o&&a("ready",o);break;case"context_update":o=e.context??null,o&&a("context_update",o);break;case"response":{let t=e.invoke_id;t!=null&&r[t]&&(e.error?r[t].reject(new Error(e.error)):r[t].resolve(e.result),delete r[t]);break}}}typeof window<"u"&&window.addEventListener("message",p,!1);var v={init(){c({type:"app_ready"})},on(n,e){i[n]||(i[n]=[]),i[n].push(e)},off(n,e){i[n]&&(i[n]=i[n].filter(t=>t!==e))},getContext(){return o},invoke(n,e){let t=++u;return c({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((s,d)=>{r[t]={resolve:s,reject:d},setTimeout(()=>{r[t]&&(r[t].reject(new Error("Invoke timeout")),delete r[t])},3e4)})}},l=v;export{v as CrmApp,l as default};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n window.parent.postMessage({ source: 'crm-app', ...msg }, '*');\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"AAwCA,IAAIA,EAA6B,KAC3BC,EAAgD,CAAC,EACjDC,EAGF,CAAC,EACDC,EAAgB,EAMpB,SAASC,EAAKC,EAAeC,EAAwB,CACnD,IAAMC,EAAMN,EAAUI,CAAK,GAAK,CAAC,EACjC,QAAWG,KAAMD,EACf,GAAI,CACFC,EAAGF,CAAI,CACT,OAASG,EAAG,CACV,QAAQ,MAAM,2BAA4BA,CAAC,CAC7C,CAEJ,CAEA,SAASC,EAAWC,EAAoC,CAEpD,OAAO,OAAW,KAClB,OAAO,QACP,OAAO,SAAW,QAElB,OAAO,OAAO,YAAY,CAAE,OAAQ,UAAW,GAAGA,CAAI,EAAG,GAAG,CAEhE,CAEA,SAASC,EAAcP,EAA2B,CAChD,GAAM,CAAE,KAAAC,CAAK,EAAID,EACjB,GAAI,GAACC,GAAQA,EAAK,SAAW,YAE7B,OAAQA,EAAK,KAAM,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CACH,CACF,EAGOM,EAAQL","names":["context","listeners","pendingInvokes","invokeCounter","emit","event","data","fns","fn","e","postToHost","msg","handleMessage","id","CrmApp","f","action","resolve","reject","index_default"]}
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@first-to-fly/crm-sdk",
3
+ "version": "1.0.1",
4
+ "description": "CRM Embeddable App SDK — enables communication between third-party iframes and the CRM host",
5
+ "main": "dist/index.cjs",
6
+ "module": "dist/index.js",
7
+ "browser": "dist/index.global.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ },
20
+ "./umd": "./dist/index.global.js"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsup",
29
+ "typecheck": "tsc --noEmit",
30
+ "test": "vitest run",
31
+ "test:watch": "vitest",
32
+ "prepublishOnly": "bun run build"
33
+ },
34
+ "keywords": [
35
+ "crm",
36
+ "sdk",
37
+ "iframe",
38
+ "embeddable",
39
+ "postmessage"
40
+ ],
41
+ "author": "First to Fly",
42
+ "license": "MIT",
43
+ "devDependencies": {
44
+ "@types/jsdom": "^28.0.0",
45
+ "jsdom": "^28.1.0",
46
+ "tsup": "^8.5.1",
47
+ "typescript": "^5.9.3",
48
+ "vitest": "^4.0.18"
49
+ }
50
+ }