@encatch/web-sdk 1.0.0-beta.0 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- const e="encatch-sdk-script";let n=!1,t=!1,i=null;function o(e,n){return function(...t){e.push([n,...t])}}const r=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse"];function c(){const c=[],s=[],a={_q:c,_eventSubscriptions:s,_initialized:!1,_apiKey:null,_config:{},init(o,r){a._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(a._apiKey=o,a._config=r||{},a._initialized=!0,c.push(["init",o,r]),"undefined"!=typeof window&&"undefined"!=typeof document&&function(o){return t?Promise.resolve():i?Promise.reject(i):n?new Promise((e,n)=>{const o=setInterval(()=>{t?(clearInterval(o),e()):i&&(clearInterval(o),n(i))},50)}):(n=!0,new Promise((r,c)=>{if(document.getElementById(e))return n=!1,t=!0,void r();const s=(o.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js",a=document.createElement("script");a.id=e,a.src=s,a.type="module",a.async=!0,a.onload=()=>{n=!1,t=!0,r()},a.onerror=e=>{n=!1,i=new Error(`[Encatch] Failed to load SDK from ${s}. Please check your network connection and web host configuration.`),console.error(i.message,e),c(i)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(a,d):document.head.appendChild(a)}))}(a._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on(e,n){const t={event:e,callback:n};return s.push(t),()=>{const e=s.indexOf(t);e>-1&&s.splice(e,1)}},off(e,n){const t=s.findIndex(t=>t.event===e&&t.callback===n);t>-1&&s.splice(t,1)},identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},addToResponse:()=>{}},d=r.filter(e=>"init"!==e);for(const e of d)a[e]=o(c,e);return a}const s=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const n=c();return n._q.push(...e._q),Array.isArray(e._eventSubscriptions)&&n._eventSubscriptions.push(...e._eventSubscriptions),e._initialized&&(n._initialized=e._initialized,n._apiKey=e._apiKey,n._config=e._config||{}),window._encatch=n,n}const n=c();return window._encatch=n,n}return c()}();export{s as _encatch,s as default};
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,a)=>{if(document.getElementById(e))return t=!1,n=!0,void r();const c=(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")}`}(),s=document.createElement("script");s.id=e,s.src=c,s.type="module",s.async=!0,s.onload=()=>{t=!1,n=!0,r()},s.onerror=e=>{t=!1,i=new Error(`[Encatch] Failed to load SDK from ${c}. Please check your network connection and web host configuration.`),console.error(i.message,e),a(i)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(s,d):document.head.appendChild(s)}))}function r(e,t){return function(...n){e.push([t,...n])}}const a=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse"];function c(){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:()=>{},addToResponse:()=>{}},i=a.filter(e=>"init"!==e);for(const o of i)n[o]=r(e,o);return n}const s=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const t=c();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=c();return window._encatch=t,t}return c()}();export{s as _encatch,s 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/** 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\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH;\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\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH;\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 '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 EventType,\n EventCallback,\n EventSubscription,\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 EventType,\n EventCallback,\n EventPayload,\n Theme,\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 subscriptions\n const eventSubscriptions: EventSubscription[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventSubscriptions: eventSubscriptions,\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 - handled locally, persists across script load\n on(event: EventType, callback: EventCallback): () => void {\n const subscription: EventSubscription = { event, callback };\n eventSubscriptions.push(subscription);\n\n // Return unsubscribe function\n return () => {\n const index = eventSubscriptions.indexOf(subscription);\n if (index > -1) {\n eventSubscriptions.splice(index, 1);\n }\n };\n },\n\n // Event unsubscription\n off(event: EventType, callback: EventCallback): void {\n const index = eventSubscriptions.findIndex(\n (sub) => sub.event === event && sub.callback === callback\n );\n if (index > -1) {\n eventSubscriptions.splice(index, 1);\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 addToResponse: () => {},\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on/off (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 subscriptions\n if (Array.isArray(existing._eventSubscriptions)) {\n sdk._eventSubscriptions.push(...existing._eventSubscriptions);\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","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventSubscriptions","sdk","_q","_eventSubscriptions","_initialized","_apiKey","_config","init","apiKey","config","console","warn","window","document","Promise","resolve","reject","checkInterval","setInterval","clearInterval","getElementById","scriptUrl","webHost","script","createElement","id","src","type","async","onload","onerror","event","Error","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","loadRemoteScript","catch","on","callback","subscription","index","indexOf","splice","off","findIndex","sub","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"AAUA,MAMMA,EAAY,qBAGlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KC4BvB,SAASC,EACdC,EACAC,GAEA,OAAO,YAAaC,GAClBF,EAAMG,KAAK,CAACF,KAAeC,GAC7B,CACF,CAKO,MAAME,EAAiB,CAC5B,OACA,eACA,Y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ue.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 '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 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 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","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,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K,QAAU7D,GAAU,CAAA,EACxBwD,EAAIG,cAAe,EAGnBV,EAAMG,KAAK,CAAC,OAAQW,EAAQ/D,IAGN,oBAAXiE,QAA8C,oBAAb1D,UAC1CR,EAAiByD,EAAIK,SAASK,MAAO1B,IACnCD,QAAQC,MAAM,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,cAAe,QAKXC,EAAiB7B,EAAe8B,OAAOC,GAAW,SAANA,GAElD,IAAA,MAAWC,KAAUH,EAGlB1B,EAAY6B,GAAUrC,EAAmBC,EAAOoC,GAGnD,OAAO7B,CACT,CA2CO,MAAM8B,EArCb,WAEE,GAAsB,oBAAXrB,OAAwB,CAEjC,MAAMsB,EAAWtB,OAAOqB,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAAS9B,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQmC,EAAS9B,IAGpB+B,MAAMC,QAAQF,EAAS7B,kBACzBF,EAAIE,gBAAgBN,QAAQmC,EAAS7B,iBAInC6B,EAAS5B,eACXH,EAAIG,aAAe4B,EAAS5B,aAC5BH,EAAII,QAAU2B,EAAS3B,QACvBJ,EAAIK,QAAU0B,EAAS1B,SAAW,CAAA,GAGpCI,OAAOqB,SAAW9B,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAW,OAAOqB,SAAW9B,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBoC"}
@@ -1,2 +1,2 @@
1
- !function(e){"use strict";const n="encatch-sdk-script";let t=!1,i=!1,o=null;function c(e,n){return function(...t){e.push([n,...t])}}const r=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse"];function s(){const e=[],s=[],a={_q:e,_eventSubscriptions:s,_initialized:!1,_apiKey:null,_config:{},init(c,r){a._initialized?console.warn("[Encatch] SDK already initialized. Ignoring init call."):(a._apiKey=c,a._config=r||{},a._initialized=!0,e.push(["init",c,r]),"undefined"!=typeof window&&"undefined"!=typeof document&&function(e){return i?Promise.resolve():o?Promise.reject(o):t?new Promise((e,n)=>{const t=setInterval(()=>{i?(clearInterval(t),e()):o&&(clearInterval(t),n(o))},50)}):(t=!0,new Promise((c,r)=>{if(document.getElementById(n))return t=!1,i=!0,void c();const s=(e.webHost||"https://app.encatch.com")+"/s/sdk/v1/encatch.js",a=document.createElement("script");a.id=n,a.src=s,a.type="module",a.async=!0,a.onload=()=>{t=!1,i=!0,c()},a.onerror=e=>{t=!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),r(o)};const d=document.getElementsByTagName("script")[0];d&&d.parentNode?d.parentNode.insertBefore(a,d):document.head.appendChild(a)}))}(a._config).catch(e=>{console.error("[Encatch] Failed to initialize SDK:",e)}))},on(e,n){const t={event:e,callback:n};return s.push(t),()=>{const e=s.indexOf(t);e>-1&&s.splice(e,1)}},off(e,n){const t=s.findIndex(t=>t.event===e&&t.callback===n);t>-1&&s.splice(t,1)},identifyUser:()=>{},setLocale:()=>{},setCountry:()=>{},setTheme:()=>{},trackEvent:()=>{},trackScreen:()=>{},startSession:()=>{},resetUser:()=>{},showForm:()=>{},addToResponse:()=>{}},d=r.filter(e=>"init"!==e);for(const n of d)a[n]=c(e,n);return a}const a=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const n=s();return n._q.push(...e._q),Array.isArray(e._eventSubscriptions)&&n._eventSubscriptions.push(...e._eventSubscriptions),e._initialized&&(n._initialized=e._initialized,n._apiKey=e._apiKey,n._config=e._config||{}),window._encatch=n,n}const n=s();return window._encatch=n,n}return s()}();e._encatch=a,e.default=a,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,c)=>{if(document.getElementById(t))return n=!1,i=!0,void r();const a=(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")}`}(),s=document.createElement("script");s.id=t,s.src=a,s.type="module",s.async=!0,s.onload=()=>{n=!1,i=!0,r()},s.onerror=e=>{n=!1,o=new Error(`[Encatch] Failed to load SDK from ${a}. Please check your network connection and web host configuration.`),console.error(o.message,e),c(o)};const l=document.getElementsByTagName("script")[0];l&&l.parentNode?l.parentNode.insertBefore(s,l):document.head.appendChild(s)}))}function c(e,t){return function(...n){e.push([t,...n])}}const a=["init","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse"];function s(){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:()=>{},addToResponse:()=>{}},i=a.filter(e=>"init"!==e);for(const o of i)n[o]=c(e,o);return n}const l=function(){if("undefined"!=typeof window){const e=window._encatch;if(e&&Array.isArray(e._q)){const t=s();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=s();return window._encatch=t,t}return s()}();e._encatch=l,e.default=l,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/** 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\n const webHost = config.webHost || DEFAULT_WEB_HOST;\n const scriptUrl = webHost + SDK_SCRIPT_PATH;\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\n */\nexport function getDefaultScriptUrl(): string {\n return DEFAULT_WEB_HOST + SDK_SCRIPT_PATH;\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 '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 EventType,\n EventCallback,\n EventSubscription,\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 EventType,\n EventCallback,\n EventPayload,\n Theme,\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 subscriptions\n const eventSubscriptions: EventSubscription[] = [];\n\n // Create the SDK object\n const sdk: EncatchSDK = {\n // Internal state\n _q: queue,\n _eventSubscriptions: eventSubscriptions,\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 - handled locally, persists across script load\n on(event: EventType, callback: EventCallback): () => void {\n const subscription: EventSubscription = { event, callback };\n eventSubscriptions.push(subscription);\n\n // Return unsubscribe function\n return () => {\n const index = eventSubscriptions.indexOf(subscription);\n if (index > -1) {\n eventSubscriptions.splice(index, 1);\n }\n };\n },\n\n // Event unsubscription\n off(event: EventType, callback: EventCallback): void {\n const index = eventSubscriptions.findIndex(\n (sub) => sub.event === event && sub.callback === callback\n );\n if (index > -1) {\n eventSubscriptions.splice(index, 1);\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 addToResponse: () => {},\n };\n\n // Replace stub methods with queue-based versions\n // Skip init (handled specially above) and on/off (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 subscriptions\n if (Array.isArray(existing._eventSubscriptions)) {\n sdk._eventSubscriptions.push(...existing._eventSubscriptions);\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","createQueuedMethod","queue","methodName","args","push","QUEUED_METHODS","createEncatchStub","eventSubscriptions","sdk","_q","_eventSubscriptions","_initialized","_apiKey","_config","init","apiKey","config","console","warn","window","document","Promise","resolve","reject","checkInterval","setInterval","clearInterval","getElementById","scriptUrl","webHost","script","createElement","id","src","type","async","onload","onerror","event","Error","error","message","firstScript","getElementsByTagName","parentNode","insertBefore","head","appendChild","loadRemoteScript","catch","on","callback","subscription","index","indexOf","splice","off","findIndex","sub","identifyUser","setLocale","setCountry","setTheme","trackEvent","trackScreen","startSession","resetUser","showForm","addToResponse","methodsToQueue","filter","m","method","_encatch","existing","Array","isArray","initGlobal"],"mappings":"0BAUA,MAMMA,EAAY,qBAGlB,IAAIC,GAAY,EACZC,GAAW,EACXC,EAA0B,KC4BvB,SAASC,EACdC,EACAC,GAEA,OAAO,YAAaC,GAClBF,EAAMG,KAAK,CAACF,KAAeC,GAC7B,CACF,CAKO,MAAME,EAAiB,CAC5B,OACA,eACA,YACA,aACA,WACA,aACA,cACA,eACA,YACA,WACA,iBClCF,SAASC,IAEP,MAAML,EAAmB,GAGnBM,EAA0C,GAG1CC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,CAAEd,QAAOa,YAIjD,OAHA5C,EAAmBH,KAAKgD,GAGjB,KACL,MAAMC,EAAQ9C,EAAmB+C,QAAQF,GACrCC,GAAQ,GACV9C,EAAmBgD,OAAOF,EAAO,GAGvC,EAGA,GAAAG,CAAIlB,EAAkBa,GACpB,MAAME,EAAQ9C,EAAmBkD,UAC9BC,GAAQA,EAAIpB,QAAUA,GAASoB,EAAIP,WAAaA,GAE/CE,GAAQ,GACV9C,EAAmBgD,OAAOF,EAAO,EAErC,EAGAM,aAAc,OACdC,UAAW,OACXC,WAAY,OACZC,SAAU,OACVC,WAAY,OACZC,YAAa,OACbC,aAAc,OACdC,UAAW,OACXC,SAAU,OACVC,cAAe,QAKXC,EAAiBhE,EAAeiE,OAAOC,GAAW,SAANA,GAElD,IAAA,MAAWC,KAAUH,EAGlB7D,EAAYgE,GAAUxE,EAAmBC,EAAOuE,GAGnD,OAAOhE,CACT,CA2CO,MAAMiE,EArCb,WAEE,GAAsB,oBAAXtD,OAAwB,CAEjC,MAAMuD,EAAWvD,OAAOsD,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAASjE,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQsE,EAASjE,IAGpBkE,MAAMC,QAAQF,EAAShE,sBACzBF,EAAIE,oBAAoBN,QAAQsE,EAAShE,qBAIvCgE,EAAS/D,eACXH,EAAIG,aAAe+D,EAAS/D,aAC5BH,EAAII,QAAU8D,EAAS9D,QACvBJ,EAAIK,QAAU6D,EAAS7D,SAAW,CAAA,GAGpCM,OAAOsD,SAAWjE,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAa,OAAOsD,SAAWjE,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBuE"}
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 '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 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 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","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,G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GN,oBAAXiE,QAA8C,oBAAb1D,UAC1CR,EAAiByD,EAAIK,SAASK,MAAO1B,IACnCD,QAAQC,MAAM,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,cAAe,QAKXC,EAAiB7B,EAAe8B,OAAOC,GAAW,SAANA,GAElD,IAAA,MAAWC,KAAUH,EAGlB1B,EAAY6B,GAAUrC,EAAmBC,EAAOoC,GAGnD,OAAO7B,CACT,CA2CO,MAAM8B,EArCb,WAEE,GAAsB,oBAAXrB,OAAwB,CAEjC,MAAMsB,EAAWtB,OAAOqB,SACxB,GAAIC,GAAYC,MAAMC,QAAQF,EAAS9B,IAAK,CAE1C,MAAMD,EAAMF,IAgBZ,OAfAE,EAAIC,GAAGL,QAAQmC,EAAS9B,IAGpB+B,MAAMC,QAAQF,EAAS7B,kBACzBF,EAAIE,gBAAgBN,QAAQmC,EAAS7B,iBAInC6B,EAAS5B,eACXH,EAAIG,aAAe4B,EAAS5B,aAC5BH,EAAII,QAAU2B,EAAS3B,QACvBJ,EAAIK,QAAU0B,EAAS1B,SAAW,CAAA,GAGpCI,OAAOqB,SAAW9B,EACXA,CACT,CAGA,MAAMA,EAAMF,IAEZ,OADAW,OAAOqB,SAAW9B,EACXA,CACT,CAGA,OAAOF,GACT,CAGwBoC"}
package/dist/index.d.ts CHANGED
@@ -77,9 +77,9 @@ export declare interface EncatchSDK {
77
77
  /**
78
78
  * Show a specific form by ID
79
79
  * @param formId - The ID of the form to display
80
- * @param force - Force show even if already shown (optional)
80
+ * @param options - Optional settings for form display behavior
81
81
  */
82
- showForm(formId: string, force?: boolean): void;
82
+ showForm(formId: string, options?: ShowFormOptions): void;
83
83
  /**
84
84
  * Prepopulate a form response
85
85
  * @param questionId - The ID of the question to prepopulate
@@ -87,22 +87,16 @@ export declare interface EncatchSDK {
87
87
  */
88
88
  addToResponse(questionId: string, value: unknown): void;
89
89
  /**
90
- * Subscribe to SDK events
91
- * @param event - The event type to listen for
92
- * @param callback - Function to call when event occurs
90
+ * Subscribe to all form events
91
+ * The callback receives all form events (show, submit, close, complete, error)
92
+ * @param callback - Function to call when any form event occurs
93
93
  * @returns Unsubscribe function
94
94
  */
95
- on(event: EventType, callback: EventCallback): () => void;
96
- /**
97
- * Unsubscribe from SDK events
98
- * @param event - The event type to stop listening for
99
- * @param callback - The callback to remove
100
- */
101
- off(event: EventType, callback: EventCallback): void;
95
+ on(callback: EventCallback): () => void;
102
96
  /** Internal: Command queue for calls made before script loads */
103
97
  _q: Command[];
104
- /** Internal: Event subscriptions */
105
- _eventSubscriptions: EventSubscription[];
98
+ /** Internal: Event callbacks */
99
+ _eventCallbacks: EventCallback[];
106
100
  /** Internal: Whether the SDK has been initialized */
107
101
  _initialized: boolean;
108
102
  /** Internal: The API key */
@@ -113,8 +107,9 @@ export declare interface EncatchSDK {
113
107
 
114
108
  /**
115
109
  * Event callback function type
110
+ * Receives all form events with the event type and payload
116
111
  */
117
- export declare type EventCallback = (payload: EventPayload) => void;
112
+ export declare type EventCallback = (eventType: EventType, payload: EventPayload) => void;
118
113
 
119
114
  /**
120
115
  * Event payload structure
@@ -128,18 +123,10 @@ export declare interface EventPayload {
128
123
  data?: Record<string, unknown>;
129
124
  }
130
125
 
131
- /**
132
- * Event subscription entry
133
- */
134
- declare interface EventSubscription {
135
- event: EventType;
136
- callback: EventCallback;
137
- }
138
-
139
126
  /**
140
127
  * Event types that can be subscribed to
141
128
  */
142
- export declare type EventType = 'form:show' | 'form:submit' | 'form:close' | 'form:complete' | 'form:error';
129
+ export declare type EventType = 'form:show' | 'form:started' | 'form:submit' | 'form:complete' | 'form:close' | 'form:dismissed' | 'form:error' | 'form:section:change' | 'form:question:answered';
143
130
 
144
131
  /**
145
132
  * Options for the identifyUser method
@@ -153,6 +140,14 @@ export declare interface IdentifyOptions {
153
140
  secure?: SecureOptions;
154
141
  }
155
142
 
143
+ /**
144
+ * Reset mode for form data when showing a form
145
+ * - 'always': Clear form data every time showForm is called (default)
146
+ * - 'on-complete': Clear form data only if form was previously completed
147
+ * - 'never': Never clear form data (preserve user's previous answers)
148
+ */
149
+ export declare type ResetMode = 'always' | 'on-complete' | 'never';
150
+
156
151
  /**
157
152
  * Secure options for user identification
158
153
  */
@@ -163,6 +158,17 @@ declare interface SecureOptions {
163
158
  generatedDateTimeinUTC?: string;
164
159
  }
165
160
 
161
+ /**
162
+ * Options for the showForm method
163
+ */
164
+ export declare interface ShowFormOptions {
165
+ /**
166
+ * Controls when form data should be cleared
167
+ * @default 'always'
168
+ */
169
+ reset?: ResetMode;
170
+ }
171
+
166
172
  /**
167
173
  * Theme options
168
174
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@encatch/web-sdk",
3
- "version": "1.0.0-beta.0",
3
+ "version": "1.0.0-beta.2",
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",