@copilotkit/shared 0.0.0-max-changeset-20260109200053 → 0.0.0-max-umd-20260122170341
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -2
- package/dist/{chunk-5YXKLIUO.mjs → chunk-2PLJOEA7.mjs} +2 -2
- package/dist/chunk-2PLJOEA7.mjs.map +1 -0
- package/dist/{chunk-NBLG4PC5.mjs → chunk-5PU4VGVJ.mjs} +2 -2
- package/dist/{chunk-WUPFNPXO.mjs → chunk-FIY4J3HK.mjs} +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -3
- package/dist/index.umd.js +2 -0
- package/dist/index.umd.js.map +1 -0
- package/dist/telemetry/index.js +1 -1
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/index.mjs +2 -2
- package/dist/telemetry/scarf-client.js +1 -1
- package/dist/telemetry/scarf-client.js.map +1 -1
- package/dist/telemetry/scarf-client.mjs +1 -1
- package/dist/telemetry/telemetry-client.js +1 -1
- package/dist/telemetry/telemetry-client.js.map +1 -1
- package/dist/telemetry/telemetry-client.mjs +2 -2
- package/dist/utils/errors.js +1 -1
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/errors.mjs +3 -3
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +3 -3
- package/package.json +8 -5
- package/rollup.config.mjs +41 -0
- package/dist/chunk-5YXKLIUO.mjs.map +0 -1
- /package/dist/{chunk-NBLG4PC5.mjs.map → chunk-5PU4VGVJ.mjs.map} +0 -0
- /package/dist/{chunk-WUPFNPXO.mjs.map → chunk-FIY4J3HK.mjs.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("graphql"),require("uuid"),require("zod")):"function"==typeof define&&define.amd?define(["exports","graphql","uuid","zod"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CopilotKitShared={},e.GraphQL,e.UUID,e.Zod)}(this,function(e,t,r,n){"use strict";function o(e,t){var r,n=e.path?(r=t,e.path.split(".").reduce(function(e,t){return null==e?void 0:e[t]},r)):t;switch(e.rule){case"AND":return e.conditions.every(function(e){return o(e,t)});case"OR":return e.conditions.some(function(e){return o(e,t)});case"NOT":return!e.conditions.every(function(e){return o(e,t)});case"EQUALS":return n===e.value;case"NOT_EQUALS":return n!==e.value;case"GREATER_THAN":return n>e.value;case"LESS_THAN":return n<e.value;case"CONTAINS":return Array.isArray(n)&&n.includes(e.value);case"NOT_CONTAINS":return Array.isArray(n)&&!n.includes(e.value);case"MATCHES":return new RegExp(e.value).test(String(n));case"STARTS_WITH":return String(n).startsWith(e.value);case"ENDS_WITH":return String(n).endsWith(e.value);case"EXISTS":return null!=n;case"NOT_EXISTS":return null==n}}var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},i(e,t)};function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var a=function(){return a=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},a.apply(this,arguments)};function c(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})}function u(e,t){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function l(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var h={primary:"#007acc",success:"#22c55e",feature:"#a855f7",cta:"#ef4444",info:"#06b6d4",inherit:"inherit",warning:"#f59e0b"},d={header:"color: ".concat(h.warning,"; font-weight: bold; font-size: 16px;"),section:"color: ".concat(h.success,"; font-weight: bold;"),highlight:"color: ".concat(h.feature,"; font-weight: bold;"),cta:"color: ".concat(h.success,"; font-weight: bold;"),info:"color: ".concat(h.info,"; font-weight: bold;"),link:"color: ".concat(h.primary,"; text-decoration: underline;"),body:"color: ".concat(h.inherit,";"),warning:"color: ".concat(h.cta,"; font-weight: bold;")};function p(){console.log("%cCopilotKit Warning%c\n\nuseCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. To enable this premium feature, add your public license key, available for free at:\n\n%chttps://cloud.copilotkit.ai%c\n\nAlternatively, useCopilotChat is available for basic programmatic control, and does not require an API key.\n\nTo learn more about premium features, read the documentation here:\n\n%chttps://docs.copilotkit.ai/premium%c",d.header,d.body,d.cta,d.body,d.link,d.body)}function f(e){console.log("\n%cCopilotKit Warning%c \n\nIn order to use ".concat(e,", you need to add your CopilotKit API key, available for free at https://cloud.copilotkit.ai.\n ").trim(),d.header,d.body)}function g(e,t){console.log.apply(console,l([e],t,!1))}var m,y,v,b={success:function(e){return g("%c✅ ".concat(e),[d.section])},info:function(e){return g("%cℹ️ ".concat(e),[d.info])},feature:function(e){return g("%c✨ ".concat(e),[d.highlight])},cta:function(e){return g("%c🚀 ".concat(e),[d.cta])},logCopilotKitPlatformMessage:p,publicApiKeyRequired:f};e.Severity=void 0,(y=e.Severity||(e.Severity={})).CRITICAL="critical",y.WARNING="warning",y.INFO="info",e.ErrorVisibility=void 0,(v=e.ErrorVisibility||(e.ErrorVisibility={})).BANNER="banner",v.TOAST="toast",v.SILENT="silent",v.DEV_ONLY="dev_only";var E,_={COPILOT_ERROR:"CopilotError",COPILOT_API_DISCOVERY_ERROR:"CopilotApiDiscoveryError",COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR:"CopilotKitRemoteEndpointDiscoveryError",COPILOT_KIT_AGENT_DISCOVERY_ERROR:"CopilotKitAgentDiscoveryError",COPILOT_KIT_LOW_LEVEL_ERROR:"CopilotKitLowLevelError",COPILOT_KIT_VERSION_MISMATCH_ERROR:"CopilotKitVersionMismatchError",RESOLVED_COPILOT_KIT_ERROR:"ResolvedCopilotKitError",CONFIGURATION_ERROR:"ConfigurationError",MISSING_PUBLIC_API_KEY_ERROR:"MissingPublicApiKeyError",UPGRADE_REQUIRED_ERROR:"UpgradeRequiredError"},w=[_.CONFIGURATION_ERROR,_.MISSING_PUBLIC_API_KEY_ERROR,_.UPGRADE_REQUIRED_ERROR,_.COPILOT_API_DISCOVERY_ERROR,_.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,_.COPILOT_KIT_AGENT_DISCOVERY_ERROR],R=w;e.CopilotKitErrorCode=void 0,(E=e.CopilotKitErrorCode||(e.CopilotKitErrorCode={})).NETWORK_ERROR="NETWORK_ERROR",E.NOT_FOUND="NOT_FOUND",E.AGENT_NOT_FOUND="AGENT_NOT_FOUND",E.API_NOT_FOUND="API_NOT_FOUND",E.REMOTE_ENDPOINT_NOT_FOUND="REMOTE_ENDPOINT_NOT_FOUND",E.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",E.MISUSE="MISUSE",E.UNKNOWN="UNKNOWN",E.VERSION_MISMATCH="VERSION_MISMATCH",E.CONFIGURATION_ERROR="CONFIGURATION_ERROR",E.MISSING_PUBLIC_API_KEY_ERROR="MISSING_PUBLIC_API_KEY_ERROR",E.UPGRADE_REQUIRED_ERROR="UPGRADE_REQUIRED_ERROR";var O="https://docs.copilotkit.ai",C=function(e){return"See more: [".concat(e,"](").concat(e,")")},I=((m={})[e.CopilotKitErrorCode.NETWORK_ERROR]={statusCode:503,troubleshootingUrl:"".concat(O,"/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found"),visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},m[e.CopilotKitErrorCode.NOT_FOUND]={statusCode:404,troubleshootingUrl:"".concat(O,"/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found"),visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},m[e.CopilotKitErrorCode.AGENT_NOT_FOUND]={statusCode:500,troubleshootingUrl:"".concat(O,"/coagents/troubleshooting/common-issues#i-am-getting-agent-not-found-error"),visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},m[e.CopilotKitErrorCode.API_NOT_FOUND]={statusCode:404,troubleshootingUrl:"".concat(O,"/troubleshooting/common-issues#i-am-getting-a-network-errors--api-not-found"),visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},m[e.CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]={statusCode:404,troubleshootingUrl:"".concat(O,"/troubleshooting/common-issues#i-am-getting-copilotkits-remote-endpoint-not-found-error"),visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},m[e.CopilotKitErrorCode.AUTHENTICATION_ERROR]={statusCode:401,troubleshootingUrl:"".concat(O,"/troubleshooting/common-issues#authentication-errors"),visibility:e.ErrorVisibility.BANNER,severity:e.Severity.CRITICAL},m[e.CopilotKitErrorCode.MISUSE]={statusCode:400,troubleshootingUrl:null,visibility:e.ErrorVisibility.DEV_ONLY,severity:e.Severity.WARNING},m[e.CopilotKitErrorCode.UNKNOWN]={statusCode:500,visibility:e.ErrorVisibility.TOAST,severity:e.Severity.CRITICAL},m[e.CopilotKitErrorCode.CONFIGURATION_ERROR]={statusCode:400,troubleshootingUrl:null,severity:e.Severity.WARNING,visibility:e.ErrorVisibility.BANNER},m[e.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]={statusCode:400,troubleshootingUrl:null,severity:e.Severity.CRITICAL,visibility:e.ErrorVisibility.BANNER},m[e.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]={statusCode:402,troubleshootingUrl:null,severity:e.Severity.WARNING,visibility:e.ErrorVisibility.BANNER},m[e.CopilotKitErrorCode.VERSION_MISMATCH]={statusCode:400,troubleshootingUrl:null,visibility:e.ErrorVisibility.DEV_ONLY,severity:e.Severity.INFO},m),S=function(t){function r(r){var n,o=r.message,i=void 0===o?"Unknown error occurred":o,s=r.code,a=r.severity,c=r.visibility,u=this,l=_.COPILOT_ERROR,h=I[s],d=h.statusCode,p=null!==(n=null!=c?c:h.visibility)&&void 0!==n?n:e.ErrorVisibility.TOAST,f=null!=a?a:"severity"in h?h.severity:void 0;return(u=t.call(this,i,{extensions:{name:l,statusCode:d,code:s,visibility:p,severity:f,troubleshootingUrl:"troubleshootingUrl"in h?h.troubleshootingUrl:null,originalError:{message:i,stack:(new Error).stack}}})||this).code=s,u.name=l,u.statusCode=d,u.severity=f,u.visibility=p,u}return s(r,t),r}(t.GraphQLError),T=function(t){function r(r){var n=r.message,o=r.code,i=void 0===o?e.CopilotKitErrorCode.MISUSE:o,s=this,a="troubleshootingUrl"in I[i]&&I[i].troubleshootingUrl?C(I[i].troubleshootingUrl):null,c=a?"".concat(n,".\n\n").concat(a):n;return(s=t.call(this,{message:c,code:i})||this).name=_.COPILOT_API_DISCOVERY_ERROR,s}return s(r,t),r}(S),A=function(e){var t=e.reactCoreVersion,r=e.runtimeVersion,n=e.runtimeClientGqlVersion;return"Version mismatch detected: @copilotkit/runtime@".concat(null!=r?r:""," is not compatible with @copilotkit/react-core@").concat(t," and @copilotkit/runtime-client-gql@").concat(n,". Please ensure all installed copilotkit packages are on the same version.")},k=function(t){function r(r){var n=r.reactCoreVersion,o=r.runtimeVersion,i=r.runtimeClientGqlVersion,s=this,a=e.CopilotKitErrorCode.VERSION_MISMATCH;return(s=t.call(this,{message:A({reactCoreVersion:n,runtimeVersion:o,runtimeClientGqlVersion:i}),code:a})||this).name=_.COPILOT_KIT_VERSION_MISMATCH_ERROR,s}return s(r,t),r}(S),P=function(t){function r(r){void 0===r&&(r={});var n,o,i,s=this,a=null!==(n=r.url)&&void 0!==n?n:"",c="";(null==a?void 0:a.includes("/info"))?c="when fetching CopilotKit info":a.includes("/actions/execute")?c="when attempting to execute actions.":a.includes("/agents/state")?c="when attempting to get agent state.":a.includes("/agents/execute")&&(c="when attempting to execute agent(s).");var u=null!==(o=r.message)&&void 0!==o?o:r.url?"Failed to find CopilotKit API endpoint at url ".concat(r.url," ").concat(c):"Failed to find CopilotKit API endpoint.",l=null!==(i=r.code)&&void 0!==i?i:e.CopilotKitErrorCode.API_NOT_FOUND,h="".concat(u,".\n\n").concat(C(I[l].troubleshootingUrl));return(s=t.call(this,{message:h,code:l})||this).name=_.COPILOT_API_DISCOVERY_ERROR,s}return s(r,t),r}(S),N=function(t){function r(r){var n,o=this,i=null!==(n=null==r?void 0:r.message)&&void 0!==n?n:(null==r?void 0:r.url)?"Failed to find or contact remote endpoint at url ".concat(r.url):"Failed to find or contact remote endpoint",s=e.CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;return(o=t.call(this,{message:i,code:s})||this).name=_.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,o}return s(r,t),r}(P),x=function(t){function r(r){var n,o=this,i=r.agentName,s=r.availableAgents,a=e.CopilotKitErrorCode.AGENT_NOT_FOUND,c=C(I[a].troubleshootingUrl);if(s.length){var u=s.map(function(e){return e.name}).join(", ");n=i?"Agent '".concat(i,"' was not found. Available agents are: ").concat(u,". Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n").concat(c):"The requested agent was not found. Available agents are: ".concat(u,". Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n").concat(c)}else n="".concat(i?"Agent '".concat(i,"'"):"The requested agent"," was not found. Please set up at least one agent before proceeding. ").concat(c);return(o=t.call(this,{message:n,code:a})||this).name=_.COPILOT_KIT_AGENT_DISCOVERY_ERROR,o}return s(r,t),r}(S),D=function(t){function r(r){var n=r.error,o=r.url,i=r.message,s=this,a=e.CopilotKitErrorCode.NETWORK_ERROR,c=n.code,u=null!=i?i:H({errorCode:c,url:o});return(s=t.call(this,{message:u,code:a})||this).name=_.COPILOT_KIT_LOW_LEVEL_ERROR,s}return s(r,t),r}(S),K=function(t){function r(r){var n=r.status,o=r.message,i=r.code,s=r.isRemoteEndpoint,a=r.url,c=this,u=i;if(!u)switch(n){case 400:throw new P({message:o,url:a});case 404:throw s?new N({message:o,url:a}):new P({message:o,url:a});default:u=e.CopilotKitErrorCode.UNKNOWN}return(c=t.call(this,{message:o,code:u})||this).name=_.RESOLVED_COPILOT_KIT_ERROR,c}return s(r,t),r}(S),M=function(t){function r(r){var n=t.call(this,{message:r,code:e.CopilotKitErrorCode.CONFIGURATION_ERROR})||this;return n.name=_.CONFIGURATION_ERROR,n.severity=e.Severity.WARNING,n}return s(r,t),r}(S),j=function(t){function r(r){var n=t.call(this,r)||this;return n.name=_.MISSING_PUBLIC_API_KEY_ERROR,n.severity=e.Severity.CRITICAL,n}return s(r,t),r}(M),U=function(t){function r(r){var n=t.call(this,r)||this;return n.name=_.UPGRADE_REQUIRED_ERROR,n.severity=e.Severity.WARNING,n}return s(r,t),r}(M);function L(e){var t;return e instanceof S||e instanceof D||(null==e?void 0:e.name)&&e.name.includes("CopilotKit")||void 0!==(null===(t=null==e?void 0:e.extensions)||void 0===t?void 0:t.code)}var H=function(t){var r=t.errorCode,n=t.url,o=I[e.CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl,i=function(e){return void 0===e&&(e="Failed to fetch from url ".concat(n,".")),"".concat(e,".\n\nPossible reasons:\n- -The server may have an error preventing it from returning a response (Check the server logs for more info).\n- -The server might be down or unreachable\n- -There might be a network issue (e.g., DNS failure, connection timeout) \n- -The URL might be incorrect\n- -The server is not running on the specified port\n\n").concat(C(o))};if(n.includes("/info"))return i("Failed to fetch CopilotKit agents/action information from url ".concat(n,"."));if(n.includes("/actions/execute"))return i("Fetch call to ".concat(n," to execute actions failed."));if(n.includes("/agents/state"))return i("Fetch call to ".concat(n," to get agent state failed."));if(n.includes("/agents/execute"))return i("Fetch call to ".concat(n," to execute agent(s) failed."));switch(r){case"ECONNREFUSED":return"Connection to ".concat(n," was refused. Ensure the server is running and accessible.\n\n").concat(C(o));case"ENOTFOUND":return"The server on ".concat(n," could not be found. Check the URL or your network configuration.\n\n").concat(C(I[e.CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl));case"ETIMEDOUT":return"The connection to ".concat(n," timed out. The server might be overloaded or taking too long to respond.\n\n").concat(C(o));default:return}};function W(e){for(var t={},r=0,n=e||[];r<n.length;r++){var o=n[r];t[o.name]=F(o)}for(var i=[],s=0,a=e||[];s<a.length;s++){var c=a[s];!1!==c.required&&i.push(c.name)}return{type:"object",properties:t,required:i}}function q(e,t,r){var n={name:e,description:t.description};switch(r||(n.required=!1),t.type){case"string":return a(a(a({},n),{type:"string"}),t.enum&&{enum:t.enum});case"number":case"boolean":return a(a({},n),{type:t.type});case"object":if(t.properties){for(var o=[],i=t.required||[],s=0,c=Object.entries(t.properties);s<c.length;s++){var u=c[s],l=u[0],h=u[1];o.push(q(l,h,i.includes(l)))}return a(a({},n),{type:"object",attributes:o})}return a(a({},n),{type:"object"});case"array":if("object"===t.items.type&&"properties"in t.items){o=[],i=t.items.required||[];for(var d=0,p=Object.entries(t.items.properties||{});d<p.length;d++){var f=p[d];l=f[0],h=f[1];o.push(q(l,h,i.includes(l)))}return a(a({},n),{type:"object[]",attributes:o})}if("array"===t.items.type)throw new Error("Nested arrays are not supported");return a(a({},n),{type:"".concat(t.items.type,"[]")});default:return a(a({},n),{type:"string"})}}function F(e){var t,r,n;switch(e.type){case"string":return a({type:"string",description:e.description},e.enum&&{enum:e.enum});case"number":case"boolean":return{type:e.type,description:e.description};case"object":case"object[]":var o=null===(t=e.attributes)||void 0===t?void 0:t.reduce(function(e,t){return e[t.name]=F(t),e},{}),i=null===(r=e.attributes)||void 0===r?void 0:r.filter(function(e){return!1!==e.required}).map(function(e){return e.name});return"object[]"===e.type?{type:"array",items:a(a({type:"object"},o&&{properties:o}),i&&i.length>0&&{required:i}),description:e.description}:a(a({type:"object",description:e.description},o&&{properties:o}),i&&i.length>0&&{required:i});default:return(null===(n=e.type)||void 0===n?void 0:n.endsWith("[]"))?{type:"array",items:{type:e.type.slice(0,-2)},description:e.description}:{type:"string",description:e.description}}}function $(e,t){if("object"===e.type){var r={};if(!e.properties||!Object.keys(e.properties).length)return t?n.z.object(r):n.z.object(r).optional();for(var o=0,i=Object.entries(e.properties);o<i.length;o++){var s=i[o],a=s[0],c=s[1];r[a]=$(c,!!e.required&&e.required.includes(a))}var u=n.z.object(r).describe(e.description);return t?u:u.optional()}if("string"===e.type){u=n.z.string().describe(e.description);return t?u:u.optional()}if("number"===e.type){u=n.z.number().describe(e.description);return t?u:u.optional()}if("boolean"===e.type){u=n.z.boolean().describe(e.description);return t?u:u.optional()}if("array"===e.type){var l=$(e.items,!0);u=n.z.array(l).describe(e.description);return t?u:u.optional()}throw new Error("Invalid JSON schema")}function V(e){if("function"==typeof e)return e.toString();if(Array.isArray(e))return e.map(V);if(null!==e&&"object"==typeof e){for(var t={},r=0,n=Object.keys(e);r<n.length;r++){var o=n[r];t[o]=V(e[o])}return t}return e}var B="https://api.cloud.copilotkit.ai",J="".concat(B,"/copilotkit/").concat("v1");function G(e,t,r){t.split&&(t=t.split("."));for(var n,o,i=0,s=t.length,a=e;i<s&&"__proto__"!=(o=""+t[i++])&&"constructor"!==o&&"prototype"!==o;)a=a[o]=i===s?r:typeof(n=a[o])==typeof t?n:0*t[i]!=0||~(""+t[i]).indexOf(".")?{}:[]}var z=function(e){function t(t,r){var n=e.call(this,"".concat(t," ").concat(r))||this;return n.field=t,n}return s(t,e),t}(Error);function Y(e){return"string"==typeof e}function Q(e){return null!=e}function X(e){return"object"===Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}var Z="is not a string",ee="is not an object",te="is nil";function re(e){!function(e){if(!Q(e))throw new z("Event",te);if("object"!=typeof e)throw new z("Event",ee)}(e),function(e){if(!Y(e.type))throw new z(".type",Z)}(e),function(e){if(!Y(e.messageId))throw new z(".messageId",Z)}(e),"track"===e.type&&(function(e){if(!Y(e.event))throw new z(".event",Z)}(e),function(e){if(!X(e.properties))throw new z(".properties",ee)}(e)),["group","identify"].includes(e.type)&&function(e){if(!X(e.traits))throw new z(".traits",ee)}(e)}var ne=function(e){var t,r;this.settings=e,this.createMessageId=e.createMessageId,this.onEventMethodCall=null!==(t=e.onEventMethodCall)&&void 0!==t?t:function(){},this.onFinishedEvent=null!==(r=e.onFinishedEvent)&&void 0!==r?r:function(){}},oe=function(){function e(e){this.settings=new ne(e)}return e.prototype.track=function(e,t,r,n){return this.settings.onEventMethodCall({type:"track",options:r}),this.normalize(a(a({},this.baseEvent()),{event:e,type:"track",properties:null!=t?t:{},options:a({},r),integrations:a({},n)}))},e.prototype.page=function(e,t,r,n,o){var i;this.settings.onEventMethodCall({type:"page",options:n});var s={type:"page",properties:a({},r),options:a({},n),integrations:a({},o)};return null!==e&&(s.category=e,s.properties=null!==(i=s.properties)&&void 0!==i?i:{},s.properties.category=e),null!==t&&(s.name=t),this.normalize(a(a({},this.baseEvent()),s))},e.prototype.screen=function(e,t,r,n,o){this.settings.onEventMethodCall({type:"screen",options:n});var i={type:"screen",properties:a({},r),options:a({},n),integrations:a({},o)};return null!==e&&(i.category=e),null!==t&&(i.name=t),this.normalize(a(a({},this.baseEvent()),i))},e.prototype.identify=function(e,t,r,n){return this.settings.onEventMethodCall({type:"identify",options:r}),this.normalize(a(a({},this.baseEvent()),{type:"identify",userId:e,traits:null!=t?t:{},options:a({},r),integrations:n}))},e.prototype.group=function(e,t,r,n){return this.settings.onEventMethodCall({type:"group",options:r}),this.normalize(a(a({},this.baseEvent()),{type:"group",traits:null!=t?t:{},options:a({},r),integrations:a({},n),groupId:e}))},e.prototype.alias=function(e,t,r,n){this.settings.onEventMethodCall({type:"alias",options:r});var o={userId:e,type:"alias",options:a({},r),integrations:a({},n)};return null!==t&&(o.previousId=t),void 0===e?this.normalize(a(a({},o),this.baseEvent())):this.normalize(a(a({},this.baseEvent()),o))},e.prototype.baseEvent=function(){return{integrations:{},options:{}}},e.prototype.context=function(e){var t,r=["userId","anonymousId","timestamp","messageId"];delete e.integrations;var n=Object.keys(e),o=null!==(t=e.context)&&void 0!==t?t:{},i={};return n.forEach(function(t){"context"!==t&&(r.includes(t)?G(i,t,e[t]):G(o,t,e[t]))}),[o,i]},e.prototype.normalize=function(e){var t,r,n,o,i=Object.keys(null!==(t=e.integrations)&&void 0!==t?t:{}).reduce(function(t,r){var n,o;return a(a({},t),((n={})[r]=Boolean(null===(o=e.integrations)||void 0===o?void 0:o[r]),n))},{});e.options=(n=e.options||{},o=function(e,t){return void 0!==t},Object.keys(n).filter(function(e){return o(e,n[e])}).reduce(function(e,t){return e[t]=n[t],e},{}));var s=a(a({},i),null===(r=e.options)||void 0===r?void 0:r.integrations),c=e.options?this.context(e.options):[],u=c[0],l=c[1],h=e.options,d=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(e,["options"]),p=a(a(a(a({timestamp:new Date},d),{context:u,integrations:s}),l),{messageId:h.messageId||this.settings.createMessageId()});return this.settings.onFinishedEvent(p),re(p),p},e}();function ie(e,t){return new Promise(function(r,n){var o=setTimeout(function(){n(Error("Promise timed out"))},t);e.then(function(e){return clearTimeout(o),r(e)}).catch(n)})}function se(e){return new Promise(function(t){return setTimeout(t,e)})}function ae(e,t,r){return se(r).then(function(){return ie(function(){try{return Promise.resolve(t(e))}catch(e){return Promise.reject(e)}}(),1e3)}).catch(function(t){null==e||e.log("warn","Callback Error",{error:t}),null==e||e.stats.increment("callback_error")}).then(function(){return e})}var ce=function(){function e(e){var t;this.callbacks={},this.warned=!1,this.maxListeners=null!==(t=null==e?void 0:e.maxListeners)&&void 0!==t?t:10}return e.prototype.warnIfPossibleMemoryLeak=function(e){this.warned||this.maxListeners&&this.callbacks[e].length>this.maxListeners&&(console.warn("Event Emitter: Possible memory leak detected; ".concat(String(e)," has exceeded ").concat(this.maxListeners," listeners.")),this.warned=!0)},e.prototype.on=function(e,t){return this.callbacks[e]?(this.callbacks[e].push(t),this.warnIfPossibleMemoryLeak(e)):this.callbacks[e]=[t],this},e.prototype.once=function(e,t){var r=this,n=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];r.off(e,n),t.apply(r,o)};return this.on(e,n),this},e.prototype.off=function(e,t){var r,n=(null!==(r=this.callbacks[e])&&void 0!==r?r:[]).filter(function(e){return e!==t});return this.callbacks[e]=n,this},e.prototype.emit=function(e){for(var t,r=this,n=[],o=1;o<arguments.length;o++)n[o-1]=arguments[o];return(null!==(t=this.callbacks[e])&&void 0!==t?t:[]).forEach(function(e){e.apply(r,n)}),this},e}();function ue(e){var t=Math.random()+1,r=e.minTimeout,n=void 0===r?500:r,o=e.factor,i=void 0===o?2:o,s=e.attempt,a=e.maxTimeout,c=void 0===a?1/0:a;return Math.min(t*n*Math.pow(i,s),c)}for(var le,he="onRemoveFromFuture",de=function(e){function t(t,r,n){var o=e.call(this)||this;return o.future=[],o.maxAttempts=t,o.queue=r,o.seen=null!=n?n:{},o}return s(t,e),t.prototype.push=function(){for(var e=this,t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var n=t.map(function(t){return!(e.updateAttempts(t)>e.maxAttempts||e.includes(t))&&(e.queue.push(t),!0)});return this.queue=this.queue.sort(function(t,r){return e.getAttempts(t)-e.getAttempts(r)}),n},t.prototype.pushWithBackoff=function(e,t){var r=this;if(void 0===t&&(t=0),0==t&&0===this.getAttempts(e))return this.push(e)[0];var n=this.updateAttempts(e);if(n>this.maxAttempts||this.includes(e))return!1;var o=ue({attempt:n-1});return t>0&&o<t&&(o=t),setTimeout(function(){r.queue.push(e),r.future=r.future.filter(function(t){return t.id!==e.id}),r.emit(he)},o),this.future.push(e),!0},t.prototype.getAttempts=function(e){var t;return null!==(t=this.seen[e.id])&&void 0!==t?t:0},t.prototype.updateAttempts=function(e){return this.seen[e.id]=this.getAttempts(e)+1,this.getAttempts(e)},t.prototype.includes=function(e){return this.queue.includes(e)||this.future.includes(e)||Boolean(this.queue.find(function(t){return t.id===e.id}))||Boolean(this.future.find(function(t){return t.id===e.id}))},t.prototype.pop=function(){return this.queue.shift()},Object.defineProperty(t.prototype,"length",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"todo",{get:function(){return this.queue.length+this.future.length},enumerable:!1,configurable:!0}),t}(ce),pe=256,fe=[];pe--;)fe[pe]=(pe+256).toString(16).substring(1);function ge(){var e,t=0,r="";if(!le||pe+16>256){for(le=Array(t=256);t--;)le[t]=256*Math.random()|0;t=pe=0}for(;t<16;t++)e=le[pe+t],r+=6==t?fe[15&e|64]:8==t?fe[63&e|128]:fe[e],1&t&&t>1&&t<11&&(r+="-");return pe++,r}var me=function(){function e(){this._logs=[]}return e.prototype.log=function(e,t,r){var n=new Date;this._logs.push({level:e,message:t,time:n,extras:r})},Object.defineProperty(e.prototype,"logs",{get:function(){return this._logs},enumerable:!1,configurable:!0}),e.prototype.flush=function(){if(this.logs.length>1){var e=this._logs.reduce(function(e,t){var r,n,o,i=a(a({},t),{json:JSON.stringify(t.extras,null," "),extras:t.extras});delete i.time;var s=null!==(o=null===(n=t.time)||void 0===n?void 0:n.toISOString())&&void 0!==o?o:"";return e[s]&&(s="".concat(s,"-").concat(Math.random())),a(a({},e),((r={})[s]=i,r))},{});console.table?console.table(e):console.log(e)}else this.logs.forEach(function(e){var t=e.level,r=e.message,n=e.extras;"info"===t||"debug"===t?console.log(r,null!=n?n:""):console[t](r,null!=n?n:"")});this._logs=[]},e}(),ye=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return s(t,e),t.prototype.gauge=function(){},t.prototype.increment=function(){},t.prototype.flush=function(){},t.prototype.serialize=function(){return[]},t}(function(){function e(){this.metrics=[]}return e.prototype.increment=function(e,t,r){void 0===t&&(t=1),this.metrics.push({metric:e,value:t,tags:null!=r?r:[],type:"counter",timestamp:Date.now()})},e.prototype.gauge=function(e,t,r){this.metrics.push({metric:e,value:t,tags:null!=r?r:[],type:"gauge",timestamp:Date.now()})},e.prototype.flush=function(){var e=this.metrics.map(function(e){return a(a({},e),{tags:e.tags.join(",")})});console.table?console.table(e):console.log(e),this.metrics=[]},e.prototype.serialize=function(){return this.metrics.map(function(e){return{m:e.metric,v:e.value,t:e.tags,k:(t=e.type,{gauge:"g",counter:"c"}[t]),e:e.timestamp};var t})},e}()),ve=function(e){var t,r,n;this.retry=null===(t=e.retry)||void 0===t||t,this.type=null!==(r=e.type)&&void 0!==r?r:"plugin Error",this.reason=null!==(n=e.reason)&&void 0!==n?n:""},be=function(){function e(e,t,r,n){void 0===t&&(t=ge()),void 0===r&&(r=new ye),void 0===n&&(n=new me),this.attempts=0,this.event=e,this._id=t,this.logger=n,this.stats=r}return e.system=function(){},e.prototype.isSame=function(e){return e.id===this.id},e.prototype.cancel=function(e){if(e)throw e;throw new ve({reason:"Context Cancel"})},e.prototype.log=function(e,t,r){this.logger.log(e,t,r)},Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),e.prototype.updateEvent=function(e,t){var r;if("integrations"===e.split(".")[0]){var n=e.split(".")[1];if(!1===(null===(r=this.event.integrations)||void 0===r?void 0:r[n]))return this.event}return G(this.event,e,t),this.event},e.prototype.failedDelivery=function(){return this._failedDelivery},e.prototype.setFailedDelivery=function(e){this._failedDelivery=e},e.prototype.logs=function(){return this.logger.logs},e.prototype.flush=function(){this.logger.flush(),this.stats.flush()},e.prototype.toJSON=function(){return{id:this._id,event:this.event,logs:this.logger.logs,metrics:this.stats.metrics}},e}();function Ee(e,t){e.log("debug","plugin",{plugin:t.name});var r=(new Date).getTime(),n=t[e.event.type];if(void 0===n)return Promise.resolve(e);var o=function(e){return c(this,void 0,void 0,function(){var t;return u(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,e()];case 1:return[2,r.sent()];case 2:return t=r.sent(),[2,Promise.reject(t)];case 3:return[2]}})})}(function(){return n.apply(t,[e])}).then(function(e){var n=(new Date).getTime()-r;return e.stats.gauge("plugin_time",n,["plugin:".concat(t.name)]),e}).catch(function(r){if(r instanceof ve&&"middleware_cancellation"===r.type)throw r;return r instanceof ve?(e.log("warn",r.type,{plugin:t.name,error:r}),r):(e.log("error","plugin Error",{plugin:t.name,error:r}),e.stats.increment("plugin_error",1,["plugin:".concat(t.name)]),r)});return o}function _e(e,t){return Ee(e,t).then(function(t){if(t instanceof be)return t;e.log("debug","Context canceled"),e.stats.increment("context_canceled"),e.cancel(t)})}var we=function(e){function t(t){var r,n,o,i=e.call(this)||this;return i.criticalTasks=(o=0,{done:function(){return r},run:function(e){var t,i=e();return"object"==typeof(t=i)&&null!==t&&"then"in t&&"function"==typeof t.then&&(1===++o&&(r=new Promise(function(e){return n=e})),i.finally(function(){return 0===--o&&n()})),i}}),i.plugins=[],i.failedInitializations=[],i.flushing=!1,i.queue=t,i.queue.on(he,function(){i.scheduleFlush(0)}),i}return s(t,e),t.prototype.register=function(e,t,r){return c(this,void 0,void 0,function(){var n,o,i=this;return u(this,function(s){switch(s.label){case 0:return this.plugins.push(t),n=function(r){i.failedInitializations.push(t.name),i.emit("initialization_failure",t),console.warn(t.name,r),e.log("warn","Failed to load destination",{plugin:t.name,error:r}),i.plugins=i.plugins.filter(function(e){return e!==t})},"destination"!==t.type||"Segment.io"===t.name?[3,1]:(t.load(e,r).catch(n),[3,4]);case 1:return s.trys.push([1,3,,4]),[4,t.load(e,r)];case 2:return s.sent(),[3,4];case 3:return o=s.sent(),n(o),[3,4];case 4:return[2]}})})},t.prototype.deregister=function(e,t,r){return c(this,void 0,void 0,function(){var n;return u(this,function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),t.unload?[4,Promise.resolve(t.unload(e,r))]:[3,2];case 1:o.sent(),o.label=2;case 2:return this.plugins=this.plugins.filter(function(e){return e.name!==t.name}),[3,4];case 3:return n=o.sent(),e.log("warn","Failed to unload destination",{plugin:t.name,error:n}),[3,4];case 4:return[2]}})})},t.prototype.dispatch=function(e){return c(this,void 0,void 0,function(){var t;return u(this,function(r){return e.log("debug","Dispatching"),e.stats.increment("message_dispatched"),this.queue.push(e),t=this.subscribeToDelivery(e),this.scheduleFlush(0),[2,t]})})},t.prototype.subscribeToDelivery=function(e){return c(this,void 0,void 0,function(){var t=this;return u(this,function(r){return[2,new Promise(function(r){var n=function(o,i){o.isSame(e)&&(t.off("flush",n),r(o))};t.on("flush",n)})]})})},t.prototype.dispatchSingle=function(e){return c(this,void 0,void 0,function(){var t=this;return u(this,function(r){return e.log("debug","Dispatching"),e.stats.increment("message_dispatched"),this.queue.updateAttempts(e),e.attempts=1,[2,this.deliver(e).catch(function(r){return t.enqueuRetry(r,e)?t.subscribeToDelivery(e):(e.setFailedDelivery({reason:r}),e)})]})})},t.prototype.isEmpty=function(){return 0===this.queue.length},t.prototype.scheduleFlush=function(e){var t=this;void 0===e&&(e=500),this.flushing||(this.flushing=!0,setTimeout(function(){t.flush().then(function(){setTimeout(function(){t.flushing=!1,t.queue.length&&t.scheduleFlush(0)},0)})},e))},t.prototype.deliver=function(e){return c(this,void 0,void 0,function(){var t,r,n,o;return u(this,function(i){switch(i.label){case 0:return[4,this.criticalTasks.done()];case 1:i.sent(),t=Date.now(),i.label=2;case 2:return i.trys.push([2,4,,5]),[4,this.flushOne(e)];case 3:return e=i.sent(),r=Date.now()-t,this.emit("delivery_success",e),e.stats.gauge("delivered",r),e.log("debug","Delivered",e.event),[2,e];case 4:throw n=i.sent(),o=n,e.log("error","Failed to deliver",o),this.emit("delivery_failure",e,o),e.stats.increment("delivery_failed"),n;case 5:return[2]}})})},t.prototype.enqueuRetry=function(e,t){return!(e instanceof ve&&!e.retry)&&this.queue.pushWithBackoff(t)},t.prototype.flush=function(){return c(this,void 0,void 0,function(){var e,t;return u(this,function(r){switch(r.label){case 0:if(0===this.queue.length)return[2,[]];if(!(e=this.queue.pop()))return[2,[]];e.attempts=this.queue.getAttempts(e),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.deliver(e)];case 2:return e=r.sent(),this.emit("flush",e,!0),[3,4];case 3:return t=r.sent(),this.enqueuRetry(t,e)||(e.setFailedDelivery({reason:t}),this.emit("flush",e,!1)),[2,[]];case 4:return[2,[e]]}})})},t.prototype.isReady=function(){return!0},t.prototype.availableExtensions=function(e){var t,r,n=this.plugins.filter(function(t){var r,n,o;if("destination"!==t.type&&"Segment.io"!==t.name)return!0;var i=void 0;return null===(r=t.alternativeNames)||void 0===r||r.forEach(function(t){void 0!==e[t]&&(i=e[t])}),null!==(o=null!==(n=e[t.name])&&void 0!==n?n:i)&&void 0!==o?o:!1!==("Segment.io"===t.name||e.All)}),o=(t="type",r={},n.forEach(function(e){var n,o,i=e[t];void 0!==(o="string"!=typeof i?JSON.stringify(i):i)&&(r[o]=l(l([],null!==(n=r[o])&&void 0!==n?n:[],!0),[e],!1))}),r),i=o.before,s=void 0===i?[]:i,a=o.enrichment,c=void 0===a?[]:a,u=o.destination,h=void 0===u?[]:u,d=o.after;return{before:s,enrichment:c,destinations:h,after:void 0===d?[]:d}},t.prototype.flushOne=function(e){var t,r;return c(this,void 0,void 0,function(){var n,o,i,s,a,c,l,h,d,p,f,g,m,y;return u(this,function(u){switch(u.label){case 0:if(!this.isReady())throw new Error("Not ready");e.attempts>1&&this.emit("delivery_retry",e),n=this.availableExtensions(null!==(t=e.event.integrations)&&void 0!==t?t:{}),o=n.before,i=n.enrichment,s=0,a=o,u.label=1;case 1:return s<a.length?(c=a[s],[4,_e(e,c)]):[3,4];case 2:(p=u.sent())instanceof be&&(e=p),this.emit("message_enriched",e,c),u.label=3;case 3:return s++,[3,1];case 4:l=0,h=i,u.label=5;case 5:return l<h.length?(d=h[l],[4,Ee(e,d)]):[3,8];case 6:(p=u.sent())instanceof be&&(e=p),this.emit("message_enriched",e,d),u.label=7;case 7:return l++,[3,5];case 8:return f=this.availableExtensions(null!==(r=e.event.integrations)&&void 0!==r?r:{}),g=f.destinations,m=f.after,[4,new Promise(function(t,r){setTimeout(function(){var n=g.map(function(t){return Ee(e,t)});Promise.all(n).then(t).catch(r)},0)})];case 9:return u.sent(),e.stats.increment("message_delivered"),this.emit("message_delivered",e),y=m.map(function(t){return Ee(e,t)}),[4,Promise.all(y)];case 10:return u.sent(),[2,e]}})})},t}(ce);const Re="2.3.0";class Oe{id=ge();items=[];sizeInBytes=0;maxEventCount;constructor(e){this.maxEventCount=Math.max(1,e)}tryAdd(e){if(this.length===this.maxEventCount)return{success:!1,message:`Event limit of ${this.maxEventCount} has been exceeded.`};const t=this.calculateSize(e.context);return t>32768?{success:!1,message:"Event exceeds maximum event size of 32 KB"}:this.sizeInBytes+t>491520?{success:!1,message:"Event has caused batch size to exceed 480 KB"}:(this.items.push(e),this.sizeInBytes+=t,{success:!0})}get length(){return this.items.length}calculateSize(e){return encodeURI(JSON.stringify(e.event)).split(/%..|i/).length}getEvents(){return this.items.map(({context:e})=>e.event)}getContexts(){return this.items.map(e=>e.context)}resolveEvents(){this.items.forEach(({resolver:e,context:t})=>e(t))}}var Ce=crypto;const Ie=e=>e instanceof CryptoKey,Se=new TextEncoder,Te=new TextDecoder;const Ae=e=>(e=>{let t=e;"string"==typeof t&&(t=Se.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),ke=e=>{let t=e;t instanceof Uint8Array&&(t=Te.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Pe extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}Pe.code="ERR_JOSE_GENERIC";(class extends Pe{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}).code="ERR_JWT_CLAIM_VALIDATION_FAILED";(class extends Pe{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}).code="ERR_JWT_EXPIRED";(class extends Pe{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}).code="ERR_JOSE_ALG_NOT_ALLOWED";class Ne extends Pe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}Ne.code="ERR_JOSE_NOT_SUPPORTED";(class extends Pe{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}).code="ERR_JWE_DECRYPTION_FAILED";(class extends Pe{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}).code="ERR_JWE_INVALID";class xe extends Pe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}xe.code="ERR_JWS_INVALID";class De extends Pe{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}De.code="ERR_JWT_INVALID";(class extends Pe{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}).code="ERR_JWK_INVALID";(class extends Pe{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}).code="ERR_JWKS_INVALID";(class extends Pe{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}).code="ERR_JWKS_NO_MATCHING_KEY";(class extends Pe{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}).code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";(class extends Pe{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}).code="ERR_JWKS_TIMEOUT";function Ke(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Me(e,t){return e.name===t}function je(e){return parseInt(e.name.slice(4),10)}function Ue(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!Me(e.algorithm,"HMAC"))throw Ke("HMAC");const r=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==r)throw Ke(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Me(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Ke("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==r)throw Ke(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Me(e.algorithm,"RSA-PSS"))throw Ke("RSA-PSS");const r=parseInt(t.slice(2),10);if(je(e.algorithm.hash)!==r)throw Ke(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw Ke("Ed25519 or Ed448");break;case"Ed25519":if(!Me(e.algorithm,"Ed25519"))throw Ke("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!Me(e.algorithm,"ECDSA"))throw Ke("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw Ke(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}(e,r)}function Le(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}(class extends Pe{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}).code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var He=(e,...t)=>Le("Key must be ",e,...t);function We(e,t,...r){return Le(`Key for the ${e} algorithm must be `,t,...r)}var qe=e=>!!Ie(e)||"KeyObject"===e?.[Symbol.toStringTag];const Fe=["CryptoKey"];function $e(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}function Ve(e){return $e(e)&&"string"==typeof e.kty}const Be=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new Ne('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new Ne('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new Ne('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new Ne('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,Ce.subtle.importKey("jwk",o,...n)},Je=e=>ke(e);let Ge;const ze=e=>"KeyObject"===e?.[Symbol.toStringTag],Ye=async(e,t,r,n,o=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const s=await Be({...r,alg:n});return o&&Object.freeze(t),i?i[n]=s:e.set(t,{[n]:s}),s};var Qe=(e,t)=>{if(ze(e)){let r=e.export({format:"jwk"});return r.k?Je(r.k):(Ge||(Ge=new WeakMap),Ye(Ge,e,r,t))}if(Ve(e)){if(e.k)return ke(e.k);Ge||(Ge=new WeakMap);return Ye(Ge,e,e,t,!0)}return e};const Xe=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));const n=e.indexOf(t[0],r);if(-1===n)return!1;const o=e.subarray(n,n+t.length);return o.length===t.length&&(o.every((e,r)=>e===t[r])||Xe(e,t,n+1))},Ze=e=>{switch(!0){case Xe(e,[42,134,72,206,61,3,1,7]):return"P-256";case Xe(e,[43,129,4,0,34]):return"P-384";case Xe(e,[43,129,4,0,35]):return"P-521";case Xe(e,[43,101,110]):return"X25519";case Xe(e,[43,101,111]):return"X448";case Xe(e,[43,101,112]):return"Ed25519";case Xe(e,[43,101,113]):return"Ed448";default:throw new Ne("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},et=(e,t,r)=>(async(e,t,r,n)=>{let o,i;const s=new Uint8Array(atob(r.replace(e,"")).split("").map(e=>e.charCodeAt(0)));switch(n){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=["sign"];break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=["decrypt","unwrapKey"];break;case"ES256":o={name:"ECDSA",namedCurve:"P-256"},i=["sign"];break;case"ES384":o={name:"ECDSA",namedCurve:"P-384"},i=["sign"];break;case"ES512":o={name:"ECDSA",namedCurve:"P-521"},i=["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{const e=Ze(s);o=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},i=["deriveBits"];break}case"Ed25519":o={name:"Ed25519"},i=["sign"];break;case"EdDSA":o={name:Ze(s)},i=["sign"];break;default:throw new Ne('Invalid or unsupported "alg" (Algorithm) value')}return Ce.subtle.importKey(t,s,o,!1,i)})(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t);const tt=e=>e?.[Symbol.toStringTag],rt=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},nt=(e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&Ve(t)){if(function(e){return Ve(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&rt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!qe(t))throw new TypeError(We(e,t,...Fe,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${tt(t)} instances for symmetric algorithms must be of type "secret"`)}};function ot(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?nt(t,r,n,e):((e,t,r,n)=>{if(n&&Ve(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&rt(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!qe(t))throw new TypeError(We(e,t,...Fe,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${tt(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${tt(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${tt(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${tt(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${tt(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}ot.bind(void 0,!1);const it=ot.bind(void 0,!0);var st=e=>Math.floor(e.getTime()/1e3);const at=86400,ct=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var ut=e=>{const t=ct.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(r*at);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const lt=async(e,t,r)=>{const n=await async function(e,t,r){if(t=await Qe(t,e),Ie(t))return Ue(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(He(t,...Fe));return Ce.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(He(t,...Fe,"Uint8Array","JSON Web Key"))}(e,t,"sign");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,n);const o=await Ce.subtle.sign(function(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new Ne(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}(e,n.algorithm),n,r);return new Uint8Array(o)};class ht{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new xe("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0})(this._protectedHeader,this._unprotectedHeader))throw new xe("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader},n=function(e,t,r,n,o){if(void 0!==o.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new Ne(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}(xe,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r);let o=!0;if(n.has("b64")&&(o=this._protectedHeader.b64,"boolean"!=typeof o))throw new xe('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=r;if("string"!=typeof i||!i)throw new xe('JWS "alg" (Algorithm) Header Parameter missing or invalid');it(i,e,"sign");let s,a=this._payload;o&&(a=Se.encode(Ae(a))),s=this._protectedHeader?Se.encode(Ae(JSON.stringify(this._protectedHeader))):Se.encode("");const c=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(s,Se.encode("."),a),u=await lt(i,e,c),l={signature:Ae(u),payload:""};return o&&(l.payload=Te.decode(a)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=Te.decode(s)),l}}class dt{constructor(e){this._flattened=new ht(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function pt(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ft{constructor(e={}){if(!$e(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:pt("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:pt("setNotBefore",st(e))}:this._payload={...this._payload,nbf:st(new Date)+ut(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:pt("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:pt("setExpirationTime",st(e))}:this._payload={...this._payload,exp:st(new Date)+ut(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:st(new Date)}:e instanceof Date?this._payload={...this._payload,iat:pt("setIssuedAt",st(e))}:this._payload="string"==typeof e?{...this._payload,iat:pt("setIssuedAt",st(new Date)+ut(e))}:{...this._payload,iat:pt("setIssuedAt",e)},this}}class gt extends ft{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new dt(Se.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new De("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}function mt(e){const t={};if(!e)return{};if(function(e){if("object"==typeof e&&null!==e&&"entries"in Object(e)&&"function"==typeof Object(e).entries)return!0;return!1}(e)){for(const[r,n]of e.entries())t[r.toLowerCase()]=n;return t}for(const[r,n]of Object.entries(e))t[r.toLowerCase()]=n;return t}class yt{alg="RS256";grantType="client_credentials";clientAssertionType="urn:ietf:params:oauth:client-assertion-type:jwt-bearer";clientId;clientKey;keyId;scope;authServer;httpClient;maxRetries;clockSkewInSeconds=0;accessToken;tokenEmitter=new ce;retryCount;pollerTimer;constructor(e){this.keyId=e.keyId,this.clientId=e.clientId,this.clientKey=e.clientKey,this.authServer=e.authServer??"https://oauth2.segment.io",this.scope=e.scope??"tracking_api:write",this.httpClient=e.httpClient,this.maxRetries=e.maxRetries,this.tokenEmitter.on("access_token",e=>{"token"in e&&(this.accessToken=e.token)}),this.retryCount=0}stopPoller(){clearTimeout(this.pollerTimer)}async pollerLoop(){let e,t=25;try{e=await this.requestAccessToken()}catch(e){return this.handleTransientError({error:e})}if(!(e=>"function"==typeof e.text)(e))return this.handleInvalidCustomResponse();const r=mt(e.headers);if(r.date&&this.updateClockSkew(Date.parse(r.date)),200!==e.status)return 429===e.status?await this.handleRateLimited(e,r,t):[400,401,415].includes(e.status)?this.handleUnrecoverableErrors(e):this.handleTransientError({error:new Error(`[${e.status}] ${e.statusText}`)});try{const r=await e.text(),o=JSON.parse(r);if(n=o,!Boolean(n&&"object"==typeof n&&"access_token"in n&&"expires_in"in n&&"string"==typeof n.access_token&&"number"==typeof n.expires_in))throw new Error("Response did not contain a valid access_token and expires_in");return o.expires_at=Math.round(Date.now()/1e3)+o.expires_in,this.tokenEmitter.emit("access_token",{token:o}),this.retryCount=0,t=o.expires_in/2*1e3,this.queueNextPoll(t)}catch(e){return this.handleTransientError({error:e,forceEmitError:!0})}var n}handleTransientError({error:e,forceEmitError:t}){this.incrementRetries({error:e,forceEmitError:t});const r=ue({attempt:this.retryCount,minTimeout:25,maxTimeout:1e3});this.queueNextPoll(r)}handleInvalidCustomResponse(){this.tokenEmitter.emit("access_token",{error:new Error("HTTPClient does not implement response.text method")})}async handleRateLimited(e,t,r){if(this.incrementRetries({error:new Error(`[${e.status}] ${e.statusText}`)}),t["x-ratelimit-reset"]){const e=parseInt(t["x-ratelimit-reset"],10);r=isFinite(e)?e-Date.now()+1e3*this.clockSkewInSeconds:5e3,await se(r),r=0}this.queueNextPoll(r)}handleUnrecoverableErrors(e){this.retryCount=0,this.tokenEmitter.emit("access_token",{error:new Error(`[${e.status}] ${e.statusText}`)}),this.stopPoller()}updateClockSkew(e){this.clockSkewInSeconds=(Date.now()-e)/1e3}incrementRetries({error:e,forceEmitError:t}){this.retryCount++,(t||this.retryCount%this.maxRetries===0)&&(this.retryCount=0,this.tokenEmitter.emit("access_token",{error:e}))}queueNextPoll(e){this.pollerTimer=setTimeout(()=>this.pollerLoop(),e),this.pollerTimer.unref&&this.pollerTimer.unref()}async requestAccessToken(){const e=ge(),t=Math.round(Date.now()/1e3)-this.clockSkewInSeconds,r={iss:this.clientId,sub:this.clientId,aud:this.authServer,iat:t-5,exp:t+55,jti:e},n=await async function(e,t){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return et(e,t)}(this.clientKey,"RS256"),o=await new gt(r).setProtectedHeader({alg:this.alg,kid:this.keyId,typ:"JWT"}).sign(n),i=`grant_type=${this.grantType}&client_assertion_type=${this.clientAssertionType}&client_assertion=${o}&scope=${this.scope}`,s={method:"POST",url:`${this.authServer}/token`,body:i,headers:{"Content-Type":"application/x-www-form-urlencoded"},httpRequestTimeout:1e4};return this.httpClient.makeRequest(s)}async getAccessToken(){return this.isValidToken(this.accessToken)?this.accessToken:(this.stopPoller(),this.pollerLoop().catch(()=>{}),new Promise((e,t)=>{this.tokenEmitter.once("access_token",r=>{"token"in r?e(r.token):t(r.error)})}))}clearToken(){this.accessToken=void 0}isValidToken(e){return null!=e&&e.expires_in<Date.now()/1e3}}function vt(e){return new Promise(t=>setTimeout(t,e))}function bt(){}class Et{pendingFlushTimeout;_batch;_flushInterval;_flushAt;_maxRetries;_url;_flushPendingItemsCount;_httpRequestTimeout;_emitter;_disable;_httpClient;_writeKey;_tokenManager;constructor({host:e,path:t,maxRetries:r,flushAt:n,flushInterval:o,writeKey:i,httpRequestTimeout:s,httpClient:a,disable:c,oauthSettings:u},l){this._emitter=l,this._maxRetries=r,this._flushAt=Math.max(n,1),this._flushInterval=o,this._url=((e,t)=>new URL(t||"",e).href.replace(/\/$/,""))(e??"https://api.segment.io",t??"/v1/batch"),this._httpRequestTimeout=s??1e4,this._disable=Boolean(c),this._httpClient=a,this._writeKey=i,u&&(this._tokenManager=new yt({...u,httpClient:u.httpClient??a,maxRetries:u.maxRetries??r}))}createBatch(){this.pendingFlushTimeout&&clearTimeout(this.pendingFlushTimeout);const e=new Oe(this._flushAt);return this._batch=e,this.pendingFlushTimeout=setTimeout(()=>{e===this._batch&&(this._batch=void 0),this.pendingFlushTimeout=void 0,e.length&&this.send(e).catch(bt)},this._flushInterval),e}clearBatch(){this.pendingFlushTimeout&&clearTimeout(this.pendingFlushTimeout),this._batch=void 0}flush(e){if(!e)return void(this._tokenManager&&this._tokenManager.stopPoller());if(this._flushPendingItemsCount=e,!this._batch)return;this._batch.length===e&&(this.send(this._batch).catch(bt).finally(()=>{this._tokenManager&&this._tokenManager.stopPoller()}),this.clearBatch())}enqueue(e){const t=this._batch??this.createBatch(),{promise:r,resolve:n}=function(){var e,t,r=!1,n=new Promise(function(n,o){e=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r=!0,n.apply(void 0,e)},t=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];r=!0,o.apply(void 0,e)}});return{resolve:e,reject:t,promise:n,isSettled:function(){return r}}}(),o={context:e,resolver:n};if(t.tryAdd(o).success){const e=t.length===this._flushPendingItemsCount;return(t.length===this._flushAt||e)&&(this.send(t).catch(bt),this.clearBatch()),r}t.length&&(this.send(t).catch(bt),this.clearBatch());const i=this.createBatch(),s=i.tryAdd(o);if(s.success){return i.length===this._flushPendingItemsCount&&(this.send(i).catch(bt),this.clearBatch()),r}return e.setFailedDelivery({reason:new Error(s.message)}),Promise.resolve(e)}async send(e){this._flushPendingItemsCount&&(this._flushPendingItemsCount-=e.length);const t=e.getEvents(),r=this._maxRetries+1;let n=0;for(;n<r;){let o,i;n++;try{if(this._disable)return e.resolveEvents();let r;if(this._tokenManager){const e=await this._tokenManager.getAccessToken();e&&e.access_token&&(r=`Bearer ${e.access_token}`)}const n={"Content-Type":"application/json","User-Agent":"analytics-node-next/latest",...r?{Authorization:r}:{}},s={url:this._url,method:"POST",headers:n,body:JSON.stringify({batch:t,writeKey:this._writeKey,sentAt:new Date}),httpRequestTimeout:this._httpRequestTimeout};this._emitter.emit("http_request",{body:s.body,method:s.method,url:s.url,headers:s.headers});const a=await this._httpClient.makeRequest(s);if(a.status>=200&&a.status<300)return void e.resolveEvents();if(!this._tokenManager||400!==a.status&&401!==a.status&&403!==a.status){if(400===a.status)return void _t(e,new Error(`[${a.status}] ${a.statusText}`));if(429===a.status){if(a.headers&&"x-ratelimit-reset"in a.headers){const e=parseInt(a.headers["x-ratelimit-reset"],10);isFinite(e)&&(o=e-Date.now())}i=new Error(`[${a.status}] ${a.statusText}`)}else i=new Error(`[${a.status}] ${a.statusText}`)}else this._tokenManager.clearToken(),i=new Error(`[${a.status}] ${a.statusText}`)}catch(e){i=e}if(n===r)return void _t(e,i);await vt(o||ue({attempt:n,minTimeout:25,maxTimeout:1e3}))}}}function _t(e,t){e.getContexts().forEach(e=>e.setFailedDelivery({reason:t})),e.resolveEvents()}const wt=()=>"object"==typeof process&&process&&"object"==typeof process.env&&process.env&&"string"==typeof process.version?"node":"object"==typeof window?"browser":"undefined"!=typeof WebSocketPair?"cloudflare-worker":"string"==typeof EdgeRuntime?"vercel-edge":"undefined"!=typeof WorkerGlobalScope&&"function"==typeof importScripts?"web-worker":"unknown";function Rt(e){function t(t){return function(e){e.updateEvent("context.library.name","@segment/analytics-node"),e.updateEvent("context.library.version",Re);const t=wt();"node"===t&&e.updateEvent("_metadata.nodeVersion",process.version),e.updateEvent("_metadata.jsRuntime",t)}(t),e.enqueue(t)}return{name:"Segment.io",type:"destination",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),alias:t,group:t,identify:t,page:t,screen:t,track:t}}const Ot=()=>`node-next-${Date.now()}-${ge()}`;class Ct extends oe{constructor(){super({createMessageId:Ot,onFinishedEvent:e=>{!function(e){var t=".userId/anonymousId/previousId/groupId",r=function(e){var t,r,n;return null!==(n=null!==(r=null!==(t=e.userId)&&void 0!==t?t:e.anonymousId)&&void 0!==r?r:e.groupId)&&void 0!==n?n:e.previousId}(e);if(!Q(r))throw new z(t,te);if(!Y(r))throw new z(t,Z)}(e)}})}}class It extends be{static system(){return new this({type:"track",event:"system"})}}const St=async(e,t,r,n)=>{try{const i=new It(e),s=await function(e,t,r,n){return c(this,void 0,void 0,function(){var o,i;return u(this,function(s){switch(s.label){case 0:return r.emit("dispatch_start",e),o=Date.now(),t.isEmpty()?[4,t.dispatchSingle(e)]:[3,2];case 1:return i=s.sent(),[3,4];case 2:return[4,t.dispatch(e)];case 3:i=s.sent(),s.label=4;case 4:return(null==n?void 0:n.callback)?[4,ae(i,n.callback,(a=o,c=n.timeout,u=Date.now()-a,Math.max((null!=c?c:300)-u,0)))]:[3,6];case 5:i=s.sent(),s.label=6;case 6:return(null==n?void 0:n.debug)&&i.flush(),[2,i]}var a,c,u})})}(i,t,r,{...n?{callback:(o=n,e=>{const t=e.failedDelivery();return o(t?t.reason:void 0,e)})}:{}}),a=s.failedDelivery();a?r.emit("error",{code:"delivery_failure",reason:a.reason,ctx:s}):r.emit(e.type,s)}catch(e){r.emit("error",{code:"unknown",reason:e})}var o};class Tt extends ce{}class At extends de{constructor(){super(1,[])}getAttempts(e){return e.attempts??0}updateAttempts(e){return e.attempts=this.getAttempts(e)+1,this.getAttempts(e)}}class kt extends we{constructor(){super(new At)}}class Pt{onabort=null;aborted=!1;eventEmitter=new ce;toString(){return"[object AbortSignal]"}get[Symbol.toStringTag](){return"AbortSignal"}removeEventListener(...e){this.eventEmitter.off(...e)}addEventListener(...e){this.eventEmitter.on(...e)}dispatchEvent(e){const t={type:e,target:this},r=`on${e}`;"function"==typeof this[r]&&this[r](t),this.eventEmitter.emit(e,t)}}let Nt=class{signal=new Pt;abort(){this.signal.aborted||(this.signal.aborted=!0,this.signal.dispatchEvent("abort"))}toString(){return"[object AbortController]"}get[Symbol.toStringTag](){return"AbortController"}};const xt=async(...e)=>{if(globalThis.fetch)return globalThis.fetch(...e);if("string"!=typeof EdgeRuntime)return(await Promise.resolve().then(function(){return yr})).default(...e);throw new Error("Invariant: an edge runtime that does not support fetch should not exist")};class Dt{_fetch;constructor(e){this._fetch=e??xt}async makeRequest(e){const[t,r]=(e=>{if("cloudflare-worker"===wt())return[];const t=new(globalThis.AbortController||Nt),r=setTimeout(()=>{t.abort()},e);return r?.unref?.(),[t.signal,r]})(e.httpRequestTimeout),n={url:e.url,method:e.method,headers:e.headers,body:e.body,signal:t};return this._fetch(e.url,n).finally(()=>clearTimeout(r))}}class Kt extends Tt{_eventFactory;_isClosed=!1;_pendingEvents=0;_closeAndFlushDefaultTimeout;_publisher;_isFlushing=!1;_queue;ready;constructor(e){super(),(e=>{if(!e.writeKey)throw new z("writeKey","writeKey is missing.")})(e),this._eventFactory=new Ct,this._queue=new kt;const t=e.flushInterval??1e4;this._closeAndFlushDefaultTimeout=1.25*t;const{plugin:r,publisher:n}=((e,t)=>{const r=new Et(e,t);return{publisher:r,plugin:Rt(r)}})({writeKey:e.writeKey,host:e.host,path:e.path,maxRetries:e.maxRetries??3,flushAt:e.flushAt??e.maxEventsInBatch??15,httpRequestTimeout:e.httpRequestTimeout,disable:e.disable,flushInterval:t,httpClient:"function"==typeof e.httpClient?new Dt(e.httpClient):e.httpClient??new Dt,oauthSettings:e.oauthSettings},this);this._publisher=n,this.ready=this.register(r).then(()=>{}),this.emit("initialize",e),function(e){for(var t=e.constructor.prototype,r=0,n=Object.getOwnPropertyNames(t);r<n.length;r++){var o=n[r];if("constructor"!==o){var i=Object.getOwnPropertyDescriptor(e.constructor.prototype,o);i&&"function"==typeof i.value&&(e[o]=e[o].bind(e))}}}(this)}get VERSION(){return Re}closeAndFlush({timeout:e=this._closeAndFlushDefaultTimeout}={}){return this.flush({timeout:e,close:!0})}async flush({timeout:e,close:t=!1}={}){if(this._isFlushing)return void console.warn("Overlapping flush calls detected. Please wait for the previous flush to finish before calling .flush again");this._isFlushing=!0,t&&(this._isClosed=!0),this._publisher.flush(this._pendingEvents);const r=new Promise(e=>{this._pendingEvents?this.once("drained",()=>{e()}):e()}).finally(()=>{this._isFlushing=!1});return e?ie(r,e).catch(()=>{}):r}_dispatch(e,t){this._isClosed?this.emit("call_after_close",e):(this._pendingEvents++,St(e,this._queue,this,t).catch(e=>e).finally(()=>{this._pendingEvents--,this._pendingEvents||this.emit("drained")}))}alias({userId:e,previousId:t,context:r,timestamp:n,integrations:o,messageId:i},s){const a=this._eventFactory.alias(e,t,{context:r,integrations:o,timestamp:n,messageId:i});this._dispatch(a,s)}group({timestamp:e,groupId:t,userId:r,anonymousId:n,traits:o={},context:i,integrations:s,messageId:a},c){const u=this._eventFactory.group(t,o,{context:i,anonymousId:n,userId:r,timestamp:e,integrations:s,messageId:a});this._dispatch(u,c)}identify({userId:e,anonymousId:t,traits:r={},context:n,timestamp:o,integrations:i,messageId:s},a){const c=this._eventFactory.identify(e,r,{context:n,anonymousId:t,userId:e,timestamp:o,integrations:i,messageId:s});this._dispatch(c,a)}page({userId:e,anonymousId:t,category:r,name:n,properties:o,context:i,timestamp:s,integrations:a,messageId:c},u){const l=this._eventFactory.page(r??null,n??null,o,{context:i,anonymousId:t,userId:e,timestamp:s,integrations:a,messageId:c});this._dispatch(l,u)}screen({userId:e,anonymousId:t,category:r,name:n,properties:o,context:i,timestamp:s,integrations:a,messageId:c},u){const l=this._eventFactory.screen(r??null,n??null,o,{context:i,anonymousId:t,userId:e,timestamp:s,integrations:a,messageId:c});this._dispatch(l,u)}track({userId:e,anonymousId:t,event:r,properties:n,context:o,timestamp:i,integrations:s,messageId:a},c){const u=this._eventFactory.track(r,n,{context:o,userId:e,anonymousId:t,timestamp:i,integrations:s,messageId:a});this._dispatch(u,c)}register(...e){return this._queue.criticalTasks.run(async()=>{const t=It.system(),r=e.map(e=>this._queue.register(t,e,this));await Promise.all(r),this.emit("register",e.map(e=>e.name))})}async deregister(...e){const t=It.system(),r=e.map(e=>{const r=this._queue.plugins.find(t=>t.name===e);if(r)return this._queue.deregister(t,r,this);t.log("warn",`plugin ${e} not found`)});await Promise.all(r),this.emit("deregister",e)}}var Mt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function jt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ut,Lt,Ht,Wt,qt,Ft,$t,Vt,Bt,Jt,Gt,zt,Yt,Qt,Xt,Zt,er,tr={exports:{}};function rr(){if(Wt)return Ht;Wt=1;const e=Lt?Ut:(Lt=1,Ut={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t={};for(const r of Object.keys(e))t[e[r]]=r;const r={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};Ht=r;for(const e of Object.keys(r)){if(!("channels"in r[e]))throw new Error("missing channels property: "+e);if(!("labels"in r[e]))throw new Error("missing channel labels property: "+e);if(r[e].labels.length!==r[e].channels)throw new Error("channel and label counts mismatch: "+e);const{channels:t,labels:n}=r[e];delete r[e].channels,delete r[e].labels,Object.defineProperty(r[e],"channels",{value:t}),Object.defineProperty(r[e],"labels",{value:n})}function n(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}return r.rgb.hsl=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.min(t,r,n),i=Math.max(t,r,n),s=i-o;let a,c;i===o?a=0:t===i?a=(r-n)/s:r===i?a=2+(n-t)/s:n===i&&(a=4+(t-r)/s),a=Math.min(60*a,360),a<0&&(a+=360);const u=(o+i)/2;return c=i===o?0:u<=.5?s/(i+o):s/(2-i-o),[a,100*c,100*u]},r.rgb.hsv=function(e){let t,r,n,o,i;const s=e[0]/255,a=e[1]/255,c=e[2]/255,u=Math.max(s,a,c),l=u-Math.min(s,a,c),h=function(e){return(u-e)/6/l+.5};return 0===l?(o=0,i=0):(i=l/u,t=h(s),r=h(a),n=h(c),s===u?o=n-r:a===u?o=1/3+t-n:c===u&&(o=2/3+r-t),o<0?o+=1:o>1&&(o-=1)),[360*o,100*i,100*u]},r.rgb.hwb=function(e){const t=e[0],n=e[1];let o=e[2];const i=r.rgb.hsl(e)[0],s=1/255*Math.min(t,Math.min(n,o));return o=1-1/255*Math.max(t,Math.max(n,o)),[i,100*s,100*o]},r.rgb.cmyk=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.min(1-t,1-r,1-n);return[100*((1-t-o)/(1-o)||0),100*((1-r-o)/(1-o)||0),100*((1-n-o)/(1-o)||0),100*o]},r.rgb.keyword=function(r){const o=t[r];if(o)return o;let i,s=1/0;for(const t of Object.keys(e)){const o=n(r,e[t]);o<s&&(s=o,i=t)}return i},r.keyword.rgb=function(t){return e[t]},r.rgb.xyz=function(e){let t=e[0]/255,r=e[1]/255,n=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;return[100*(.4124*t+.3576*r+.1805*n),100*(.2126*t+.7152*r+.0722*n),100*(.0193*t+.1192*r+.9505*n)]},r.rgb.lab=function(e){const t=r.rgb.xyz(e);let n=t[0],o=t[1],i=t[2];n/=95.047,o/=100,i/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;return[116*o-16,500*(n-o),200*(o-i)]},r.hsl.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;let o,i,s;if(0===r)return s=255*n,[s,s,s];o=n<.5?n*(1+r):n+r-n*r;const a=2*n-o,c=[0,0,0];for(let e=0;e<3;e++)i=t+1/3*-(e-1),i<0&&i++,i>1&&i--,s=6*i<1?a+6*(o-a)*i:2*i<1?o:3*i<2?a+(o-a)*(2/3-i)*6:a,c[e]=255*s;return c},r.hsl.hsv=function(e){const t=e[0];let r=e[1]/100,n=e[2]/100,o=r;const i=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,o*=i<=1?i:2-i;return[t,100*(0===n?2*o/(i+o):2*r/(n+r)),100*((n+r)/2)]},r.hsv.rgb=function(e){const t=e[0]/60,r=e[1]/100;let n=e[2]/100;const o=Math.floor(t)%6,i=t-Math.floor(t),s=255*n*(1-r),a=255*n*(1-r*i),c=255*n*(1-r*(1-i));switch(n*=255,o){case 0:return[n,c,s];case 1:return[a,n,s];case 2:return[s,n,c];case 3:return[s,a,n];case 4:return[c,s,n];case 5:return[n,s,a]}},r.hsv.hsl=function(e){const t=e[0],r=e[1]/100,n=e[2]/100,o=Math.max(n,.01);let i,s;s=(2-r)*n;const a=(2-r)*o;return i=r*o,i/=a<=1?a:2-a,i=i||0,s/=2,[t,100*i,100*s]},r.hwb.rgb=function(e){const t=e[0]/360;let r=e[1]/100,n=e[2]/100;const o=r+n;let i;o>1&&(r/=o,n/=o);const s=Math.floor(6*t),a=1-n;i=6*t-s,1&s&&(i=1-i);const c=r+i*(a-r);let u,l,h;switch(s){default:case 6:case 0:u=a,l=c,h=r;break;case 1:u=c,l=a,h=r;break;case 2:u=r,l=a,h=c;break;case 3:u=r,l=c,h=a;break;case 4:u=c,l=r,h=a;break;case 5:u=a,l=r,h=c}return[255*u,255*l,255*h]},r.cmyk.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100,o=e[3]/100;return[255*(1-Math.min(1,t*(1-o)+o)),255*(1-Math.min(1,r*(1-o)+o)),255*(1-Math.min(1,n*(1-o)+o))]},r.xyz.rgb=function(e){const t=e[0]/100,r=e[1]/100,n=e[2]/100;let o,i,s;return o=3.2406*t+-1.5372*r+-.4986*n,i=-.9689*t+1.8758*r+.0415*n,s=.0557*t+-.204*r+1.057*n,o=o>.0031308?1.055*o**(1/2.4)-.055:12.92*o,i=i>.0031308?1.055*i**(1/2.4)-.055:12.92*i,s=s>.0031308?1.055*s**(1/2.4)-.055:12.92*s,o=Math.min(Math.max(0,o),1),i=Math.min(Math.max(0,i),1),s=Math.min(Math.max(0,s),1),[255*o,255*i,255*s]},r.xyz.lab=function(e){let t=e[0],r=e[1],n=e[2];t/=95.047,r/=100,n/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;return[116*r-16,500*(t-r),200*(r-n)]},r.lab.xyz=function(e){let t,r,n;r=(e[0]+16)/116,t=e[1]/500+r,n=r-e[2]/200;const o=r**3,i=t**3,s=n**3;return r=o>.008856?o:(r-16/116)/7.787,t=i>.008856?i:(t-16/116)/7.787,n=s>.008856?s:(n-16/116)/7.787,t*=95.047,r*=100,n*=108.883,[t,r,n]},r.lab.lch=function(e){const t=e[0],r=e[1],n=e[2];let o;o=360*Math.atan2(n,r)/2/Math.PI,o<0&&(o+=360);return[t,Math.sqrt(r*r+n*n),o]},r.lch.lab=function(e){const t=e[0],r=e[1],n=e[2]/360*2*Math.PI;return[t,r*Math.cos(n),r*Math.sin(n)]},r.rgb.ansi16=function(e,t=null){const[n,o,i]=e;let s=null===t?r.rgb.hsv(e)[2]:t;if(s=Math.round(s/50),0===s)return 30;let a=30+(Math.round(i/255)<<2|Math.round(o/255)<<1|Math.round(n/255));return 2===s&&(a+=60),a},r.hsv.ansi16=function(e){return r.rgb.ansi16(r.hsv.rgb(e),e[2])},r.rgb.ansi256=function(e){const t=e[0],r=e[1],n=e[2];if(t===r&&r===n)return t<8?16:t>248?231:Math.round((t-8)/247*24)+232;return 16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},r.ansi16.rgb=function(e){let t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];const r=.5*(1+~~(e>50));return[(1&t)*r*255,(t>>1&1)*r*255,(t>>2&1)*r*255]},r.ansi256.rgb=function(e){if(e>=232){const t=10*(e-232)+8;return[t,t,t]}let t;e-=16;return[Math.floor(e/36)/5*255,Math.floor((t=e%36)/6)/5*255,t%6/5*255]},r.rgb.hex=function(e){const t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},r.hex.rgb=function(e){const t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let r=t[0];3===t[0].length&&(r=r.split("").map(e=>e+e).join(""));const n=parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},r.rgb.hcg=function(e){const t=e[0]/255,r=e[1]/255,n=e[2]/255,o=Math.max(Math.max(t,r),n),i=Math.min(Math.min(t,r),n),s=o-i;let a,c;return a=s<1?i/(1-s):0,c=s<=0?0:o===t?(r-n)/s%6:o===r?2+(n-t)/s:4+(t-r)/s,c/=6,c%=1,[360*c,100*s,100*a]},r.hsl.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=r<.5?2*t*r:2*t*(1-r);let o=0;return n<1&&(o=(r-.5*n)/(1-n)),[e[0],100*n,100*o]},r.hsv.hcg=function(e){const t=e[1]/100,r=e[2]/100,n=t*r;let o=0;return n<1&&(o=(r-n)/(1-n)),[e[0],100*n,100*o]},r.hcg.rgb=function(e){const t=e[0]/360,r=e[1]/100,n=e[2]/100;if(0===r)return[255*n,255*n,255*n];const o=[0,0,0],i=t%1*6,s=i%1,a=1-s;let c=0;switch(Math.floor(i)){case 0:o[0]=1,o[1]=s,o[2]=0;break;case 1:o[0]=a,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=s;break;case 3:o[0]=0,o[1]=a,o[2]=1;break;case 4:o[0]=s,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=a}return c=(1-r)*n,[255*(r*o[0]+c),255*(r*o[1]+c),255*(r*o[2]+c)]},r.hcg.hsv=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);let n=0;return r>0&&(n=t/r),[e[0],100*n,100*r]},r.hcg.hsl=function(e){const t=e[1]/100,r=e[2]/100*(1-t)+.5*t;let n=0;return r>0&&r<.5?n=t/(2*r):r>=.5&&r<1&&(n=t/(2*(1-r))),[e[0],100*n,100*r]},r.hcg.hwb=function(e){const t=e[1]/100,r=t+e[2]/100*(1-t);return[e[0],100*(r-t),100*(1-r)]},r.hwb.hcg=function(e){const t=e[1]/100,r=1-e[2]/100,n=r-t;let o=0;return n<1&&(o=(r-n)/(1-n)),[e[0],100*n,100*o]},r.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},r.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},r.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},r.gray.hsl=function(e){return[0,0,e[0]]},r.gray.hsv=r.gray.hsl,r.gray.hwb=function(e){return[0,100,e[0]]},r.gray.cmyk=function(e){return[0,0,0,e[0]]},r.gray.lab=function(e){return[e[0],0,0]},r.gray.hex=function(e){const t=255&Math.round(e[0]/100*255),r=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(r.length)+r},r.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]},Ht}function nr(){if(Ft)return qt;Ft=1;const e=rr();function t(t){const r=function(){const t={},r=Object.keys(e);for(let e=r.length,n=0;n<e;n++)t[r[n]]={distance:-1,parent:null};return t}(),n=[t];for(r[t].distance=0;n.length;){const t=n.pop(),o=Object.keys(e[t]);for(let e=o.length,i=0;i<e;i++){const e=o[i],s=r[e];-1===s.distance&&(s.distance=r[t].distance+1,s.parent=t,n.unshift(e))}}return r}function r(e,t){return function(r){return t(e(r))}}function n(t,n){const o=[n[t].parent,t];let i=e[n[t].parent][t],s=n[t].parent;for(;n[s].parent;)o.unshift(n[s].parent),i=r(e[n[s].parent][s],i),s=n[s].parent;return i.conversion=o,i}return qt=function(e){const r=t(e),o={},i=Object.keys(r);for(let e=i.length,t=0;t<e;t++){const e=i[t];null!==r[e].parent&&(o[e]=n(e,r))}return o}}function or(){if(Vt)return $t;Vt=1;const e=rr(),t=nr(),r={};return Object.keys(e).forEach(n=>{r[n]={},Object.defineProperty(r[n],"channels",{value:e[n].channels}),Object.defineProperty(r[n],"labels",{value:e[n].labels});const o=t(n);Object.keys(o).forEach(e=>{const t=o[e];r[n][e]=function(e){const t=function(...t){const r=t[0];if(null==r)return r;r.length>1&&(t=r);const n=e(t);if("object"==typeof n)for(let e=n.length,t=0;t<e;t++)n[t]=Math.round(n[t]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}(t),r[n][e].raw=function(e){const t=function(...t){const r=t[0];return null==r?r:(r.length>1&&(t=r),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(t)})}),$t=r}function ir(){return Bt||(Bt=1,function(e){const t=(e,t)=>(...r)=>`[${e(...r)+t}m`,r=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};5;${n}m`},n=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};2;${n[0]};${n[1]};${n[2]}m`},o=e=>e,i=(e,t,r)=>[e,t,r],s=(e,t,r)=>{Object.defineProperty(e,t,{get:()=>{const n=r();return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})};let a;const c=(e,t,r,n)=>{void 0===a&&(a=or());const o=n?10:0,i={};for(const[n,s]of Object.entries(a)){const a="ansi16"===n?"ansi":n;n===t?i[a]=e(r,o):"object"==typeof s&&(i[a]=e(s[t],o))}return i};Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,a={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};a.color.gray=a.color.blackBright,a.bgColor.bgGray=a.bgColor.bgBlackBright,a.color.grey=a.color.blackBright,a.bgColor.bgGrey=a.bgColor.bgBlackBright;for(const[t,r]of Object.entries(a)){for(const[t,n]of Object.entries(r))a[t]={open:`[${n[0]}m`,close:`[${n[1]}m`},r[t]=a[t],e.set(n[0],n[1]);Object.defineProperty(a,t,{value:r,enumerable:!1})}return Object.defineProperty(a,"codes",{value:e,enumerable:!1}),a.color.close="[39m",a.bgColor.close="[49m",s(a.color,"ansi",()=>c(t,"ansi16",o,!1)),s(a.color,"ansi256",()=>c(r,"ansi256",o,!1)),s(a.color,"ansi16m",()=>c(n,"rgb",i,!1)),s(a.bgColor,"ansi",()=>c(t,"ansi16",o,!0)),s(a.bgColor,"ansi256",()=>c(r,"ansi256",o,!0)),s(a.bgColor,"ansi16m",()=>c(n,"rgb",i,!0)),a}})}(tr)),tr.exports}function sr(e,t,r){for(var n in void 0===t&&(t=""),void 0===r&&(r={}),e){var o=t?"".concat(t,".").concat(n):n;"object"==typeof e[n]&&null!==e[n]?sr(e[n],o,r):r[o]=e[n]}return r}!function(){if(er)return Zt;er=1;const e=ir(),{stdout:t,stderr:r}=Gt?Jt:(Gt=1,Jt={stdout:!1,stderr:!1}),{stringReplaceAll:n,stringEncaseCRLFWithFirstIndex:o}=Yt?zt:(Yt=1,zt={stringReplaceAll:(e,t,r)=>{let n=e.indexOf(t);if(-1===n)return e;const o=t.length;let i=0,s="";do{s+=e.substr(i,n-i)+t+r,i=n+o,n=e.indexOf(t,i)}while(-1!==n);return s+=e.substr(i),s},stringEncaseCRLFWithFirstIndex:(e,t,r,n)=>{let o=0,i="";do{const s="\r"===e[n-1];i+=e.substr(o,(s?n-1:n)-o)+t+(s?"\r\n":"\n")+r,o=n+1,n=e.indexOf("\n",o)}while(-1!==n);return i+=e.substr(o),i}}),{isArray:i}=Array,s=["ansi","ansi","ansi256","ansi16m"],a=Object.create(null);class c{constructor(e){return u(e)}}const u=e=>{const r={};return((e,r={})=>{if(r.level&&!(Number.isInteger(r.level)&&r.level>=0&&r.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=t?t.level:0;e.level=void 0===r.level?n:r.level})(r,e),r.template=(...e)=>y(r.template,...e),Object.setPrototypeOf(r,l.prototype),Object.setPrototypeOf(r.template,r),r.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},r.template.Instance=c,r.template};function l(e){return u(e)}for(const[t,r]of Object.entries(e))a[t]={get(){const e=f(this,p(r.open,r.close,this._styler),this._isEmpty);return Object.defineProperty(this,t,{value:e}),e}};a.visible={get(){const e=f(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:e}),e}};const h=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(const t of h)a[t]={get(){const{level:r}=this;return function(...n){const o=p(e.color[s[r]][t](...n),e.color.close,this._styler);return f(this,o,this._isEmpty)}}};for(const t of h){a["bg"+t[0].toUpperCase()+t.slice(1)]={get(){const{level:r}=this;return function(...n){const o=p(e.bgColor[s[r]][t](...n),e.bgColor.close,this._styler);return f(this,o,this._isEmpty)}}}}const d=Object.defineProperties(()=>{},{...a,level:{enumerable:!0,get(){return this._generator.level},set(e){this._generator.level=e}}}),p=(e,t,r)=>{let n,o;return void 0===r?(n=e,o=t):(n=r.openAll+e,o=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:o,parent:r}},f=(e,t,r)=>{const n=(...e)=>i(e[0])&&i(e[0].raw)?g(n,y(n,...e)):g(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,d),n._generator=e,n._styler=t,n._isEmpty=r,n},g=(e,t)=>{if(e.level<=0||!t)return e._isEmpty?"":t;let r=e._styler;if(void 0===r)return t;const{openAll:i,closeAll:s}=r;if(-1!==t.indexOf(""))for(;void 0!==r;)t=n(t,r.close,r.open),r=r.parent;const a=t.indexOf("\n");return-1!==a&&(t=o(t,s,i,a)),i+t+s};let m;const y=(e,...t)=>{const[r]=t;if(!i(r)||!i(r.raw))return t.join(" ");const n=t.slice(1),o=[r.raw[0]];for(let e=1;e<r.length;e++)o.push(String(n[e-1]).replace(/[{}\\]/g,"\\$&"),String(r.raw[e]));return void 0===m&&(m=function(){if(Xt)return Qt;Xt=1;const e=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,t=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,r=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,n=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,o=new Map([["n","\n"],["r","\r"],["t","\t"],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e",""],["a",""]]);function i(e){const t="u"===e[0],r="{"===e[1];return t&&!r&&5===e.length||"x"===e[0]&&3===e.length?String.fromCharCode(parseInt(e.slice(1),16)):t&&r?String.fromCodePoint(parseInt(e.slice(2,-1),16)):o.get(e)||e}function s(e,t){const o=[],s=t.trim().split(/\s*,\s*/g);let a;for(const t of s){const s=Number(t);if(Number.isNaN(s)){if(!(a=t.match(r)))throw new Error(`Invalid Chalk template style argument: ${t} (in style '${e}')`);o.push(a[2].replace(n,(e,t,r)=>t?i(t):r))}else o.push(s)}return o}function a(e){t.lastIndex=0;const r=[];let n;for(;null!==(n=t.exec(e));){const e=n[1];if(n[2]){const t=s(e,n[2]);r.push([e].concat(t))}else r.push([e])}return r}function c(e,t){const r={};for(const e of t)for(const t of e.styles)r[t[0]]=e.inverse?null:t.slice(1);let n=e;for(const[e,t]of Object.entries(r))if(Array.isArray(t)){if(!(e in n))throw new Error(`Unknown Chalk style: ${e}`);n=t.length>0?n[e](...t):n[e]}return n}return Qt=(t,r)=>{const n=[],o=[];let s=[];if(r.replace(e,(e,r,u,l,h,d)=>{if(r)s.push(i(r));else if(l){const e=s.join("");s=[],o.push(0===n.length?e:c(t,n)(e)),n.push({inverse:u,styles:a(l)})}else if(h){if(0===n.length)throw new Error("Found extraneous } in Chalk template literal");o.push(c(t,n)(s.join(""))),s=[],n.pop()}else s.push(d)}),o.push(s.join("")),n.length>0){const e=`Chalk template literal is missing ${n.length} closing bracket${1===n.length?"":"s"} (\`}\`)`;throw new Error(e)}return o.join("")}}()),m(e,o.join(""))};Object.defineProperties(l.prototype,a);const v=l();v.supportsColor=t,v.stderr=l({level:r?r.level:0}),v.stderr.supportsColor=r,Zt=v}();var ar="1.51.3-next.2",cr="https://copilotkit.gateway.scarf.sh/".concat(ar),ur=function(){function e(){}return e.prototype.logEvent=function(e){return c(this,void 0,void 0,function(){var t,r,n,o,i;return u(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),t=new AbortController,r=setTimeout(function(){return t.abort()},3e3),n=new URLSearchParams,Object.entries(e).forEach(function(e){var t=e[0],r=e[1];null!=r&&n.append(t,String(r))}),o="".concat(cr,"?").concat(n.toString()),[4,fetch(o,{method:"GET",signal:t.signal})];case 1:if(i=s.sent(),clearTimeout(r),!i.ok)throw new Error("HTTP error! status: ".concat(i.status));return[3,3];case 2:return s.sent(),[3,3];case 3:return[2]}})})},e}(),lr=new ur;function hr(){return"true"===process.env.COPILOTKIT_TELEMETRY_DISABLED||"1"===process.env.COPILOTKIT_TELEMETRY_DISABLED||"true"===process.env.DO_NOT_TRACK||"1"===process.env.DO_NOT_TRACK}var dr,pr=function(){function e(e){var t=e.packageName,n=e.packageVersion,o=e.telemetryDisabled;e.telemetryBaseUrl;var i=e.sampleRate;if(this.globalProperties={},this.cloudConfiguration=null,this.telemetryDisabled=!1,this.sampleRate=.05,this.anonymousId="anon_".concat(r.v4()),this.packageName=t,this.packageVersion=n,this.telemetryDisabled=o||hr(),!this.telemetryDisabled){this.setSampleRate(i);var s=process.env.COPILOTKIT_SEGMENT_WRITE_KEY||"n7XAZtQCGS2v1vvBy3LgBCv2h3Y8whja";this.segment=new Kt({writeKey:s}),this.setGlobalProperties({"copilotkit.package.name":t,"copilotkit.package.version":n})}}return e.prototype.shouldSendEvent=function(){return Math.random()<this.sampleRate},e.prototype.capture=function(e,t){return c(this,void 0,void 0,function(){var r,n,o;return u(this,function(i){switch(i.label){case 0:return this.shouldSendEvent()&&this.segment?(r=sr(t),n=a(a({},this.globalProperties),r),o=Object.keys(n).sort().reduce(function(e,t){return e[t]=n[t],e},{}),this.segment.track({anonymousId:this.anonymousId,event:e,properties:a({},o)}),[4,lr.logEvent({event:e})]):[2];case 1:return i.sent(),[2]}})})},e.prototype.setGlobalProperties=function(e){var t=sr(e);this.globalProperties=a(a({},this.globalProperties),t)},e.prototype.setCloudConfiguration=function(e){this.cloudConfiguration=e,this.setGlobalProperties({cloud:{publicApiKey:e.publicApiKey,baseUrl:e.baseUrl}})},e.prototype.setSampleRate=function(e){var t;if(t=null!=e?e:.05,process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE&&(t=parseFloat(process.env.COPILOTKIT_TELEMETRY_SAMPLE_RATE)),t<0||t>1)throw new Error("Sample rate must be between 0 and 1");this.sampleRate=t,this.setGlobalProperties({sampleRate:this.sampleRate,sampleRateAdjustmentFactor:1-this.sampleRate,sampleWeight:1/this.sampleRate})},e}(),fr=ar,gr={exports:{}};var mr=jt((dr||(dr=1,function(e,t){var r=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==Mt)return Mt;throw new Error("unable to locate global object")}();e.exports=t=r.fetch,r.fetch&&(t.default=r.fetch.bind(r)),t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response}(gr,gr.exports)),gr.exports)),yr=Object.freeze({__proto__:null,default:mr});e.BANNER_ERROR_NAMES=w,e.COPILOTKIT_VERSION=fr,e.COPILOT_CLOUD_API_URL=B,e.COPILOT_CLOUD_CHAT_URL=J,e.COPILOT_CLOUD_ERROR_NAMES=R,e.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER="X-CopilotCloud-Public-Api-Key",e.COPILOT_CLOUD_VERSION="v1",e.ConfigurationError=M,e.ConsoleColors=h,e.ConsoleStyles=d,e.CopilotKitAgentDiscoveryError=x,e.CopilotKitApiDiscoveryError=P,e.CopilotKitError=S,e.CopilotKitLowLevelError=D,e.CopilotKitMisuseError=T,e.CopilotKitRemoteEndpointDiscoveryError=N,e.CopilotKitVersionMismatchError=k,e.ERROR_CONFIG=I,e.ERROR_NAMES=_,e.MissingPublicApiKeyError=j,e.ResolvedCopilotKitError=K,e.TelemetryClient=pr,e.UpgradeRequiredError=U,e.actionParametersToJsonSchema=W,e.convertJsonSchemaToZodSchema=$,e.dataToUUID=function(e,t){var n="e4b01160-ff74-4c6e-9b27-d53cd930fe8e",o=t?r.v5(t,n):n,i="string"==typeof e?e:JSON.stringify(V(e));return r.v5(i,o)},e.ensureStructuredError=function(e,t){return L(e)?e:t(e)},e.executeConditions=function(e){var t=e.conditions,r=e.value;return!(null==t?void 0:t.length)||t.every(function(e){return o(e,r)})},e.getPossibleVersionMismatch=function(e){return c(this,arguments,void 0,function(e){var t=e.runtimeVersion,r=e.runtimeClientGqlVersion;return u(this,function(e){return t&&""!==t&&r&&(fr!==t||fr!==r||t!==r)?[2,{runtimeVersion:t,runtimeClientGqlVersion:r,reactCoreVersion:fr,message:A({runtimeVersion:t,runtimeClientGqlVersion:r,reactCoreVersion:fr})}]:[2]})})},e.getZodParameters=function(e){return e?$(W(e),!0):n.z.object({})},e.isMacOS=function(){return/Mac|iMac|Macintosh/i.test(navigator.userAgent)},e.isStructuredCopilotKitError=L,e.isTelemetryDisabled=hr,e.isValidUUID=function(e){return r.validate(e)},e.jsonSchemaToActionParameters=function(e){if("object"!==e.type||!e.properties)return[];for(var t=[],r=e.required||[],n=0,o=Object.entries(e.properties);n<o.length;n++){var i=o[n],s=i[0],a=q(s,i[1],r.includes(s));t.push(a)}return t},e.logCopilotKitPlatformMessage=p,e.logStyled=g,e.parseJson=function(e,t){void 0===t&&(t="unset");try{return JSON.parse(e)}catch(e){return"unset"===t?null:t}},e.publicApiKeyRequired=f,e.randomId=function(){return"ck-"+r.v4()},e.randomUUID=function(){return r.v4()},e.readBody=function(e){return c(this,void 0,void 0,function(){var t,r,n,o,i,s,a,c,l,h,d,p;return u(this,function(u){switch(u.label){case 0:if("GET"===(t="method"in e?e.method.toUpperCase():void 0)||"HEAD"===t)return[2,void 0];if(!("body"in e)||null==e.body)return[2,void 0];u.label=1;case 1:return u.trys.push([1,3,,14]),[4,e.clone().json()];case 2:return[2,u.sent()];case 3:u.sent(),u.label=4;case 4:return u.trys.push([4,6,,13]),[4,e.clone().text()];case 5:if(r=u.sent(),0===(d=r.trim()).length)return[2,r];if(d.startsWith("{")||d.startsWith("["))try{return[2,JSON.parse(d)]}catch(e){return[2,r]}return[2,r];case 6:u.sent(),u.label=7;case 7:if(u.trys.push([7,11,,12]),n=e.clone(),!(o=null!==(p=n.body)&&void 0!==p?p:null))return[2,void 0];i=o.getReader(),s=new TextDecoder,a="",u.label=8;case 8:return[4,i.read()];case 9:return c=u.sent(),l=c.done,h=c.value,l?[3,10]:(a+="string"==typeof h?h:s.decode(h,{stream:!0}),[3,8]);case 10:if(a+=s.decode(),0===(d=a.trim()).length)return[2,a];if(d.startsWith("{")||d.startsWith("["))try{return[2,JSON.parse(d)]}catch(e){return[2,a]}return[2,a];case 11:return u.sent(),[2,void 0];case 12:return[3,13];case 13:return[3,14];case 14:return[2]}})})},e.styledConsole=b,e.tryMap=function(e,t){return e.reduce(function(e,r,n,o){try{e.push(t(r,n,o))}catch(e){console.error(e)}return e},[])}});
|
|
2
|
+
//# sourceMappingURL=index.umd.js.map
|