@encatch/web-sdk 1.1.0-beta.0 → 1.1.0-beta.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.
@@ -1,2 +1,2 @@
1
- const e="encatch-sdk-script";let t=!1,n=!1,i=null;function o(o){return n?Promise.resolve():i?Promise.reject(i):t?new Promise((e,t)=>{const o=setInterval(()=>{n?(clearInterval(o),e()):i&&(clearInterval(o),t(i))},50)}):(t=!0,new Promise((r,s)=>{if(document.getElementById(e))return t=!1,n=!0,void r();const a=(o.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js?dt="+function(){const e=/* @__PURE__ */new Date,t=String(e.getUTCFullYear()).slice(-2),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),r=30*Math.floor(e.getUTCMinutes()/30);return`${t}${n}${i}${o}${String(r).padStart(2,"0")}`}(),c=document.createElement("script");c.id=e,c.src=a,c.type="module",c.async=!0,c.onload=()=>{t=!1,n=!0,r()},c.onerror=e=>{t=!1,i=new Error(`[Encatch] Failed to load SDK from ${a}. Please check your network connection and web host configuration.`),console.error(i.message,e),s(i)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(c,d):document.head.appendChild(c)}))}function r(e,t){return function(...n){e.push([t,...n])}}const s=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse"];function a(){const e=[],t=[],n={_q:e,_eventCallbacks:t,_initialized:!1,_apiKey:null,_config:{},init(t,i){n._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(n._apiKey=t,n._config=i||{},n._initialized=!0,e.push(["init",t,i]),"undefined"!=typeof window&&"undefined"!=typeof document&&o(n._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on:e=>(t.push(e),()=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)}),identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},dismissForm:()=>{},addToResponse:()=>{}},i=s.filter(e=>"init"!==e);for(const o of i)n[o]=r(e,o);return n}const c=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const t=a();return t._q.push(...e._q),Array.isArray(e._eventCallbacks)&&t._eventCallbacks.push(...e._eventCallbacks),e._initialized&&(t._initialized=e._initialized,t._apiKey=e._apiKey,t._config=e._config||{}),window._encatch=t,t}const t=a();return window._encatch=t,t}return a()}();export{c as _encatch,c as default};
1
+ const e="encatch-sdk-script";let t=!1,n=!1,i=null;function r(r){return n?Promise.resolve():i?Promise.reject(i):t?new Promise((e,t)=>{const r=setInterval(()=>{n?(clearInterval(r),e()):i&&(clearInterval(r),t(i))},50)}):(t=!0,new Promise((o,s)=>{if(document.getElementById(e))return t=!1,n=!0,void o();const a=(r.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js?dt="+function(){const e=/* @__PURE__ */new Date,t=String(e.getUTCFullYear()).slice(-2),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),r=String(e.getUTCHours()).padStart(2,"0"),o=30*Math.floor(e.getUTCMinutes()/30);return`${t}${n}${i}${r}${String(o).padStart(2,"0")}`}(),c=document.createElement("script");c.id=e,c.src=a,c.type="module",c.async=!0,c.onload=()=>{t=!1,n=!0,o()},c.onerror=e=>{t=!1,i=new Error(`[Encatch] Failed to load SDK from ${a}. Please check your network connection and web host configuration.`),console.error(i.message,e),s(i)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(c,d):document.head.appendChild(c)}))}function o(e,t){return function(...n){e.push([t,...n])}}const s=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse","submitForm","emitEvent"];function a(){const e=[],t=[],n={_q:e,_eventCallbacks:t,_initialized:!1,_apiKey:null,_config:{},init(t,i){n._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(n._apiKey=t,n._config=i||{},n._initialized=!0,e.push(["init",t,i]),"undefined"!=typeof window&&"undefined"!=typeof document&&r(n._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on:e=>(t.push(e),()=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)}),identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},dismissForm:()=>{},addToResponse:()=>{},submitForm:()=>{},emitEvent:()=>{},refineText:()=>Promise.resolve({})},i=s.filter(e=>"init"!==e);for(const r of i)n[r]=o(e,r);return n}const c=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const t=a();return t._q.push(...e._q),Array.isArray(e._eventCallbacks)&&t._eventCallbacks.push(...e._eventCallbacks),e._initialized&&(t._initialized=e._initialized,t._apiKey=e._apiKey,t._config=e._config||{}),window._encatch=t,t}const t=a();return window._encatch=t,t}return a()}();export{c as _encatch,c as default};
2
2
  //# sourceMappingURL=encatch.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"encatch.es.js","sources":["../src/loader.ts","../src/queue.ts","../src/index.ts"],"sourcesContent":["/**\n * Script Loader Utility\n * \n * Handles the dynamic loading of the remote SDK implementation script.\n * Provides error handling and prevents duplicate script injection.\n */\n\nimport type { EncatchConfig } from './types';\n\n/** Default web host for the remote implementation script */\nconst DEFAULT_WEB_HOST = 'https://app.encatch.com';\n\n/** Fixed path for the SDK script */\nconst SDK_SCRIPT_PATH = '/s/sdk/v1/encatch.js';\n\n/** Script element ID to prevent duplicate injections */\nconst SCRIPT_ID = 'encatch-sdk-script';\n\n/**\n * Returns a cache-bust string that changes at most every 30 minutes (YYMMDDHHmm, mm is 00 or 30).\n * Allows the script to be cached for up to 30 minutes before a new URL triggers a fresh fetch.\n */\nfunction getCacheBustParam(): string {\n const d = new Date();\n const yy = String(d.getUTCFullYear()).slice(-2);\n const mm = String(d.getUTCMonth() + 1).padStart(2, '0');\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const min30 = Math.floor(d.getUTCMinutes() / 30) * 30;\n const minStr = String(min30).padStart(2, '0');\n return `${yy}${mm}${dd}${hh}${minStr}`;\n}\n\n/** Track loading state */\nlet isLoading = false;\nlet isLoaded = false;\nlet loadError: Error | null = null;\n\n/**\n * Load the remote SDK implementation script\n * \n * @param config - Configuration containing optional custom web host\n * @returns Promise that resolves when script loads, rejects on error\n */\nexport function loadRemoteScript(config: EncatchConfig): Promise<void> {\n // Return early if already loaded\n if (isLoaded) {\n return Promise.resolve();\n }\n\n // Return error if previous load failed\n if (loadError) {\n return Promise.reject(loadError);\n }\n\n // Return existing promise if already loading\n if (isLoading) {\n return new Promise((resolve, reject) => {\n const checkInterval = setInterval(() => {\n if (isLoaded) {\n clearInterval(checkInterval);\n resolve();\n } else if (loadError) {\n clearInterval(checkInterval);\n reject(loadError);\n }\n }, 50);\n });\n }\n\n isLoading = true;\n\n return new Promise((resolve, reject) => {\n // Check if script already exists in DOM\n const existingScript = document.getElementById(SCRIPT_ID);\n if (existingScript) {\n isLoading = false;\n isLoaded = true;\n resolve();\n return;\n }\n\n // Determine script URL from webHost (with 30-min cache-bust so script is cached at most 30 min)\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n\n // Create and configure script element\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.src = scriptUrl;\n script.type = 'module';\n script.async = true;\n\n // Handle successful load\n script.onload = () => {\n isLoading = false;\n isLoaded = true;\n resolve();\n };\n\n // Handle load error\n script.onerror = (event) => {\n isLoading = false;\n loadError = new Error(\n `[Encatch] Failed to load SDK from ${scriptUrl}. ` +\n `Please check your network connection and web host configuration.`\n );\n console.error(loadError.message, event);\n reject(loadError);\n };\n\n // Inject script into document head\n const firstScript = document.getElementsByTagName('script')[0];\n if (firstScript && firstScript.parentNode) {\n firstScript.parentNode.insertBefore(script, firstScript);\n } else {\n document.head.appendChild(script);\n }\n });\n}\n\n/**\n * Check if the remote script has been loaded\n */\nexport function isScriptLoaded(): boolean {\n return isLoaded;\n}\n\n/**\n * Reset loader state (useful for testing)\n */\nexport function resetLoaderState(): void {\n isLoading = false;\n isLoaded = false;\n loadError = null;\n}\n\n/**\n * Get the default script URL (includes current 30-min cache-bust param)\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n}\n","/**\n * Command Queue Implementation\n * \n * Manages the queue of SDK method calls that occur before the remote\n * implementation script has loaded. Commands are stored as tuples\n * and processed FIFO when the remote script becomes available.\n */\n\nimport type { Command, EncatchSDK } from './types';\n\n/**\n * Process all queued commands by calling the corresponding methods\n * on the SDK instance. This is called by the remote script once loaded.\n * \n * @param sdk - The SDK instance with real implementations\n * @param queue - Array of queued commands to process\n */\nexport function processQueue(sdk: EncatchSDK, queue: Command[]): void {\n while (queue.length > 0) {\n const command = queue.shift();\n if (!command) continue;\n\n const [method, ...args] = command;\n \n // Skip internal properties\n if (method.startsWith('_')) continue;\n\n // Get the method from the SDK\n const fn = sdk[method as keyof EncatchSDK];\n \n if (typeof fn === 'function') {\n try {\n (fn as (...args: unknown[]) => void).apply(sdk, args);\n } catch (error) {\n console.error(`[Encatch] Error processing queued command \"${method}\":`, error);\n }\n } else {\n console.warn(`[Encatch] Unknown method in queue: \"${method}\"`);\n }\n }\n}\n\n/**\n * Creates a stub method that queues calls for later processing\n * \n * @param queue - The command queue array\n * @param methodName - Name of the method being stubbed\n * @returns A function that pushes calls to the queue\n */\nexport function createQueuedMethod(\n queue: Command[],\n methodName: string\n): (...args: unknown[]) => void {\n return function (...args: unknown[]): void {\n queue.push([methodName, ...args]);\n };\n}\n\n/**\n * List of SDK methods that should be queued before initialization\n */\nexport const QUEUED_METHODS = [\n 'init',\n 'identifyUser',\n 'setLocale',\n 'setCountry',\n 'setTheme',\n 'trackEvent',\n 'trackScreen',\n 'startSession',\n 'resetUser',\n 'showForm',\n 'dismissForm',\n 'addToResponse',\n] as const;\n\nexport type QueuedMethodName = typeof QUEUED_METHODS[number];\n","/**\n * Encatch Web SDK\n * \n * A lightweight, type-safe SDK for integrating Encatch forms and surveys.\n * This module creates the _encatch global object that queues commands\n * until the remote implementation script loads.\n */\n\nimport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventCallback,\n Command,\n} from './types';\nimport { loadRemoteScript } from './loader';\nimport { createQueuedMethod, QUEUED_METHODS } from './queue';\n\n// Re-export types for consumers\nexport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n StartSessionOptions,\n EventType,\n EventCallback,\n EventPayload,\n Theme,\n ResetMode,\n ShowFormOptions,\n} from './types';\n\n/**\n * Creates the Encatch SDK stub instance\n * All method calls are queued until setProject() is called and the\n * remote implementation script loads.\n */\nfunction createEncatchStub(): EncatchSDK {\n // Command queue for calls made before remote script loads\n const queue: Command[] = [];\n \n // Event callbacks - all callbacks receive all form events\n const eventCallbacks: EventCallback[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventCallbacks: eventCallbacks,\n _initialized: false,\n _apiKey: null,\n _config: {},\n\n // init is special - it triggers script loading\n init(apiKey: string, config?: EncatchConfig): void {\n if (sdk._initialized) {\n console.warn('[Encatch] SDK already initialized. Ignoring init call.');\n return;\n }\n\n sdk._apiKey = apiKey;\n sdk._config = config || {};\n sdk._initialized = true;\n\n // Queue this call for the remote implementation\n queue.push(['init', apiKey, config]);\n\n // Load the remote script\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n loadRemoteScript(sdk._config).catch((error) => {\n console.error('[Encatch] Failed to initialize SDK:', error);\n });\n }\n },\n\n // Event subscription - receives all form events\n on(callback: EventCallback): () => void {\n eventCallbacks.push(callback);\n\n // Return unsubscribe function\n return () => {\n const index = eventCallbacks.indexOf(callback);\n if (index > -1) {\n eventCallbacks.splice(index, 1);\n }\n };\n },\n\n // Stub implementations - will be replaced by remote script\n identifyUser: () => {},\n setLocale: () => {},\n setCountry: () => {},\n setTheme: () => {},\n trackEvent: () => {},\n trackScreen: () => {},\n startSession: () => {},\n resetUser: () => {},\n showForm: () => {},\n dismissForm: () => {},\n addToResponse: () => {},\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on (handled locally)\n const methodsToQueue = QUEUED_METHODS.filter(m => m !== 'init');\n \n for (const method of methodsToQueue) {\n // Use type assertion to assign queued methods\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (sdk as any)[method] = createQueuedMethod(queue, method);\n }\n\n return sdk;\n}\n\n/**\n * Initialize the global _encatch object\n * This runs immediately when the script loads\n */\nfunction initGlobal(): EncatchSDK {\n // Check for existing instance (may have been created by snippet)\n if (typeof window !== 'undefined') {\n // If _encatch already exists with a queue, preserve it\n const existing = window._encatch;\n if (existing && Array.isArray(existing._q)) {\n // Merge existing queue into new instance\n const sdk = createEncatchStub();\n sdk._q.push(...existing._q);\n \n // Copy over any existing callbacks\n if (Array.isArray(existing._eventCallbacks)) {\n sdk._eventCallbacks.push(...existing._eventCallbacks);\n }\n \n // Copy initialization state\n if (existing._initialized) {\n sdk._initialized = existing._initialized;\n sdk._apiKey = existing._apiKey;\n sdk._config = existing._config || {};\n }\n \n window._encatch = sdk;\n return sdk;\n }\n\n // Create fresh instance\n const sdk = createEncatchStub();\n window._encatch = sdk;\n return sdk;\n }\n\n // Non-browser environment\n return createEncatchStub();\n}\n\n// Initialize and export\nexport const _encatch = initGlobal();\n\n// Default export for convenience\nexport default _encatch;\n"],"names":["SCRIPT_ID","isLoading","isLoaded","loadError","loadRemoteScript","config","Promise","resolve","reject","checkInterval","setInterval","clearInterval","document","getElementById","scriptUrl","webHost","d","Date","yy","String","getUTCFullYear","slice","mm","getUTCMonth","padStart","dd","getUTCDate","hh","getUTCHours","min30","Math","floor","getUTCMinutes","getCacheBustParam","script","createElement","id","src","type","async","onload","onerror","event","Error","console","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventCallbacks","sdk","_q","_eventCallbacks","_initialized","_apiKey","_config","init","apiKey","warn","window","catch","on","callback","index","indexOf","splice","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"AAUA,MAMMA,EAAY,qBAkBlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KAQvB,SAASC,EAAiBC,GAE/B,OAAIH,EACKI,QAAQC,UAIbJ,EACKG,QAAQE,OAAOL,GAIpBF,EACK,IAAIK,QAAQ,CAACC,EAASC,KAC3B,MAAMC,EAAgBC,YAAY,KAC5BR,GACFS,cAAcF,GACdF,KACSJ,IACTQ,cAAcF,GACdD,EAAOL,KAER,OAIPF,GAAY,EAEL,IAAIK,QAAQ,CAACC,EAASC,KAG3B,GADuBI,SAASC,eAAeb,GAK7C,OAHAC,GAAY,EACZC,GAAW,OACXK,IAKF,MACMO,GADUT,EAAOU,SAzEF,2BA0EHA,2BA9DtB,WACE,MAAMC,qBAAQC,KACRC,EAAKC,OAAOH,EAAEI,kBAAkBC,OAAM,GACtCC,EAAKH,OAAOH,EAAEO,cAAgB,GAAGC,SAAS,EAAG,KAC7CC,EAAKN,OAAOH,EAAEU,cAAcF,SAAS,EAAG,KACxCG,EAAKR,OAAOH,EAAEY,eAAeJ,SAAS,EAAG,KACzCK,EAA6C,GAArCC,KAAKC,MAAMf,EAAEgB,gBAAkB,IAE7C,MAAO,GAAGd,IAAKI,IAAKG,IAAKE,IADVR,OAAOU,GAA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,OACZC,SAAU,OACVC,WAAY,OACZC,YAAa,OACbC,aAAc,OACdC,UAAW,OACXC,SAAU,OACVC,YAAa,OACbC,cAAe,QAKXC,EAAiB9B,EAAe+B,OAAOC,GAAW,SAANA,GAElD,IAAA,MAAWC,KAAUH,EAGlB3B,EAAY8B,GAAUtC,EAAmBC,EAAOqC,GAGnD,OAAO9B,CACT,CA2CO,MAAM+B,EArCb,WAEE,GAAsB,oBAAXtB,OAAwB,CAEjC,MAAMuB,EAAWvB,OAAOsB,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAAS/B,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQoC,EAAS/B,IAGpBgC,MAAMC,QAAQF,EAAS9B,kBACzBF,EAAIE,gBAAgBN,QAAQoC,EAAS9B,iBAInC8B,EAAS7B,eACXH,EAAIG,aAAe6B,EAAS7B,aAC5BH,EAAII,QAAU4B,EAAS5B,QACvBJ,EAAIK,QAAU2B,EAAS3B,SAAW,CAAA,GAGpCI,OAAOsB,SAAW/B,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAW,OAAOsB,SAAW/B,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBqC"}
1
+ {"version":3,"file":"encatch.es.js","sources":["../src/loader.ts","../src/queue.ts","../src/index.ts"],"sourcesContent":["/**\n * Script Loader Utility\n * \n * Handles the dynamic loading of the remote SDK implementation script.\n * Provides error handling and prevents duplicate script injection.\n */\n\nimport type { EncatchConfig } from './types';\n\n/** Default web host for the remote implementation script */\nconst DEFAULT_WEB_HOST = 'https://app.encatch.com';\n\n/** Fixed path for the SDK script */\nconst SDK_SCRIPT_PATH = '/s/sdk/v1/encatch.js';\n\n/** Script element ID to prevent duplicate injections */\nconst SCRIPT_ID = 'encatch-sdk-script';\n\n/**\n * Returns a cache-bust string that changes at most every 30 minutes (YYMMDDHHmm, mm is 00 or 30).\n * Allows the script to be cached for up to 30 minutes before a new URL triggers a fresh fetch.\n */\nfunction getCacheBustParam(): string {\n const d = new Date();\n const yy = String(d.getUTCFullYear()).slice(-2);\n const mm = String(d.getUTCMonth() + 1).padStart(2, '0');\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const min30 = Math.floor(d.getUTCMinutes() / 30) * 30;\n const minStr = String(min30).padStart(2, '0');\n return `${yy}${mm}${dd}${hh}${minStr}`;\n}\n\n/** Track loading state */\nlet isLoading = false;\nlet isLoaded = false;\nlet loadError: Error | null = null;\n\n/**\n * Load the remote SDK implementation script\n * \n * @param config - Configuration containing optional custom web host\n * @returns Promise that resolves when script loads, rejects on error\n */\nexport function loadRemoteScript(config: EncatchConfig): Promise<void> {\n // Return early if already loaded\n if (isLoaded) {\n return Promise.resolve();\n }\n\n // Return error if previous load failed\n if (loadError) {\n return Promise.reject(loadError);\n }\n\n // Return existing promise if already loading\n if (isLoading) {\n return new Promise((resolve, reject) => {\n const checkInterval = setInterval(() => {\n if (isLoaded) {\n clearInterval(checkInterval);\n resolve();\n } else if (loadError) {\n clearInterval(checkInterval);\n reject(loadError);\n }\n }, 50);\n });\n }\n\n isLoading = true;\n\n return new Promise((resolve, reject) => {\n // Check if script already exists in DOM\n const existingScript = document.getElementById(SCRIPT_ID);\n if (existingScript) {\n isLoading = false;\n isLoaded = true;\n resolve();\n return;\n }\n\n // Determine script URL from webHost (with 30-min cache-bust so script is cached at most 30 min)\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n\n // Create and configure script element\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.src = scriptUrl;\n script.type = 'module';\n script.async = true;\n\n // Handle successful load\n script.onload = () => {\n isLoading = false;\n isLoaded = true;\n resolve();\n };\n\n // Handle load error\n script.onerror = (event) => {\n isLoading = false;\n loadError = new Error(\n `[Encatch] Failed to load SDK from ${scriptUrl}. ` +\n `Please check your network connection and web host configuration.`\n );\n console.error(loadError.message, event);\n reject(loadError);\n };\n\n // Inject script into document head\n const firstScript = document.getElementsByTagName('script')[0];\n if (firstScript && firstScript.parentNode) {\n firstScript.parentNode.insertBefore(script, firstScript);\n } else {\n document.head.appendChild(script);\n }\n });\n}\n\n/**\n * Check if the remote script has been loaded\n */\nexport function isScriptLoaded(): boolean {\n return isLoaded;\n}\n\n/**\n * Reset loader state (useful for testing)\n */\nexport function resetLoaderState(): void {\n isLoading = false;\n isLoaded = false;\n loadError = null;\n}\n\n/**\n * Get the default script URL (includes current 30-min cache-bust param)\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n}\n","/**\n * Command Queue Implementation\n * \n * Manages the queue of SDK method calls that occur before the remote\n * implementation script has loaded. Commands are stored as tuples\n * and processed FIFO when the remote script becomes available.\n */\n\nimport type { Command, EncatchSDK } from './types';\n\n/**\n * Process all queued commands by calling the corresponding methods\n * on the SDK instance. This is called by the remote script once loaded.\n * \n * @param sdk - The SDK instance with real implementations\n * @param queue - Array of queued commands to process\n */\nexport function processQueue(sdk: EncatchSDK, queue: Command[]): void {\n while (queue.length > 0) {\n const command = queue.shift();\n if (!command) continue;\n\n const [method, ...args] = command;\n \n // Skip internal properties\n if (method.startsWith('_')) continue;\n\n // Get the method from the SDK\n const fn = sdk[method as keyof EncatchSDK];\n \n if (typeof fn === 'function') {\n try {\n (fn as (...args: unknown[]) => void).apply(sdk, args);\n } catch (error) {\n console.error(`[Encatch] Error processing queued command \"${method}\":`, error);\n }\n } else {\n console.warn(`[Encatch] Unknown method in queue: \"${method}\"`);\n }\n }\n}\n\n/**\n * Creates a stub method that queues calls for later processing\n * \n * @param queue - The command queue array\n * @param methodName - Name of the method being stubbed\n * @returns A function that pushes calls to the queue\n */\nexport function createQueuedMethod(\n queue: Command[],\n methodName: string\n): (...args: unknown[]) => void {\n return function (...args: unknown[]): void {\n queue.push([methodName, ...args]);\n };\n}\n\n/**\n * List of SDK methods that should be queued before initialization\n */\nexport const QUEUED_METHODS = [\n 'init',\n 'identifyUser',\n 'setLocale',\n 'setCountry',\n 'setTheme',\n 'trackEvent',\n 'trackScreen',\n 'startSession',\n 'resetUser',\n 'showForm',\n 'dismissForm',\n 'addToResponse',\n 'submitForm',\n 'emitEvent',\n] as const;\n\nexport type QueuedMethodName = typeof QUEUED_METHODS[number];\n","/**\n * Encatch Web SDK\n * \n * A lightweight, type-safe SDK for integrating Encatch forms and surveys.\n * This module creates the _encatch global object that queues commands\n * until the remote implementation script loads.\n */\n\nimport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventCallback,\n Command,\n} from './types';\nimport { loadRemoteScript } from './loader';\nimport { createQueuedMethod, QUEUED_METHODS } from './queue';\n\n// Re-export types for consumers\nexport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n StartSessionOptions,\n EventType,\n EventCallback,\n EventPayload,\n Theme,\n ResetMode,\n ShowFormOptions,\n ShowFormInterceptorPayload,\n SubmitFormRequest,\n FormDetails,\n QuestionResponse,\n QuestionAnswer,\n RefineTextRequest,\n RefineTextResponse,\n} from './types';\n\n/**\n * Creates the Encatch SDK stub instance\n * All method calls are queued until setProject() is called and the\n * remote implementation script loads.\n */\nfunction createEncatchStub(): EncatchSDK {\n // Command queue for calls made before remote script loads\n const queue: Command[] = [];\n \n // Event callbacks - all callbacks receive all form events\n const eventCallbacks: EventCallback[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventCallbacks: eventCallbacks,\n _initialized: false,\n _apiKey: null,\n _config: {},\n\n // init is special - it triggers script loading\n init(apiKey: string, config?: EncatchConfig): void {\n if (sdk._initialized) {\n console.warn('[Encatch] SDK already initialized. Ignoring init call.');\n return;\n }\n\n sdk._apiKey = apiKey;\n sdk._config = config || {};\n sdk._initialized = true;\n\n // Queue this call for the remote implementation\n queue.push(['init', apiKey, config]);\n\n // Load the remote script\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n loadRemoteScript(sdk._config).catch((error) => {\n console.error('[Encatch] Failed to initialize SDK:', error);\n });\n }\n },\n\n // Event subscription - receives all form events\n on(callback: EventCallback): () => void {\n eventCallbacks.push(callback);\n\n // Return unsubscribe function\n return () => {\n const index = eventCallbacks.indexOf(callback);\n if (index > -1) {\n eventCallbacks.splice(index, 1);\n }\n };\n },\n\n // Stub implementations - will be replaced by remote script\n identifyUser: () => {},\n setLocale: () => {},\n setCountry: () => {},\n setTheme: () => {},\n trackEvent: () => {},\n trackScreen: () => {},\n startSession: () => {},\n resetUser: () => {},\n showForm: () => {},\n dismissForm: () => {},\n addToResponse: () => {},\n submitForm: () => {},\n emitEvent: () => {},\n refineText: () => Promise.resolve({}),\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on (handled locally)\n const methodsToQueue = QUEUED_METHODS.filter(m => m !== 'init');\n \n for (const method of methodsToQueue) {\n // Use type assertion to assign queued methods\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (sdk as any)[method] = createQueuedMethod(queue, method);\n }\n\n return sdk;\n}\n\n/**\n * Initialize the global _encatch object\n * This runs immediately when the script loads\n */\nfunction initGlobal(): EncatchSDK {\n // Check for existing instance (may have been created by snippet)\n if (typeof window !== 'undefined') {\n // If _encatch already exists with a queue, preserve it\n const existing = window._encatch;\n if (existing && Array.isArray(existing._q)) {\n // Merge existing queue into new instance\n const sdk = createEncatchStub();\n sdk._q.push(...existing._q);\n \n // Copy over any existing callbacks\n if (Array.isArray(existing._eventCallbacks)) {\n sdk._eventCallbacks.push(...existing._eventCallbacks);\n }\n \n // Copy initialization state\n if (existing._initialized) {\n sdk._initialized = existing._initialized;\n sdk._apiKey = existing._apiKey;\n sdk._config = existing._config || {};\n }\n \n window._encatch = sdk;\n return sdk;\n }\n\n // Create fresh instance\n const sdk = createEncatchStub();\n window._encatch = sdk;\n return sdk;\n }\n\n // Non-browser environment\n return createEncatchStub();\n}\n\n// Initialize and export\nexport const _encatch = initGlobal();\n\n// Default export for convenience\nexport default _encatch;\n"],"names":["SCRIPT_ID","isLoading","isLoaded","loadError","loadRemoteScript","config","Promise","resolve","reject","checkInterval","setInterval","clearInterval","document","getElementById","scriptUrl","webHost","d","Date","yy","String","getUTCFullYear","slice","mm","getUTCMonth","padStart","dd","getUTCDate","hh","getUTCHours","min30","Math","floor","getUTCMinutes","getCacheBustParam","script","createElement","id","src","type","async","onload","onerror","event","Error","console","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventCallbacks","sdk","_q","_eventCallbacks","_initialized","_apiKey","_config","init","apiKey","warn","window","catch","on","callback","index","indexOf","splice","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse","submitForm","emitEvent","refineText","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"AAUA,MAMMA,EAAY,qBAkBlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KAQvB,SAASC,EAAiBC,GAE/B,OAAIH,EACKI,QAAQC,UAIbJ,EACKG,QAAQE,OAAOL,GAIpBF,EACK,IAAIK,QAAQ,CAACC,EAASC,KAC3B,MAAMC,EAAgBC,YAAY,KAC5BR,GACFS,cAAcF,GACdF,KACSJ,IACTQ,cAAcF,GACdD,EAAOL,KAER,OAIPF,GAAY,EAEL,IAAIK,QAAQ,CAACC,EAASC,KAG3B,GADuBI,SAASC,eAAeb,GAK7C,OAHAC,GAAY,EACZC,GAAW,OACXK,IAKF,MACMO,GADUT,EAAOU,SAzEF,2BA0EHA,2BA9DtB,WACE,MAAMC,qBAAQC,KACRC,EAAKC,OAAOH,EAAEI,kBAAkBC,OAAM,GACtCC,EAAKH,OAAOH,EAAEO,cAAgB,GAAGC,SAAS,EAAG,KAC7CC,EAAKN,OAAOH,EAAEU,cAAcF,SAAS,EAA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AM,sCAAuCA,KAG3D,EAGA2B,GAAGC,IACDb,EAAeH,KAAKgB,GAGb,KACL,MAAMC,EAAQd,EAAee,QAAQF,GACjCC,GAAQ,GACVd,EAAegB,OAAOF,EAAO,KAMnCG,aAAc,OACdC,UAAW,OACXC,WAAY,OACZC,SAAU,OACVC,WAAY,OACZC,YAAa,OACbC,aAAc,OACdC,UAAW,OACXC,SAAU,OACVC,YAAa,OACbC,cAAe,OACfC,WAAY,OACZC,UAAW,OACXC,WAAY,IAAMpF,QAAQC,QAAQ,CAAA,IAK9BoF,EAAiBjC,EAAekC,OAAOC,GAAW,SAANA,GAElD,IAAA,MAAWC,KAAUH,EAGlB9B,EAAYiC,GAAUzC,EAAmBC,EAAOwC,GAGnD,OAAOjC,CACT,CA2CO,MAAMkC,EArCb,WAEE,GAAsB,oBAAXzB,OAAwB,CAEjC,MAAM0B,EAAW1B,OAAOyB,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAASlC,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQuC,EAASlC,IAGpBmC,MAAMC,QAAQF,EAASjC,kBACzBF,EAAIE,gBAAgBN,QAAQuC,EAASjC,iBAInCiC,EAAShC,eACXH,EAAIG,aAAegC,EAAShC,aAC5BH,EAAII,QAAU+B,EAAS/B,QACvBJ,EAAIK,QAAU8B,EAAS9B,SAAW,CAAA,GAGpCI,OAAOyB,SAAWlC,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAW,OAAOyB,SAAWlC,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBwC"}
@@ -1,2 +1,2 @@
1
- !function(e){"use strict";const t="encatch-sdk-script";let n=!1,i=!1,o=null;function r(e){return i?Promise.resolve():o?Promise.reject(o):n?new Promise((e,t)=>{const n=setInterval(()=>{i?(clearInterval(n),e()):o&&(clearInterval(n),t(o))},50)}):(n=!0,new Promise((r,c)=>{if(document.getElementById(t))return n=!1,i=!0,void r();const s=(e.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js?dt="+function(){const e=new Date,t=String(e.getUTCFullYear()).slice(-2),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),r=30*Math.floor(e.getUTCMinutes()/30);return`${t}${n}${i}${o}${String(r).padStart(2,"0")}`}(),a=document.createElement("script");a.id=t,a.src=s,a.type="module",a.async=!0,a.onload=()=>{n=!1,i=!0,r()},a.onerror=e=>{n=!1,o=new Error(`[Encatch] Failed to load SDK from ${s}. Please check your network connection and web host configuration.`),console.error(o.message,e),c(o)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(a,d):document.head.appendChild(a)}))}function c(e,t){return function(...n){e.push([t,...n])}}const s=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse"];function a(){const e=[],t=[],n={_q:e,_eventCallbacks:t,_initialized:!1,_apiKey:null,_config:{},init(t,i){n._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(n._apiKey=t,n._config=i||{},n._initialized=!0,e.push(["init",t,i]),"undefined"!=typeof window&&"undefined"!=typeof document&&r(n._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on:e=>(t.push(e),()=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)}),identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},dismissForm:()=>{},addToResponse:()=>{}},i=s.filter(e=>"init"!==e);for(const o of i)n[o]=c(e,o);return n}const d=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const t=a();return t._q.push(...e._q),Array.isArray(e._eventCallbacks)&&t._eventCallbacks.push(...e._eventCallbacks),e._initialized&&(t._initialized=e._initialized,t._apiKey=e._apiKey,t._config=e._config||{}),window._encatch=t,t}const t=a();return window._encatch=t,t}return a()}();e._encatch=d,e.default=d,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}(this._encatch=this._encatch||{});
1
+ !function(e){"use strict";const t="encatch-sdk-script";let n=!1,i=!1,o=null;function r(e){return i?Promise.resolve():o?Promise.reject(o):n?new Promise((e,t)=>{const n=setInterval(()=>{i?(clearInterval(n),e()):o&&(clearInterval(n),t(o))},50)}):(n=!0,new Promise((r,s)=>{if(document.getElementById(t))return n=!1,i=!0,void r();const c=(e.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js?dt="+function(){const e=new Date,t=String(e.getUTCFullYear()).slice(-2),n=String(e.getUTCMonth()+1).padStart(2,"0"),i=String(e.getUTCDate()).padStart(2,"0"),o=String(e.getUTCHours()).padStart(2,"0"),r=30*Math.floor(e.getUTCMinutes()/30);return`${t}${n}${i}${o}${String(r).padStart(2,"0")}`}(),a=document.createElement("script");a.id=t,a.src=c,a.type="module",a.async=!0,a.onload=()=>{n=!1,i=!0,r()},a.onerror=e=>{n=!1,o=new Error(`[Encatch] Failed to load SDK from ${c}. Please check your network connection and web host configuration.`),console.error(o.message,e),s(o)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(a,d):document.head.appendChild(a)}))}function s(e,t){return function(...n){e.push([t,...n])}}const c=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse","submitForm","emitEvent"];function a(){const e=[],t=[],n={_q:e,_eventCallbacks:t,_initialized:!1,_apiKey:null,_config:{},init(t,i){n._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(n._apiKey=t,n._config=i||{},n._initialized=!0,e.push(["init",t,i]),"undefined"!=typeof window&&"undefined"!=typeof document&&r(n._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on:e=>(t.push(e),()=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)}),identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},dismissForm:()=>{},addToResponse:()=>{},submitForm:()=>{},emitEvent:()=>{},refineText:()=>Promise.resolve({})},i=c.filter(e=>"init"!==e);for(const o of i)n[o]=s(e,o);return n}const d=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const t=a();return t._q.push(...e._q),Array.isArray(e._eventCallbacks)&&t._eventCallbacks.push(...e._eventCallbacks),e._initialized&&(t._initialized=e._initialized,t._apiKey=e._apiKey,t._config=e._config||{}),window._encatch=t,t}const t=a();return window._encatch=t,t}return a()}();e._encatch=d,e.default=d,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}(this._encatch=this._encatch||{});
2
2
  //# sourceMappingURL=encatch.iife.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"encatch.iife.js","sources":["../src/loader.ts","../src/queue.ts","../src/index.ts"],"sourcesContent":["/**\n * Script Loader Utility\n * \n * Handles the dynamic loading of the remote SDK implementation script.\n * Provides error handling and prevents duplicate script injection.\n */\n\nimport type { EncatchConfig } from './types';\n\n/** Default web host for the remote implementation script */\nconst DEFAULT_WEB_HOST = 'https://app.encatch.com';\n\n/** Fixed path for the SDK script */\nconst SDK_SCRIPT_PATH = '/s/sdk/v1/encatch.js';\n\n/** Script element ID to prevent duplicate injections */\nconst SCRIPT_ID = 'encatch-sdk-script';\n\n/**\n * Returns a cache-bust string that changes at most every 30 minutes (YYMMDDHHmm, mm is 00 or 30).\n * Allows the script to be cached for up to 30 minutes before a new URL triggers a fresh fetch.\n */\nfunction getCacheBustParam(): string {\n const d = new Date();\n const yy = String(d.getUTCFullYear()).slice(-2);\n const mm = String(d.getUTCMonth() + 1).padStart(2, '0');\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const min30 = Math.floor(d.getUTCMinutes() / 30) * 30;\n const minStr = String(min30).padStart(2, '0');\n return `${yy}${mm}${dd}${hh}${minStr}`;\n}\n\n/** Track loading state */\nlet isLoading = false;\nlet isLoaded = false;\nlet loadError: Error | null = null;\n\n/**\n * Load the remote SDK implementation script\n * \n * @param config - Configuration containing optional custom web host\n * @returns Promise that resolves when script loads, rejects on error\n */\nexport function loadRemoteScript(config: EncatchConfig): Promise<void> {\n // Return early if already loaded\n if (isLoaded) {\n return Promise.resolve();\n }\n\n // Return error if previous load failed\n if (loadError) {\n return Promise.reject(loadError);\n }\n\n // Return existing promise if already loading\n if (isLoading) {\n return new Promise((resolve, reject) => {\n const checkInterval = setInterval(() => {\n if (isLoaded) {\n clearInterval(checkInterval);\n resolve();\n } else if (loadError) {\n clearInterval(checkInterval);\n reject(loadError);\n }\n }, 50);\n });\n }\n\n isLoading = true;\n\n return new Promise((resolve, reject) => {\n // Check if script already exists in DOM\n const existingScript = document.getElementById(SCRIPT_ID);\n if (existingScript) {\n isLoading = false;\n isLoaded = true;\n resolve();\n return;\n }\n\n // Determine script URL from webHost (with 30-min cache-bust so script is cached at most 30 min)\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n\n // Create and configure script element\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.src = scriptUrl;\n script.type = 'module';\n script.async = true;\n\n // Handle successful load\n script.onload = () => {\n isLoading = false;\n isLoaded = true;\n resolve();\n };\n\n // Handle load error\n script.onerror = (event) => {\n isLoading = false;\n loadError = new Error(\n `[Encatch] Failed to load SDK from ${scriptUrl}. ` +\n `Please check your network connection and web host configuration.`\n );\n console.error(loadError.message, event);\n reject(loadError);\n };\n\n // Inject script into document head\n const firstScript = document.getElementsByTagName('script')[0];\n if (firstScript && firstScript.parentNode) {\n firstScript.parentNode.insertBefore(script, firstScript);\n } else {\n document.head.appendChild(script);\n }\n });\n}\n\n/**\n * Check if the remote script has been loaded\n */\nexport function isScriptLoaded(): boolean {\n return isLoaded;\n}\n\n/**\n * Reset loader state (useful for testing)\n */\nexport function resetLoaderState(): void {\n isLoading = false;\n isLoaded = false;\n loadError = null;\n}\n\n/**\n * Get the default script URL (includes current 30-min cache-bust param)\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n}\n","/**\n * Command Queue Implementation\n * \n * Manages the queue of SDK method calls that occur before the remote\n * implementation script has loaded. Commands are stored as tuples\n * and processed FIFO when the remote script becomes available.\n */\n\nimport type { Command, EncatchSDK } from './types';\n\n/**\n * Process all queued commands by calling the corresponding methods\n * on the SDK instance. This is called by the remote script once loaded.\n * \n * @param sdk - The SDK instance with real implementations\n * @param queue - Array of queued commands to process\n */\nexport function processQueue(sdk: EncatchSDK, queue: Command[]): void {\n while (queue.length > 0) {\n const command = queue.shift();\n if (!command) continue;\n\n const [method, ...args] = command;\n \n // Skip internal properties\n if (method.startsWith('_')) continue;\n\n // Get the method from the SDK\n const fn = sdk[method as keyof EncatchSDK];\n \n if (typeof fn === 'function') {\n try {\n (fn as (...args: unknown[]) => void).apply(sdk, args);\n } catch (error) {\n console.error(`[Encatch] Error processing queued command \"${method}\":`, error);\n }\n } else {\n console.warn(`[Encatch] Unknown method in queue: \"${method}\"`);\n }\n }\n}\n\n/**\n * Creates a stub method that queues calls for later processing\n * \n * @param queue - The command queue array\n * @param methodName - Name of the method being stubbed\n * @returns A function that pushes calls to the queue\n */\nexport function createQueuedMethod(\n queue: Command[],\n methodName: string\n): (...args: unknown[]) => void {\n return function (...args: unknown[]): void {\n queue.push([methodName, ...args]);\n };\n}\n\n/**\n * List of SDK methods that should be queued before initialization\n */\nexport const QUEUED_METHODS = [\n 'init',\n 'identifyUser',\n 'setLocale',\n 'setCountry',\n 'setTheme',\n 'trackEvent',\n 'trackScreen',\n 'startSession',\n 'resetUser',\n 'showForm',\n 'dismissForm',\n 'addToResponse',\n] as const;\n\nexport type QueuedMethodName = typeof QUEUED_METHODS[number];\n","/**\n * Encatch Web SDK\n * \n * A lightweight, type-safe SDK for integrating Encatch forms and surveys.\n * This module creates the _encatch global object that queues commands\n * until the remote implementation script loads.\n */\n\nimport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventCallback,\n Command,\n} from './types';\nimport { loadRemoteScript } from './loader';\nimport { createQueuedMethod, QUEUED_METHODS } from './queue';\n\n// Re-export types for consumers\nexport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n StartSessionOptions,\n EventType,\n EventCallback,\n EventPayload,\n Theme,\n ResetMode,\n ShowFormOptions,\n} from './types';\n\n/**\n * Creates the Encatch SDK stub instance\n * All method calls are queued until setProject() is called and the\n * remote implementation script loads.\n */\nfunction createEncatchStub(): EncatchSDK {\n // Command queue for calls made before remote script loads\n const queue: Command[] = [];\n \n // Event callbacks - all callbacks receive all form events\n const eventCallbacks: EventCallback[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventCallbacks: eventCallbacks,\n _initialized: false,\n _apiKey: null,\n _config: {},\n\n // init is special - it triggers script loading\n init(apiKey: string, config?: EncatchConfig): void {\n if (sdk._initialized) {\n console.warn('[Encatch] SDK already initialized. Ignoring init call.');\n return;\n }\n\n sdk._apiKey = apiKey;\n sdk._config = config || {};\n sdk._initialized = true;\n\n // Queue this call for the remote implementation\n queue.push(['init', apiKey, config]);\n\n // Load the remote script\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n loadRemoteScript(sdk._config).catch((error) => {\n console.error('[Encatch] Failed to initialize SDK:', error);\n });\n }\n },\n\n // Event subscription - receives all form events\n on(callback: EventCallback): () => void {\n eventCallbacks.push(callback);\n\n // Return unsubscribe function\n return () => {\n const index = eventCallbacks.indexOf(callback);\n if (index > -1) {\n eventCallbacks.splice(index, 1);\n }\n };\n },\n\n // Stub implementations - will be replaced by remote script\n identifyUser: () => {},\n setLocale: () => {},\n setCountry: () => {},\n setTheme: () => {},\n trackEvent: () => {},\n trackScreen: () => {},\n startSession: () => {},\n resetUser: () => {},\n showForm: () => {},\n dismissForm: () => {},\n addToResponse: () => {},\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on (handled locally)\n const methodsToQueue = QUEUED_METHODS.filter(m => m !== 'init');\n \n for (const method of methodsToQueue) {\n // Use type assertion to assign queued methods\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (sdk as any)[method] = createQueuedMethod(queue, method);\n }\n\n return sdk;\n}\n\n/**\n * Initialize the global _encatch object\n * This runs immediately when the script loads\n */\nfunction initGlobal(): EncatchSDK {\n // Check for existing instance (may have been created by snippet)\n if (typeof window !== 'undefined') {\n // If _encatch already exists with a queue, preserve it\n const existing = window._encatch;\n if (existing && Array.isArray(existing._q)) {\n // Merge existing queue into new instance\n const sdk = createEncatchStub();\n sdk._q.push(...existing._q);\n \n // Copy over any existing callbacks\n if (Array.isArray(existing._eventCallbacks)) {\n sdk._eventCallbacks.push(...existing._eventCallbacks);\n }\n \n // Copy initialization state\n if (existing._initialized) {\n sdk._initialized = existing._initialized;\n sdk._apiKey = existing._apiKey;\n sdk._config = existing._config || {};\n }\n \n window._encatch = sdk;\n return sdk;\n }\n\n // Create fresh instance\n const sdk = createEncatchStub();\n window._encatch = sdk;\n return sdk;\n }\n\n // Non-browser environment\n return createEncatchStub();\n}\n\n// Initialize and export\nexport const _encatch = initGlobal();\n\n// Default export for convenience\nexport default _encatch;\n"],"names":["SCRIPT_ID","isLoading","isLoaded","loadError","loadRemoteScript","config","Promise","resolve","reject","checkInterval","setInterval","clearInterval","document","getElementById","scriptUrl","webHost","d","Date","yy","String","getUTCFullYear","slice","mm","getUTCMonth","padStart","dd","getUTCDate","hh","getUTCHours","min30","Math","floor","getUTCMinutes","getCacheBustParam","script","createElement","id","src","type","async","onload","onerror","event","Error","console","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventCallbacks","sdk","_q","_eventCallbacks","_initialized","_apiKey","_config","init","apiKey","warn","window","catch","on","callback","index","indexOf","splice","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"0BAUA,MAMMA,EAAY,qBAkBlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KAQvB,SAASC,EAAiBC,GAE/B,OAAIH,EACKI,QAAQC,UAIbJ,EACKG,QAAQE,OAAOL,GAIpBF,EACK,IAAIK,QAAQ,CAACC,EAASC,KAC3B,MAAMC,EAAgBC,YAAY,KAC5BR,GACFS,cAAcF,GACdF,KACSJ,IACTQ,cAAcF,GACdD,EAAOL,KAER,OAIPF,GAAY,EAEL,IAAIK,QAAQ,CAACC,EAASC,KAG3B,GADuBI,SAASC,eAAeb,GAK7C,OAHAC,GAAY,EACZC,GAAW,OACXK,IAKF,MACMO,GADUT,EAAOU,SAzEF,2BA0EHA,2BA9DtB,WACE,MAAMC,MAAQC,KACRC,EAAKC,OAAOH,EAAEI,kBAAkBC,OAAM,GACtCC,EAAKH,OAAOH,EAAEO,cAAgB,GAAGC,SAAS,EAAG,KAC7CC,EAAKN,OAAOH,EAAEU,cAAcF,SAAS,EAAG,KACxCG,EAAKR,OAAOH,EAAEY,eAAeJ,SAAS,EAAG,KACzCK,EAA6C,GAArCC,KAAKC,MAAMf,EAAEgB,gBAAkB,IAE7C,MAAO,GAAGd,IAAKI,IAAKG,IAAKE,IADVR,OAAOU,GAAOL,SAAS,EAAG,MAE3C,CAqD2DS,GAGjDC,EAAStB,SAASuB,cAAc,UACtCD,EAAOE,GAAKpC,EACZkC,EAAOG,IAAMvB,EACboB,EAAOI,KAAO,SACdJ,EAAOK,OAAQ,EAGfL,EAAOM,OAAS,KACdvC,GAAY,EACZC,GAAW,EACXK,KAIF2B,EAAO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AGnD,OAAO9B,CACT,CA2CO,MAAM+B,EArCb,WAEE,GAAsB,oBAAXtB,OAAwB,CAEjC,MAAMuB,EAAWvB,OAAOsB,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAAS/B,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQoC,EAAS/B,IAGpBgC,MAAMC,QAAQF,EAAS9B,kBACzBF,EAAIE,gBAAgBN,QAAQoC,EAAS9B,iBAInC8B,EAAS7B,eACXH,EAAIG,aAAe6B,EAAS7B,aAC5BH,EAAII,QAAU4B,EAAS5B,QACvBJ,EAAIK,QAAU2B,EAAS3B,SAAW,CAAA,GAGpCI,OAAOsB,SAAW/B,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAW,OAAOsB,SAAW/B,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBqC"}
1
+ {"version":3,"file":"encatch.iife.js","sources":["../src/loader.ts","../src/queue.ts","../src/index.ts"],"sourcesContent":["/**\n * Script Loader Utility\n * \n * Handles the dynamic loading of the remote SDK implementation script.\n * Provides error handling and prevents duplicate script injection.\n */\n\nimport type { EncatchConfig } from './types';\n\n/** Default web host for the remote implementation script */\nconst DEFAULT_WEB_HOST = 'https://app.encatch.com';\n\n/** Fixed path for the SDK script */\nconst SDK_SCRIPT_PATH = '/s/sdk/v1/encatch.js';\n\n/** Script element ID to prevent duplicate injections */\nconst SCRIPT_ID = 'encatch-sdk-script';\n\n/**\n * Returns a cache-bust string that changes at most every 30 minutes (YYMMDDHHmm, mm is 00 or 30).\n * Allows the script to be cached for up to 30 minutes before a new URL triggers a fresh fetch.\n */\nfunction getCacheBustParam(): string {\n const d = new Date();\n const yy = String(d.getUTCFullYear()).slice(-2);\n const mm = String(d.getUTCMonth() + 1).padStart(2, '0');\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const min30 = Math.floor(d.getUTCMinutes() / 30) * 30;\n const minStr = String(min30).padStart(2, '0');\n return `${yy}${mm}${dd}${hh}${minStr}`;\n}\n\n/** Track loading state */\nlet isLoading = false;\nlet isLoaded = false;\nlet loadError: Error | null = null;\n\n/**\n * Load the remote SDK implementation script\n * \n * @param config - Configuration containing optional custom web host\n * @returns Promise that resolves when script loads, rejects on error\n */\nexport function loadRemoteScript(config: EncatchConfig): Promise<void> {\n // Return early if already loaded\n if (isLoaded) {\n return Promise.resolve();\n }\n\n // Return error if previous load failed\n if (loadError) {\n return Promise.reject(loadError);\n }\n\n // Return existing promise if already loading\n if (isLoading) {\n return new Promise((resolve, reject) => {\n const checkInterval = setInterval(() => {\n if (isLoaded) {\n clearInterval(checkInterval);\n resolve();\n } else if (loadError) {\n clearInterval(checkInterval);\n reject(loadError);\n }\n }, 50);\n });\n }\n\n isLoading = true;\n\n return new Promise((resolve, reject) => {\n // Check if script already exists in DOM\n const existingScript = document.getElementById(SCRIPT_ID);\n if (existingScript) {\n isLoading = false;\n isLoaded = true;\n resolve();\n return;\n }\n\n // Determine script URL from webHost (with 30-min cache-bust so script is cached at most 30 min)\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n\n // Create and configure script element\n const script = document.createElement('script');\n script.id = SCRIPT_ID;\n script.src = scriptUrl;\n script.type = 'module';\n script.async = true;\n\n // Handle successful load\n script.onload = () => {\n isLoading = false;\n isLoaded = true;\n resolve();\n };\n\n // Handle load error\n script.onerror = (event) => {\n isLoading = false;\n loadError = new Error(\n `[Encatch] Failed to load SDK from ${scriptUrl}. ` +\n `Please check your network connection and web host configuration.`\n );\n console.error(loadError.message, event);\n reject(loadError);\n };\n\n // Inject script into document head\n const firstScript = document.getElementsByTagName('script')[0];\n if (firstScript && firstScript.parentNode) {\n firstScript.parentNode.insertBefore(script, firstScript);\n } else {\n document.head.appendChild(script);\n }\n });\n}\n\n/**\n * Check if the remote script has been loaded\n */\nexport function isScriptLoaded(): boolean {\n return isLoaded;\n}\n\n/**\n * Reset loader state (useful for testing)\n */\nexport function resetLoaderState(): void {\n isLoading = false;\n isLoaded = false;\n loadError = null;\n}\n\n/**\n * Get the default script URL (includes current 30-min cache-bust param)\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH + '?dt=' + getCacheBustParam();\n}\n","/**\n * Command Queue Implementation\n * \n * Manages the queue of SDK method calls that occur before the remote\n * implementation script has loaded. Commands are stored as tuples\n * and processed FIFO when the remote script becomes available.\n */\n\nimport type { Command, EncatchSDK } from './types';\n\n/**\n * Process all queued commands by calling the corresponding methods\n * on the SDK instance. This is called by the remote script once loaded.\n * \n * @param sdk - The SDK instance with real implementations\n * @param queue - Array of queued commands to process\n */\nexport function processQueue(sdk: EncatchSDK, queue: Command[]): void {\n while (queue.length > 0) {\n const command = queue.shift();\n if (!command) continue;\n\n const [method, ...args] = command;\n \n // Skip internal properties\n if (method.startsWith('_')) continue;\n\n // Get the method from the SDK\n const fn = sdk[method as keyof EncatchSDK];\n \n if (typeof fn === 'function') {\n try {\n (fn as (...args: unknown[]) => void).apply(sdk, args);\n } catch (error) {\n console.error(`[Encatch] Error processing queued command \"${method}\":`, error);\n }\n } else {\n console.warn(`[Encatch] Unknown method in queue: \"${method}\"`);\n }\n }\n}\n\n/**\n * Creates a stub method that queues calls for later processing\n * \n * @param queue - The command queue array\n * @param methodName - Name of the method being stubbed\n * @returns A function that pushes calls to the queue\n */\nexport function createQueuedMethod(\n queue: Command[],\n methodName: string\n): (...args: unknown[]) => void {\n return function (...args: unknown[]): void {\n queue.push([methodName, ...args]);\n };\n}\n\n/**\n * List of SDK methods that should be queued before initialization\n */\nexport const QUEUED_METHODS = [\n 'init',\n 'identifyUser',\n 'setLocale',\n 'setCountry',\n 'setTheme',\n 'trackEvent',\n 'trackScreen',\n 'startSession',\n 'resetUser',\n 'showForm',\n 'dismissForm',\n 'addToResponse',\n 'submitForm',\n 'emitEvent',\n] as const;\n\nexport type QueuedMethodName = typeof QUEUED_METHODS[number];\n","/**\n * Encatch Web SDK\n * \n * A lightweight, type-safe SDK for integrating Encatch forms and surveys.\n * This module creates the _encatch global object that queues commands\n * until the remote implementation script loads.\n */\n\nimport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n EventCallback,\n Command,\n} from './types';\nimport { loadRemoteScript } from './loader';\nimport { createQueuedMethod, QUEUED_METHODS } from './queue';\n\n// Re-export types for consumers\nexport type {\n EncatchSDK,\n EncatchConfig,\n UserTraits,\n IdentifyOptions,\n StartSessionOptions,\n EventType,\n EventCallback,\n EventPayload,\n Theme,\n ResetMode,\n ShowFormOptions,\n ShowFormInterceptorPayload,\n SubmitFormRequest,\n FormDetails,\n QuestionResponse,\n QuestionAnswer,\n RefineTextRequest,\n RefineTextResponse,\n} from './types';\n\n/**\n * Creates the Encatch SDK stub instance\n * All method calls are queued until setProject() is called and the\n * remote implementation script loads.\n */\nfunction createEncatchStub(): EncatchSDK {\n // Command queue for calls made before remote script loads\n const queue: Command[] = [];\n \n // Event callbacks - all callbacks receive all form events\n const eventCallbacks: EventCallback[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventCallbacks: eventCallbacks,\n _initialized: false,\n _apiKey: null,\n _config: {},\n\n // init is special - it triggers script loading\n init(apiKey: string, config?: EncatchConfig): void {\n if (sdk._initialized) {\n console.warn('[Encatch] SDK already initialized. Ignoring init call.');\n return;\n }\n\n sdk._apiKey = apiKey;\n sdk._config = config || {};\n sdk._initialized = true;\n\n // Queue this call for the remote implementation\n queue.push(['init', apiKey, config]);\n\n // Load the remote script\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n loadRemoteScript(sdk._config).catch((error) => {\n console.error('[Encatch] Failed to initialize SDK:', error);\n });\n }\n },\n\n // Event subscription - receives all form events\n on(callback: EventCallback): () => void {\n eventCallbacks.push(callback);\n\n // Return unsubscribe function\n return () => {\n const index = eventCallbacks.indexOf(callback);\n if (index > -1) {\n eventCallbacks.splice(index, 1);\n }\n };\n },\n\n // Stub implementations - will be replaced by remote script\n identifyUser: () => {},\n setLocale: () => {},\n setCountry: () => {},\n setTheme: () => {},\n trackEvent: () => {},\n trackScreen: () => {},\n startSession: () => {},\n resetUser: () => {},\n showForm: () => {},\n dismissForm: () => {},\n addToResponse: () => {},\n submitForm: () => {},\n emitEvent: () => {},\n refineText: () => Promise.resolve({}),\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on (handled locally)\n const methodsToQueue = QUEUED_METHODS.filter(m => m !== 'init');\n \n for (const method of methodsToQueue) {\n // Use type assertion to assign queued methods\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (sdk as any)[method] = createQueuedMethod(queue, method);\n }\n\n return sdk;\n}\n\n/**\n * Initialize the global _encatch object\n * This runs immediately when the script loads\n */\nfunction initGlobal(): EncatchSDK {\n // Check for existing instance (may have been created by snippet)\n if (typeof window !== 'undefined') {\n // If _encatch already exists with a queue, preserve it\n const existing = window._encatch;\n if (existing && Array.isArray(existing._q)) {\n // Merge existing queue into new instance\n const sdk = createEncatchStub();\n sdk._q.push(...existing._q);\n \n // Copy over any existing callbacks\n if (Array.isArray(existing._eventCallbacks)) {\n sdk._eventCallbacks.push(...existing._eventCallbacks);\n }\n \n // Copy initialization state\n if (existing._initialized) {\n sdk._initialized = existing._initialized;\n sdk._apiKey = existing._apiKey;\n sdk._config = existing._config || {};\n }\n \n window._encatch = sdk;\n return sdk;\n }\n\n // Create fresh instance\n const sdk = createEncatchStub();\n window._encatch = sdk;\n return sdk;\n }\n\n // Non-browser environment\n return createEncatchStub();\n}\n\n// Initialize and export\nexport const _encatch = initGlobal();\n\n// Default export for convenience\nexport default _encatch;\n"],"names":["SCRIPT_ID","isLoading","isLoaded","loadError","loadRemoteScript","config","Promise","resolve","reject","checkInterval","setInterval","clearInterval","document","getElementById","scriptUrl","webHost","d","Date","yy","String","getUTCFullYear","slice","mm","getUTCMonth","padStart","dd","getUTCDate","hh","getUTCHours","min30","Math","floor","getUTCMinutes","getCacheBustParam","script","createElement","id","src","type","async","onload","onerror","event","Error","console","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventCallbacks","sdk","_q","_eventCallbacks","_initialized","_apiKey","_config","init","apiKey","warn","window","catch","on","callback","index","indexOf","splice","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","dismissForm","addToResponse","submitForm","emitEvent","refineText","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"0BAUA,MAMMA,EAAY,qBAkBlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KAQvB,SAASC,EAAiBC,GAE/B,OAAIH,EACKI,QAAQC,UAIbJ,EACKG,QAAQE,OAAOL,GAIpBF,EACK,IAAIK,QAAQ,CAACC,EAASC,KAC3B,MAAMC,EAAgBC,YAAY,KAC5BR,GACFS,cAAcF,GACdF,KACSJ,IACTQ,cAAcF,GACdD,EAAOL,KAER,OAIPF,GAAY,EAEL,IAAIK,QAAQ,CAACC,EAASC,KAG3B,GADuBI,SAASC,eAAeb,GAK7C,OAHAC,GAAY,EACZC,GAAW,OACXK,IAKF,MACMO,GADUT,EAAOU,SAzEF,2BA0EHA,2BA9DtB,WACE,MAAMC,MAAQC,KACRC,EAAKC,OAAOH,EAAEI,kBAAkBC,OAAM,GACtCC,EAAKH,OAAOH,EAAEO,cAAgB,GAAGC,SAAS,EAAG,KAC7CC,EAAKN,OAAOH,EAAEU,cAAcF,SAAS,EAAG,KACxCG,EAAKR,OAAOH,EAAEY,eAAeJ,SAAS,EAAG,KACzCK,EAA6C,GAArCC,KAAKC,MAAMf,EAAEgB,gBAAkB,IAE7C,MAAO,GAAGd,IAAKI,IAAKG,IAAKE,IADVR,OAAOU,GAAOL,SAAS,EAAG,MAE3C,CAqD2DS,GAGjDC,EAAStB,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OACbC,aAAc,OACdC,UAAW,OACXC,SAAU,OACVC,YAAa,OACbC,cAAe,OACfC,WAAY,OACZC,UAAW,OACXC,WAAY,IAAMpF,QAAQC,QAAQ,CAAA,IAK9BoF,EAAiBjC,EAAekC,OAAOC,GAAW,SAANA,GAElD,IAAA,MAAWC,KAAUH,EAGlB9B,EAAYiC,GAAUzC,EAAmBC,EAAOwC,GAGnD,OAAOjC,CACT,CA2CO,MAAMkC,EArCb,WAEE,GAAsB,oBAAXzB,OAAwB,CAEjC,MAAM0B,EAAW1B,OAAOyB,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAASlC,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQuC,EAASlC,IAGpBmC,MAAMC,QAAQF,EAASjC,kBACzBF,EAAIE,gBAAgBN,QAAQuC,EAASjC,iBAInCiC,EAAShC,eACXH,EAAIG,aAAegC,EAAShC,aAC5BH,EAAII,QAAU+B,EAAS/B,QACvBJ,EAAIK,QAAU8B,EAAS9B,SAAW,CAAA,GAGpCI,OAAOyB,SAAWlC,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAW,OAAOyB,SAAWlC,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBwC"}
package/dist/index.d.ts CHANGED
@@ -25,6 +25,14 @@ export declare interface EncatchConfig {
25
25
  apiBaseUrl?: string;
26
26
  /** When true, displays the form inline at full height without modal overlay */
27
27
  isFullScreen?: boolean;
28
+ /**
29
+ * Optional interceptor called before any form is shown (manual or automatic).
30
+ * Receives the form configuration payload. If it returns false (or Promise<false>),
31
+ * the SDK will not display its built-in iframe form; the app can instead render a
32
+ * custom UI and use submitForm / emitEvent / refineText to complete the flow.
33
+ * Pending responses from addToResponse() are cleared when false is returned.
34
+ */
35
+ onBeforeShowForm?: (payload: ShowFormInterceptorPayload) => boolean | Promise<boolean>;
28
36
  }
29
37
 
30
38
  /**
@@ -94,11 +102,36 @@ export declare interface EncatchSDK {
94
102
  */
95
103
  dismissForm(formConfigurationId?: string): void;
96
104
  /**
97
- * Prepopulate a form response
98
- * @param questionId - The ID of the question to prepopulate
105
+ * Prepopulate a form response.
106
+ * @param questionId - The ID or slug of the question to prepopulate. When a slug
107
+ * is provided the form engine resolves it to the matching question ID automatically.
99
108
  * @param value - The value to set
100
109
  */
101
110
  addToResponse(questionId: string, value: unknown): void;
111
+ /**
112
+ * Manually submit a form to the Encatch API.
113
+ * Use this when onBeforeShowForm returns false and you render a custom UI —
114
+ * call submitForm once the user completes your custom form.
115
+ * @param params - Submission details including formConfigurationId and question responses
116
+ */
117
+ submitForm(params: SubmitFormRequest): void;
118
+ /**
119
+ * Emit a form lifecycle event to all on() subscribers.
120
+ * Use this when onBeforeShowForm returns false to mirror the events that the
121
+ * built-in iframe form would normally fire (e.g. form:show, form:started,
122
+ * form:answered, form:submit, form:complete, form:close).
123
+ * @param eventType - The event type to emit
124
+ * @param payload - Event payload (timestamp is added automatically)
125
+ */
126
+ emitEvent(eventType: EventType, payload: Omit<EventPayload, 'timestamp'>): void;
127
+ /**
128
+ * Request AI text refinement for a long-text answer.
129
+ * Use this when onBeforeShowForm returns false and your custom UI includes
130
+ * an AI-enhance feature.
131
+ * @param params - The question ID, form configuration ID, and user text to refine
132
+ * @returns Promise resolving to the refined text response
133
+ */
134
+ refineText(params: RefineTextRequest): Promise<RefineTextResponse>;
102
135
  /**
103
136
  * Subscribe to all form events
104
137
  * The callback receives all form events (show, submit, close, complete, error)
@@ -141,6 +174,26 @@ export declare interface EventPayload {
141
174
  */
142
175
  export declare type EventType = 'form:show' | 'form:started' | 'form:submit' | 'form:complete' | 'form:close' | 'form:dismissed' | 'form:error' | 'form:section:change' | 'form:answered';
143
176
 
177
+ /**
178
+ * Form details for a manual form submission
179
+ */
180
+ export declare interface FormDetails {
181
+ /** The server-issued configuration ID for this form */
182
+ formConfigurationId: string;
183
+ /** When true, marks this as a partial (mid-journey) submission */
184
+ isPartialSubmit?: boolean;
185
+ feedbackIdentifier?: string;
186
+ responseLanguageCode?: string;
187
+ response?: {
188
+ questions?: QuestionResponse[];
189
+ };
190
+ completionTimeInSeconds?: number;
191
+ /** Caller-provided metadata attached to this submission (Dates already serialized to ISO strings) */
192
+ context?: Record<string, string | number | boolean>;
193
+ /** IDs of questions the user actually visited, in order */
194
+ visitedQuestionIds?: string[];
195
+ }
196
+
144
197
  /**
145
198
  * Options for the identifyUser method
146
199
  */
@@ -153,6 +206,51 @@ export declare interface IdentifyOptions {
153
206
  secure?: SecureOptions;
154
207
  }
155
208
 
209
+ /**
210
+ * An individual question answer within a form submission
211
+ */
212
+ export declare interface QuestionAnswer {
213
+ nps?: number;
214
+ csat?: number;
215
+ starRating?: number;
216
+ singleChoice?: string;
217
+ singleChoiceOther?: string;
218
+ multipleChoiceMultiple?: string[];
219
+ multipleChoiceMultipleOther?: string;
220
+ nestedSelection?: string[];
221
+ shortAnswer?: string;
222
+ longText?: string;
223
+ }
224
+
225
+ /**
226
+ * A single question response within a form submission
227
+ */
228
+ export declare interface QuestionResponse {
229
+ questionId: string;
230
+ type?: string;
231
+ answer?: QuestionAnswer;
232
+ }
233
+
234
+ /**
235
+ * Parameters for the refineText AI enhancement endpoint
236
+ */
237
+ export declare interface RefineTextRequest {
238
+ questionId: string;
239
+ feedbackConfigurationId: string;
240
+ userText: string;
241
+ }
242
+
243
+ /**
244
+ * Response from the refineText endpoint
245
+ */
246
+ export declare interface RefineTextResponse {
247
+ message?: string;
248
+ refinedText?: string;
249
+ status?: number;
250
+ error?: string;
251
+ code?: string;
252
+ }
253
+
156
254
  /**
157
255
  * Reset mode for form data when showing a form
158
256
  * - 'always': Clear form data every time showForm is called (default)
@@ -171,6 +269,30 @@ declare interface SecureOptions {
171
269
  generatedDateTimeinUTC?: string;
172
270
  }
173
271
 
272
+ /**
273
+ * Payload passed to the onBeforeShowForm interceptor.
274
+ * Contains the full form configuration returned by the server along with
275
+ * context values the SDK resolved at call time.
276
+ */
277
+ export declare interface ShowFormInterceptorPayload {
278
+ /** The form slug or ID that was requested */
279
+ formId: string;
280
+ /** Raw form configuration returned by the show-form API */
281
+ formConfig: Record<string, unknown>;
282
+ /** Reset mode in effect for this show call */
283
+ resetMode: ResetMode;
284
+ /** Whether the form was triggered automatically (server-side) or manually (developer call) */
285
+ triggerType: 'automatic' | 'manual';
286
+ /** Pre-filled responses staged via addToResponse() */
287
+ prefillResponses: Record<string, unknown>;
288
+ /** Active locale, if set */
289
+ locale?: string;
290
+ /** Active theme */
291
+ theme?: Theme;
292
+ /** Serialized context values (Dates already converted to ISO strings) */
293
+ context?: Record<string, string | number | boolean>;
294
+ }
295
+
174
296
  /**
175
297
  * Options for the showForm method
176
298
  */
@@ -198,6 +320,14 @@ export declare interface StartSessionOptions {
198
320
  skipImmediateTrackScreen?: boolean;
199
321
  }
200
322
 
323
+ /**
324
+ * Parameters for manually submitting a form (used with onBeforeShowForm interceptor)
325
+ */
326
+ export declare interface SubmitFormRequest {
327
+ triggerType?: 'automatic' | 'manual';
328
+ formDetails: FormDetails;
329
+ }
330
+
201
331
  /**
202
332
  * Theme options
203
333
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@encatch/web-sdk",
3
- "version": "1.1.0-beta.0",
3
+ "version": "1.1.0-beta.1",
4
4
  "description": "A lightweight, type-safe JavaScript SDK for integrating Encatch forms and surveys",
5
5
  "type": "module",
6
6
  "main": "dist/encatch.es.js",