@mission_sciences/provider-sdk 0.1.2 → 0.2.0-dev.b8394a3
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/README.md +365 -416
- package/dist/index.d.ts +3 -1
- package/dist/marketplace-sdk.es.js +9 -5
- package/dist/marketplace-sdk.es.js.map +1 -1
- package/dist/marketplace-sdk.umd.js +1 -1
- package/dist/marketplace-sdk.umd.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).MarketplaceSDK={})}(this,function(e){"use strict";var t,s,n,i,o,r,a,c,h,d,l,g,u,p,m=Object.defineProperty,y=e=>{throw TypeError(e)},f=(e,t,s)=>((e,t,s)=>t in e?m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s),w=(e,t,s)=>t.has(e)||y("Cannot "+s),S=(e,t,s)=>(w(e,t,"read from private field"),s?s.call(e):t.get(e)),b=(e,t,s)=>t.has(e)?y("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),E=(e,t,s,n)=>(w(e,t,"write to private field"),n?n.call(e,s):t.set(e,s),s);class v extends Error{constructor(e,t,s){super(e),this.code=t,this.statusCode=s,this.name="SDKError",Error.captureStackTrace&&Error.captureStackTrace(this,v)}}class k{static decode(e){if(!e||"string"!=typeof e)throw new v("Invalid JWT token format","INVALID_TOKEN");const t=e.split(".");if(3!==t.length)throw new v("Malformed JWT token - expected 3 parts","MALFORMED_TOKEN");try{const e=t[1],s=this.base64UrlDecode(e);return JSON.parse(s)}catch(s){throw new v(`Failed to decode JWT payload: ${s instanceof Error?s.message:"Unknown error"}`,"DECODE_ERROR")}}static decodeHeader(e){if(!e||"string"!=typeof e)throw new v("Invalid JWT token format","INVALID_TOKEN");const t=e.split(".");if(3!==t.length)throw new v("Malformed JWT token - expected 3 parts","MALFORMED_TOKEN");try{const e=t[0],s=this.base64UrlDecode(e);return JSON.parse(s)}catch(s){throw new v(`Failed to decode JWT header: ${s instanceof Error?s.message:"Unknown error"}`,"DECODE_ERROR")}}static extractClaim(e,t){return this.decode(e)[t]}static isExpired(e){const t=this.decode(e).exp;return!!t&&Date.now()>=1e3*t}static getTimeRemaining(e){const t=this.decode(e).exp;if(!t)return 0;const s=t-Math.floor(Date.now()/1e3);return Math.max(0,s)}static base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const s=t.length%4;s&&(t+="=".repeat(4-s));try{if("undefined"!=typeof Buffer)return Buffer.from(t,"base64").toString("utf-8");if("undefined"!=typeof atob)return atob(t);throw new Error("No base64 decoding available")}catch(n){throw new v("Invalid base64 encoding","ENCODING_ERROR")}}}const T=new TextEncoder,I=new TextDecoder;function x(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:I.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=I.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return function(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),s=new Uint8Array(t.length);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return s}(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}class A extends Error{constructor(e,t){super(e,t),f(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}f(A,"code","ERR_JOSE_GENERIC");class $ extends A{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),f(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),f(this,"claim"),f(this,"reason"),f(this,"payload"),this.claim=s,this.reason=n,this.payload=t}}f($,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class R extends A{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),f(this,"code","ERR_JWT_EXPIRED"),f(this,"claim"),f(this,"reason"),f(this,"payload"),this.claim=s,this.reason=n,this.payload=t}}f(R,"code","ERR_JWT_EXPIRED");class C extends A{constructor(){super(...arguments),f(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}f(C,"code","ERR_JOSE_ALG_NOT_ALLOWED");class D extends A{constructor(){super(...arguments),f(this,"code","ERR_JOSE_NOT_SUPPORTED")}}f(D,"code","ERR_JOSE_NOT_SUPPORTED");class M extends A{constructor(){super(...arguments),f(this,"code","ERR_JWS_INVALID")}}f(M,"code","ERR_JWS_INVALID");class W extends A{constructor(){super(...arguments),f(this,"code","ERR_JWT_INVALID")}}f(W,"code","ERR_JWT_INVALID");class _ extends A{constructor(){super(...arguments),f(this,"code","ERR_JWKS_INVALID")}}f(_,"code","ERR_JWKS_INVALID");class K extends A{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),f(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}f(K,"code","ERR_JWKS_NO_MATCHING_KEY");class O extends(s=A,t=Symbol.asyncIterator,s){constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),f(this,t),f(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}f(O,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class P extends A{constructor(e="request timed out",t){super(e,t),f(this,"code","ERR_JWKS_TIMEOUT")}}f(P,"code","ERR_JWKS_TIMEOUT");class H extends A{constructor(e="signature verification failed",t){super(e,t),f(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}function j(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function J(e,t){return e.name===t}function N(e){return parseInt(e.name.slice(4),10)}function L(e,t,s){switch(t){case"HS256":case"HS384":case"HS512":{if(!J(e.algorithm,"HMAC"))throw j("HMAC");const s=parseInt(t.slice(2),10);if(N(e.algorithm.hash)!==s)throw j(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!J(e.algorithm,"RSASSA-PKCS1-v1_5"))throw j("RSASSA-PKCS1-v1_5");const s=parseInt(t.slice(2),10);if(N(e.algorithm.hash)!==s)throw j(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!J(e.algorithm,"RSA-PSS"))throw j("RSA-PSS");const s=parseInt(t.slice(2),10);if(N(e.algorithm.hash)!==s)throw j(`SHA-${s}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if(!J(e.algorithm,"Ed25519"))throw j("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!J(e.algorithm,t))throw j(t);break;case"ES256":case"ES384":case"ES512":{if(!J(e.algorithm,"ECDSA"))throw j("ECDSA");const s=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!==s)throw j(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}(e,s)}function F(e,t,...s){if((s=s.filter(Boolean)).length>2){const t=s.pop();e+=`one of type ${s.join(", ")}, or ${t}.`}else 2===s.length?e+=`one of type ${s[0]} or ${s[1]}.`:e+=`of type ${s[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}f(H,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function U(e,t,...s){return F(`Key for the ${e} algorithm must be `,t,...s)}function z(e){return"CryptoKey"===e?.[Symbol.toStringTag]}function B(e){return"KeyObject"===e?.[Symbol.toStringTag]}const V=e=>z(e)||B(e);const G=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 s=e;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(e)===s};const q=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:s}=function(e){let t,s;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},s=e.priv?["sign"]:["verify"];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},s=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}`},s=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},s=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},s=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},s=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},s=e.d?["deriveBits"]:[];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new D('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:s}}(e),n={...e};return"AKP"!==n.kty&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??(!e.d&&!e.priv),e.key_ops??s)};function Y(e){return G(e)&&"string"==typeof e.kty}let X;const Z=async(e,t,s,n=!1)=>{X||(X=new WeakMap);let i=X.get(e);if(i?.[s])return i[s];const o=await q({...t,alg:s});return n&&Object.freeze(e),i?i[s]=o:X.set(e,{[s]:o}),o},Q=async(e,t)=>{if(e instanceof Uint8Array)return e;if(z(e))return e;if(B(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{X||(X=new WeakMap);let s=X.get(e);if(s?.[t])return s[t];const n="public"===e.type,i=!!n;let o;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}o=e.toCryptoKey(e.asymmetricKeyType,i,n?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},i,n?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},i,[n?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const s=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!s)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===s&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:s},i,[n?"verify":"sign"])),"ES384"===t&&"P-384"===s&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:s},i,[n?"verify":"sign"])),"ES512"===t&&"P-521"===s&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:s},i,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:s},i,n?[]:["deriveBits"]))}if(!o)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return s?s[t]=o:X.set(e,{[t]:o}),o})(e,t)}catch(s){if(s instanceof TypeError)throw s}let n=e.export({format:"jwk"});return Z(e,n,t)}if(Y(e))return e.k?x(e.k):Z(e,e,t,!0);throw new Error("unreachable")},ee=e=>e?.[Symbol.toStringTag],te=(e,t,s)=>{if(void 0!==t.use){let e;switch(s){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"verify"===s:case"dir"===e:case e.includes("CBC-HS"):n=s;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"unwrapKey":s;break;case"encrypt"===s:n="wrapKey";break;case"decrypt"===s:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&!1===t.key_ops?.includes?.(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},se=(e,t,s)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?((e,t,s)=>{if(!(t instanceof Uint8Array)){if(Y(t)){if(function(e){return"oct"===e.kty&&"string"==typeof e.k}(t)&&te(e,t,s))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(!V(t))throw new TypeError(U(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${ee(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,s):((e,t,s)=>{if(Y(t))switch(s){case"decrypt":case"sign":if(function(e){return"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d)}(t)&&te(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d&&void 0===e.priv}(t)&&te(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!V(t))throw new TypeError(U(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${ee(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(s){case"sign":throw new TypeError(`${ee(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ee(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(s){case"verify":throw new TypeError(`${ee(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ee(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,s)},ne=async(e,t,s)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(((e,...t)=>F("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[s])}return L(t,e,s),t},ie=async(e,t,s,n)=>{const i=await ne(e,t,"verify");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:s}=t.algorithm;if("number"!=typeof s||s<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,i);const o=((e,t)=>{const s=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new D(`alg ${e} is not supported either by JOSE or your javascript runtime`)}})(e,i.algorithm);try{return await crypto.subtle.verify(o,i,s,n)}catch{return!1}};async function oe(e,t,s){if(!G(e))throw new M("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new M('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new M("JWS Protected Header incorrect type");if(void 0===e.payload)throw new M("JWS Payload missing");if("string"!=typeof e.signature)throw new M("JWS Signature missing or incorrect type");if(void 0!==e.header&&!G(e.header))throw new M("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=x(e.protected);n=JSON.parse(I.decode(t))}catch{throw new M("JWS Protected Header is invalid")}if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let s;for(const n of t){const e=Object.keys(n);if(s&&0!==s.size)for(const t of e){if(s.has(t))return!1;s.add(t)}else s=new Set(e)}return!0})(n,e.header))throw new M("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=((e,t,s,n,i)=>{if(void 0!==i.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 o;o=void 0!==s?new Map([...Object.entries(s),...t.entries()]):t;for(const r of n.crit){if(!o.has(r))throw new D(`Extension Header Parameter "${r}" is not recognized`);if(void 0===i[r])throw new e(`Extension Header Parameter "${r}" is missing`);if(o.get(r)&&void 0===n[r])throw new e(`Extension Header Parameter "${r}" MUST be integrity protected`)}return new Set(n.crit)})(M,new Map([["b64",!0]]),s?.crit,n,i);let r=!0;if(o.has("b64")&&(r=n.b64,"boolean"!=typeof r))throw new M('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if("string"!=typeof a||!a)throw new M('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=s&&((e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)})("algorithms",s.algorithms);if(c&&!c.has(a))throw new C('"alg" (Algorithm) Header Parameter value not allowed');if(r){if("string"!=typeof e.payload)throw new M("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new M("JWS Payload must be a string or an Uint8Array instance");let h=!1;"function"==typeof t&&(t=await t(n,e),h=!0),se(a,t,"verify");const d=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),s=new Uint8Array(t);let n=0;for(const i of e)s.set(i,n),n+=i.length;return s}(T.encode(e.protected??""),T.encode("."),"string"==typeof e.payload?T.encode(e.payload):e.payload);let l;try{l=x(e.signature)}catch{throw new M("Failed to base64url decode the signature")}const g=await Q(t,a);if(!(await ie(a,g,l,d)))throw new H;let u;if(r)try{u=x(e.payload)}catch{throw new M("Failed to base64url decode the payload")}else u="string"==typeof e.payload?T.encode(e.payload):e.payload;const p={payload:u};return void 0!==e.protected&&(p.protectedHeader=n),void 0!==e.header&&(p.unprotectedHeader=e.header),h?{...p,key:g}:p}const re=86400,ae=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ce=e=>{const t=ae.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const s=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*s);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*s);break;case"day":case"days":case"d":n=Math.round(s*re);break;case"week":case"weeks":case"w":n=Math.round(604800*s);break;default:n=Math.round(31557600*s)}return"-"===t[1]||"ago"===t[4]?-n:n},he=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;function de(e,t,s={}){let n;try{n=JSON.parse(I.decode(t))}catch{}if(!G(n))throw new W("JWT Claims Set must be a top-level JSON object");const{typ:i}=s;if(i&&("string"!=typeof e.typ||he(e.typ)!==he(i)))throw new $('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:o=[],issuer:r,subject:a,audience:c,maxTokenAge:h}=s,d=[...o];void 0!==h&&d.push("iat"),void 0!==c&&d.push("aud"),void 0!==a&&d.push("sub"),void 0!==r&&d.push("iss");for(const f of new Set(d.reverse()))if(!(f in n))throw new $(`missing required "${f}" claim`,n,f,"missing");if(r&&!(Array.isArray(r)?r:[r]).includes(n.iss))throw new $('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new $('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(l=n.aud,g="string"==typeof c?[c]:c,!("string"==typeof l?g.includes(l):Array.isArray(l)&&g.some(Set.prototype.has.bind(new Set(l))))))throw new $('unexpected "aud" claim value',n,"aud","check_failed");var l,g;let u;switch(typeof s.clockTolerance){case"string":u=ce(s.clockTolerance);break;case"number":u=s.clockTolerance;break;case"undefined":u=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:p}=s,m=(y=p||new Date,Math.floor(y.getTime()/1e3));var y;if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new $('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new $('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>m+u)throw new $('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new $('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=m-u)throw new R('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=m-n.iat;if(e-u>("number"==typeof h?h:ce(h)))throw new R('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-u)throw new $('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function le(e,t,s){const n=await async function(e,t,s){if(e instanceof Uint8Array&&(e=I.decode(e)),"string"!=typeof e)throw new M("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:r}=e.split(".");if(3!==r)throw new M("Invalid Compact JWS");const a=await oe({payload:i,protected:n,signature:o},t,s),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}(e,t,s);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new W("JWTs MUST NOT use unencoded payload");const i={payload:de(n.protectedHeader,n.payload,s),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}function ge(e){return G(e)}class ue{constructor(e){if(b(this,n),b(this,i,new WeakMap),!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(ge)}(e))throw new _("JSON Web Key Set malformed");E(this,n,structuredClone(e))}jwks(){return S(this,n)}async getKey(e,t){const{alg:s,kid:o}={...e,...t?.header},r=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new D('Unsupported "alg" value for a JSON Web Key Set')}}(s),a=S(this,n).keys.filter(e=>{let t=r===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),!t||"string"!=typeof e.alg&&"AKP"!==r||(t=s===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(s){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t}),{0:c,length:h}=a;if(0===h)throw new K;if(1!==h){const e=new O,t=S(this,i);throw e[Symbol.asyncIterator]=async function*(){for(const e of a)try{yield await pe(t,e,s)}catch{}},e}return pe(S(this,i),c,s)}}async function pe(e,t,s){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[s]){const e=await async function(e,t){if(!G(e))throw new TypeError("JWK must be an object");let s;switch(t??(t=e.alg),s??(s=e.ext),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return x(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new D('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return q({...e,alg:t,ext:s});case"AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return q({...e,ext:s});case"EC":case"OKP":return q({...e,alg:t,ext:s});default:throw new D('Unsupported "kty" (Key Type) Parameter value')}}({...t,ext:!0},s);if(e instanceof Uint8Array||"public"!==e.type)throw new _("JSON Web Key Set members must be public keys");n[s]=e}return n[s]}function me(e){const t=new ue(e),s=async(e,s)=>t.getKey(e,s);return Object.defineProperties(s,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),s}let ye;if(n=new WeakMap,i=new WeakMap,"undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){ye=`${"jose"}/${"v6.1.0"}`}const fe=Symbol();const we=Symbol();class Se{constructor(e,t){if(b(this,o),b(this,r),b(this,a),b(this,c),b(this,h),b(this,d),b(this,l),b(this,g),b(this,u),b(this,p),!(e instanceof URL))throw new TypeError("url must be an instance of URL");var s,n;E(this,o,new URL(e.href)),E(this,r,"number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3),E(this,a,"number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4),E(this,c,"number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5),E(this,l,new Headers(t?.headers)),ye&&!S(this,l).has("User-Agent")&&S(this,l).set("User-Agent",ye),S(this,l).has("accept")||(S(this,l).set("accept","application/json"),S(this,l).append("accept","application/jwk-set+json")),E(this,g,t?.[fe]),void 0!==t?.[we]&&(E(this,p,t?.[we]),s=t?.[we],n=S(this,c),"object"==typeof s&&null!==s&&"uat"in s&&"number"==typeof s.uat&&!(Date.now()-s.uat>=n)&&"jwks"in s&&G(s.jwks)&&Array.isArray(s.jwks.keys)&&Array.prototype.every.call(s.jwks.keys,G)&&(E(this,h,S(this,p).uat),E(this,u,me(S(this,p).jwks))))}pendingFetch(){return!!S(this,d)}coolingDown(){return"number"==typeof S(this,h)&&Date.now()<S(this,h)+S(this,a)}fresh(){return"number"==typeof S(this,h)&&Date.now()<S(this,h)+S(this,c)}jwks(){return S(this,u)?.jwks()}async getKey(e,t){S(this,u)&&this.fresh()||await this.reload();try{return await S(this,u).call(this,e,t)}catch(s){if(s instanceof K&&!1===this.coolingDown())return await this.reload(),S(this,u).call(this,e,t);throw s}}async reload(){S(this,d)&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&E(this,d,void 0),S(this,d)||E(this,d,async function(e,t,s,n=fetch){const i=await n(e,{method:"GET",signal:s,redirect:"manual",headers:t}).catch(e=>{if("TimeoutError"===e.name)throw new P;throw e});if(200!==i.status)throw new A("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new A("Failed to parse the JSON Web Key Set HTTP response as JSON")}}(S(this,o).href,S(this,l),AbortSignal.timeout(S(this,r)),S(this,g)).then(e=>{E(this,u,me(e)),S(this,p)&&(S(this,p).uat=Date.now(),S(this,p).jwks=e),E(this,h,Date.now()),E(this,d,void 0)}).catch(e=>{throw E(this,d,void 0),e})),await S(this,d)}}function be(e,t){const s=new Se(e,t),n=async(e,t)=>s.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>s.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>s.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>s.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>s.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>s.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}o=new WeakMap,r=new WeakMap,a=new WeakMap,c=new WeakMap,h=new WeakMap,d=new WeakMap,l=new WeakMap,g=new WeakMap,u=new WeakMap,p=new WeakMap;class Ee{constructor(e=!1,t="[MarketplaceSDK]"){this.debug=e,this.prefix=t}log(...e){this.debug}info(...e){this.debug}warn(...e){}error(...e){}}class ve{constructor(e,t=!1){this.jwksUri=e,this.logger=new Ee(t,"[JWKSValidator]"),this.jwks=be(new URL(this.jwksUri)),this.logger.info("Initialized with JWKS URI:",this.jwksUri)}async verify(e,t="generalwisdom.com",s){this.logger.log("Verifying JWT signature...");try{const n=(await le(e,this.jwks,{issuer:t,algorithms:["RS256"]})).payload,i=["sessionId","userId","orgId","applicationId","exp","iat"];for(const e of i)if(!(e in n))throw new v(`Missing required claim: ${e}`,"MISSING_CLAIM");if(s&&n.applicationId!==s)throw this.logger.error(`Application ID mismatch: expected ${s}, got ${n.applicationId}`),new v("Token is for a different application","APPLICATION_MISMATCH");const o={sessionId:n.sessionId,applicationId:n.applicationId,userId:n.userId,orgId:n.orgId,startTime:n.startTime,durationMinutes:n.durationMinutes,iat:n.iat,exp:n.exp,iss:n.iss,sub:n.sub};return this.logger.log("JWT verified successfully"),o}catch(n){if(this.logger.error("JWT verification failed:",n),n instanceof v)throw n;const e=n instanceof Error?n.message:"Unknown error",t=n instanceof Error?n.name:"Error";if("JWTExpired"===t||e.includes("expired"))throw new v("Session expired","SESSION_EXPIRED");if("JWSSignatureVerificationFailed"===t)throw new v("Invalid JWT signature","INVALID_SIGNATURE");if("JWTClaimValidationFailed"===t)throw new v(`JWT claim validation failed: ${e}`,"INVALID_CLAIM");throw new v(`JWT verification failed: ${e}`,"VERIFICATION_FAILED")}}updateJwksUri(e){this.jwksUri=e,this.jwks=be(new URL(this.jwksUri)),this.logger.info("Updated JWKS URI:",this.jwksUri)}}class ke{constructor(e,t=300,s={},n=!1){this.intervalId=null,this.warningShown=!1,this.remainingSeconds=e,this.warningThreshold=t,this.events=s,this.logger=new Ee(n,"[TimerManager]"),this.logger.log("Initialized with duration:",e,"seconds")}start(){null===this.intervalId?(this.logger.log("Starting timer with",this.remainingSeconds,"seconds remaining"),this.intervalId=window.setInterval(()=>{this.remainingSeconds--,!this.warningShown&&this.remainingSeconds<=this.warningThreshold&&this.remainingSeconds>0&&(this.warningShown=!0,this.logger.warn("Warning threshold reached:",this.remainingSeconds,"seconds remaining"),this.events.onSessionWarning?.({remainingSeconds:this.remainingSeconds})),this.remainingSeconds<=0&&(this.logger.warn("Session expired"),this.stop(),this.events.onSessionEnd?.())},1e3)):this.logger.warn("Timer already running")}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.logger.log("Timer stopped"))}pause(){this.stop(),this.logger.log("Timer paused at:",this.remainingSeconds,"seconds")}resume(){null===this.intervalId&&this.remainingSeconds>0&&(this.start(),this.logger.log("Timer resumed at:",this.remainingSeconds,"seconds"))}getRemainingSeconds(){return this.remainingSeconds}getFormattedTime(){return`${Math.floor(this.remainingSeconds/60)}:${(this.remainingSeconds%60).toString().padStart(2,"0")}`}getFormattedTimeWithHours(){const e=Math.floor(this.remainingSeconds/3600),t=Math.floor(this.remainingSeconds%3600/60),s=this.remainingSeconds%60;return e>0?`${e}:${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:this.getFormattedTime()}isRunning(){return null!==this.intervalId}hasWarningBeenShown(){return this.warningShown}updateRemainingTime(e){this.remainingSeconds=e,this.logger.log("Remaining time updated to:",e,"seconds")}}class Te{constructor(e,t,s,n,i,o=30,r=!1){this.sessionId=e,this.apiEndpoint=t,this.token=s,this.onSync=n,this.onError=i,this.intervalId=null,this.failureCount=0,this.maxFailures=3,this.isEnabled=!1,this.heartbeatInterval=1e3*o,this.logger=new Ee(r,"[HeartbeatManager]"),this.logger.log("Initialized with",o,"second interval")}start(){null===this.intervalId?(this.isEnabled=!0,this.logger.log("Starting heartbeat for session:",this.sessionId),this.sendHeartbeat(),this.intervalId=window.setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)):this.logger.warn("Heartbeat already running")}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.isEnabled=!1,this.logger.log("Heartbeat stopped"))}async sendHeartbeat(){if(this.isEnabled){this.logger.log("Sending heartbeat...");try{const e=await fetch(`${this.apiEndpoint}/sessions/${this.sessionId}/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({timestamp:Date.now(),active:!0})});if(!e.ok)throw new v(`Heartbeat failed with status ${e.status}`,"HEARTBEAT_FAILED",e.status);const t=await e.json();this.failureCount=0,"number"==typeof t.remaining_seconds&&(this.logger.log("Server reports",t.remaining_seconds,"seconds remaining"),this.onSync?.(t.remaining_seconds)),this.logger.log("Heartbeat acknowledged")}catch(e){if(this.failureCount++,this.logger.error("Heartbeat failed:",e,`(${this.failureCount}/${this.maxFailures})`),this.failureCount>=this.maxFailures){this.logger.error("Max heartbeat failures reached, stopping"),this.stop();const t=e instanceof v?e:new v(e instanceof Error?e.message:"Heartbeat failed","HEARTBEAT_ERROR");this.onError?.(t)}}}}isRunning(){return null!==this.intervalId}getFailureCount(){return this.failureCount}updateInterval(e){const t=this.isRunning();t&&this.stop(),this.heartbeatInterval=1e3*e,this.logger.log("Heartbeat interval updated to",e,"seconds"),t&&this.start()}}class Ie{constructor(e,t,s=!1){this.sessionId=e,this.onMessage=t,this.channel=null,this.isMaster=!1,this.handleStorageEvent=e=>{if(e.key===this.storageKey&&e.newValue)try{const t=JSON.parse(e.newValue);this.handleMessage(t)}catch(t){this.logger.error("Failed to parse storage event:",t)}},this.storageKey=`gw_session_sync_${e}`,this.logger=new Ee(s,"[TabSyncManager]"),this.initialize()}initialize(){"undefined"!=typeof BroadcastChannel?(this.logger.log("Using BroadcastChannel for tab sync"),this.channel=new BroadcastChannel(`gw-session-${this.sessionId}`),this.channel.onmessage=e=>{this.handleMessage(e.data)}):(this.logger.log("Using localStorage for tab sync (fallback)"),window.addEventListener("storage",this.handleStorageEvent)),this.electMaster()}broadcast(e,t){const s={type:e,sessionId:this.sessionId,timestamp:Date.now(),...t};this.channel?(this.channel.postMessage(s),this.logger.log("Broadcasted:",e)):(localStorage.setItem(this.storageKey,JSON.stringify(s)),this.logger.log("Broadcasted via localStorage:",e))}handleMessage(e){e.sessionId===this.sessionId&&(this.logger.log("Received message:",e.type),this.onMessage(e))}electMaster(){const e=`gw_session_master_${this.sessionId}`;localStorage.getItem(e)?(this.logger.log("Another tab is master"),setInterval(()=>{const t=localStorage.getItem(e);if(t){Date.now()-parseInt(t)>1e4&&(this.logger.warn("Master tab appears dead, becoming master"),this.isMaster=!0,localStorage.setItem(e,Date.now().toString()))}},5e3)):(this.isMaster=!0,localStorage.setItem(e,Date.now().toString()),this.logger.log("Elected as master tab"),setInterval(()=>{this.isMaster&&localStorage.setItem(e,Date.now().toString())},5e3),window.addEventListener("beforeunload",()=>{this.isMaster&&(localStorage.removeItem(e),this.logger.log("Removed master status"))}))}isMasterTab(){return this.isMaster}destroy(){this.channel?(this.channel.close(),this.channel=null):window.removeEventListener("storage",this.handleStorageEvent),localStorage.removeItem(this.storageKey),this.isMaster&&localStorage.removeItem(`gw_session_master_${this.sessionId}`),this.logger.log("Tab sync destroyed")}}const xe={colors:{background:"hsl(0 0% 100%)",foreground:"hsl(222.2 84% 4.9%)",card:"hsl(0 0% 100%)",cardForeground:"hsl(222.2 84% 4.9%)",popover:"hsl(0 0% 100%)",popoverForeground:"hsl(222.2 84% 4.9%)",primary:"hsl(221.2 83.2% 53.3%)",primaryForeground:"hsl(210 40% 98%)",secondary:"hsl(210 40% 96.1%)",secondaryForeground:"hsl(222.2 47.4% 11.2%)",muted:"hsl(210 40% 96.1%)",mutedForeground:"hsl(215.4 16.3% 46.9%)",accent:"hsl(210 40% 96.1%)",accentForeground:"hsl(222.2 47.4% 11.2%)",destructive:"hsl(0 84.2% 60.2%)",destructiveForeground:"hsl(210 40% 98%)",success:"hsl(142 76% 36%)",successForeground:"hsl(0 0% 100%)",border:"hsl(214.3 31.8% 91.4%)",input:"hsl(214.3 31.8% 91.4%)",ring:"hsl(221.2 83.2% 53.3%)"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{xs:"12px",sm:"14px",base:"16px",lg:"18px",xl:"20px","2xl":"24px"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.75"}},spacing:{borderRadius:{sm:"4px",md:"6px",lg:"8px"},padding:{sm:"8px",md:"16px",lg:"24px",xl:"32px"},gap:{sm:"8px",md:"12px",lg:"16px"}}},Ae={colors:{background:"hsl(222.2 84% 4.9%)",foreground:"hsl(210 40% 98%)",card:"hsl(222.2 84% 4.9%)",cardForeground:"hsl(210 40% 98%)",popover:"hsl(222.2 84% 4.9%)",popoverForeground:"hsl(210 40% 98%)",primary:"hsl(217.2 91.2% 59.8%)",primaryForeground:"hsl(222.2 47.4% 11.2%)",secondary:"hsl(217.2 32.6% 17.5%)",secondaryForeground:"hsl(210 40% 98%)",muted:"hsl(217.2 32.6% 17.5%)",mutedForeground:"hsl(215 20.2% 65.1%)",accent:"hsl(217.2 32.6% 17.5%)",accentForeground:"hsl(210 40% 98%)",destructive:"hsl(0 62.8% 30.6%)",destructiveForeground:"hsl(210 40% 98%)",success:"hsl(142 71% 45%)",successForeground:"hsl(0 0% 100%)",border:"hsl(217.2 32.6% 17.5%)",input:"hsl(217.2 32.6% 17.5%)",ring:"hsl(224.3 76.3% 48%)"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{xs:"12px",sm:"14px",base:"16px",lg:"18px",xl:"20px","2xl":"24px"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.75"}},spacing:{borderRadius:{sm:"4px",md:"6px",lg:"8px"},padding:{sm:"8px",md:"16px",lg:"24px",xl:"32px"},gap:{sm:"8px",md:"12px",lg:"16px"}}};function $e(e){if(void 0!==e)return e?Ae:xe;if("undefined"!=typeof window&&window.matchMedia){return window.matchMedia("(prefers-color-scheme: dark)").matches?Ae:xe}return xe}class Re{constructor(e="light",t){this.modal=null,this.legacyStyles=null,this.updateInterval=null,this.timeDisplay=null,this.startTime=0,this.initialSeconds=0,this.onEndCallback=void 0;const s="dark"===e||"auto"===e&&this.detectDarkMode();this.theme=$e(s),t&&(this.legacyStyles={backgroundColor:t.backgroundColor||"#ffffff",textColor:t.textColor||"#333333",primaryColor:t.primaryColor||"#007bff",borderRadius:t.borderRadius||"8px",fontFamily:t.fontFamily||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'})}detectDarkMode(){return!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-color-scheme: dark)").matches}show(e){this.hide(),this.modal=document.createElement("div"),this.modal.id="gw-session-warning-modal",this.modal.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 99999;\n font-family: ${this.legacyStyles?.fontFamily||this.theme.typography.fontFamily};\n `;const t=document.createElement("div"),s=this.legacyStyles?.backgroundColor||this.theme.colors.card,n=this.legacyStyles?.textColor||this.theme.colors.cardForeground,i=this.legacyStyles?.borderRadius||this.theme.spacing.borderRadius.lg;t.style.cssText=`\n background-color: ${s};\n color: ${n};\n border-radius: ${i};\n padding: ${this.theme.spacing.padding.lg};\n max-width: 400px;\n width: 90%;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border: 1px solid ${this.theme.colors.border};\n `,this.initialSeconds=e.remainingSeconds,this.startTime=Date.now(),this.onEndCallback=e.onEnd;const o=Math.floor(e.remainingSeconds/60),r=e.remainingSeconds%60;t.innerHTML=`\n <h2 style="margin: 0 0 ${this.theme.spacing.padding.md} 0; font-size: ${this.theme.typography.fontSize.xl}; font-weight: ${this.theme.typography.fontWeight.semibold}; color: ${n};">\n ⏱️ Time Running Low\n </h2>\n <p style="margin: 0 0 ${this.theme.spacing.padding.lg} 0; font-size: ${this.theme.typography.fontSize.base}; line-height: ${this.theme.typography.lineHeight.normal}; color: ${this.theme.colors.mutedForeground};">\n Your session will expire in <strong id="gw-time-display" style="color: ${n};">${o}:${r.toString().padStart(2,"0")}</strong>.\n </p>\n <div style="display: flex; gap: ${this.theme.spacing.gap.md}; justify-content: flex-end;">\n <button id="gw-dismiss-btn" style="\n padding: 10px 20px;\n background-color: ${this.theme.colors.secondary};\n color: ${this.theme.colors.secondaryForeground};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n cursor: pointer;\n transition: all 0.2s;\n font-family: ${this.theme.typography.fontFamily};\n ">\n Continue\n </button>\n ${e.onExtend?`<button id="gw-extend-btn" style="\n padding: 10px 20px;\n background-color: ${this.theme.colors.success};\n color: ${this.theme.colors.successForeground};\n border: none;\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n cursor: pointer;\n transition: all 0.2s;\n font-family: ${this.theme.typography.fontFamily};\n ">\n Extend Session\n </button>`:""}\n ${e.onEnd?`<button id="gw-end-btn" style="\n padding: 10px 20px;\n background-color: ${this.theme.colors.destructive};\n color: ${this.theme.colors.destructiveForeground};\n border: none;\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n cursor: pointer;\n transition: all 0.2s;\n font-family: ${this.theme.typography.fontFamily};\n ">\n End Session\n </button>`:""}\n </div>\n `,this.modal.appendChild(t),document.body.appendChild(this.modal);const a=document.getElementById("gw-extend-btn");a&&e.onExtend&&a.addEventListener("click",()=>{e.onExtend?.(),this.hide()});const c=document.getElementById("gw-dismiss-btn");c&&c.addEventListener("click",()=>{this.hide()});const h=document.getElementById("gw-end-btn");h&&e.onEnd&&h.addEventListener("click",()=>{e.onEnd?.()});t.querySelectorAll("button").forEach(e=>{e.addEventListener("mouseenter",()=>{e.style.opacity="0.9"}),e.addEventListener("mouseleave",()=>{e.style.opacity="1"}),e.addEventListener("focus",()=>{e.style.outline=`2px solid ${this.theme.colors.ring}`,e.style.outlineOffset="2px"}),e.addEventListener("blur",()=>{e.style.outline="none"})}),this.timeDisplay=document.getElementById("gw-time-display"),this.updateInterval=window.setInterval(()=>{const e=Math.floor((Date.now()-this.startTime)/1e3),t=Math.max(0,this.initialSeconds-e),s=Math.floor(t/60),n=t%60;this.timeDisplay&&(this.timeDisplay.textContent=`${s}:${n.toString().padStart(2,"0")}`),0===t&&(this.onEndCallback&&this.onEndCallback(),this.hide())},1e3)}hide(){null!==this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.modal&&this.modal.parentNode&&(this.modal.parentNode.removeChild(this.modal),this.modal=null,this.timeDisplay=null)}isShown(){return null!==this.modal}showEndingMessage(e,t=3e3){this.hide();const s=this.legacyStyles?.backgroundColor||this.theme.colors.card,n=this.legacyStyles?.textColor||this.theme.colors.cardForeground,i=this.legacyStyles?.borderRadius||this.theme.spacing.borderRadius.lg;this.modal=document.createElement("div"),this.modal.id="gw-session-ending-modal",this.modal.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 99999;\n font-family: ${this.legacyStyles?.fontFamily||this.theme.typography.fontFamily};\n animation: fadeIn 0.2s ease-in;\n `;const o=document.createElement("div");o.style.cssText=`\n background-color: ${s};\n color: ${n};\n border-radius: ${i};\n padding: ${this.theme.spacing.padding.xl};\n max-width: 400px;\n width: 90%;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n text-align: center;\n animation: slideIn 0.3s ease-out;\n border: 1px solid ${this.theme.colors.border};\n `,o.innerHTML=`\n <div style="font-size: 48px; margin-bottom: ${this.theme.spacing.padding.lg};">⏱️</div>\n <h2 style="margin: 0 0 ${this.theme.spacing.padding.md} 0; font-size: ${this.theme.typography.fontSize["2xl"]}; font-weight: ${this.theme.typography.fontWeight.semibold}; color: ${this.theme.colors.destructive};">\n Session Ending\n </h2>\n <p style="margin: 0 0 ${this.theme.spacing.padding.lg} 0; font-size: ${this.theme.typography.fontSize.base}; line-height: ${this.theme.typography.lineHeight.normal}; color: ${this.theme.colors.mutedForeground};">\n Your session has expired.<br/>\n Redirecting to marketplace...\n </p>\n <div style="\n width: 100%;\n height: 4px;\n background: ${this.theme.colors.muted};\n border-radius: ${this.theme.spacing.borderRadius.sm};\n overflow: hidden;\n margin-top: ${this.theme.spacing.padding.lg};\n ">\n <div id="gw-progress-bar" style="\n width: 100%;\n height: 100%;\n background: linear-gradient(90deg, ${this.theme.colors.destructive}, ${this.theme.colors.primary});\n animation: progressBar ${t}ms linear forwards;\n "></div>\n </div>\n `;const r=document.createElement("style");r.textContent="\n @keyframes fadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n @keyframes slideIn {\n from { transform: translateY(-20px); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n @keyframes progressBar {\n from { width: 100%; }\n to { width: 0%; }\n }\n ",document.head.appendChild(r),this.modal.appendChild(o),document.body.appendChild(this.modal),setTimeout(()=>{this.hide(),e()},t)}}function Ce(e="jwt",t){try{const s=t||("undefined"!=typeof window?window.location.href:"");if(!s)return null;const n=new URL(s);return n.searchParams.get(e)}catch(s){throw new v(`Failed to extract token from URL: ${s instanceof Error?s.message:"Unknown error"}`,"URL_PARSE_ERROR")}}class De{constructor(e){this.timer=null,this.heartbeat=null,this.tabSync=null,this.modal=null,this.events={},this.sessionData=null,this.jwtToken=null,this.endReason="manual",this.config={jwksUri:e.jwksUri||"https://api.generalwisdom.com/.well-known/jwks.json",apiEndpoint:e.apiEndpoint||"http://localhost:3000",debug:e.debug??!1,autoStart:e.autoStart??!0,warningThresholdSeconds:e.warningThresholdSeconds??300,customStyles:e.customStyles??{},themeMode:e.themeMode??"light",applicationId:e.applicationId??"",marketplaceUrl:e.marketplaceUrl??"https://d3p2yqofgy75sz.cloudfront.net/",enableHeartbeat:e.enableHeartbeat??!1,heartbeatIntervalSeconds:e.heartbeatIntervalSeconds??30,enableTabSync:e.enableTabSync??!1,pauseOnHidden:e.pauseOnHidden??!1,useBackendValidation:e.useBackendValidation??!1,hooks:e.hooks??{},hookTimeoutMs:e.hookTimeoutMs??5e3},this.validator=new ve(this.config.jwksUri,this.config.debug),this.logger=new Ee(this.config.debug,"[MarketplaceSDK]"),this.logger.info("SDK initialized with config:",{jwksUri:this.config.jwksUri,apiEndpoint:this.config.apiEndpoint,enableHeartbeat:this.config.enableHeartbeat,enableTabSync:this.config.enableTabSync,pauseOnHidden:this.config.pauseOnHidden})}on(e,t){this.events[e]=t,this.logger.log("Event handler registered:",e)}async executeHook(e,t,s,n=!0){if(!t)return;this.logger.log(`Calling ${e} hook`);const i=new Promise((t,s)=>setTimeout(()=>s(new v(`${e} hook timeout after ${this.config.hookTimeoutMs}ms`,"HOOK_TIMEOUT")),this.config.hookTimeoutMs));try{await Promise.race([Promise.resolve(t(s)),i]),this.logger.log(`${e} hook completed successfully`)}catch(o){if(this.logger.error(`${e} hook failed:`,o),n)throw new v(`${e} hook failed: ${o instanceof Error?o.message:"Unknown error"}`,"HOOK_ERROR");this.logger.warn(`${e} hook failed but continuing (lenient mode)`)}}calculateActualDuration(){if(!this.sessionData)return;const e=Math.floor(Date.now()/1e3)-this.sessionData.startTime;return Math.ceil(e/60)}async initialize(){this.logger.info("Initializing session...");try{const e="gw_marketplace_jwt";if(this.jwtToken=Ce("jwt"),this.jwtToken||"undefined"==typeof sessionStorage||(this.jwtToken=sessionStorage.getItem(e),this.jwtToken&&this.logger.log("JWT token retrieved from storage")),!this.jwtToken)throw new v("No jwt token found in URL or storage","MISSING_TOKEN");let t;"undefined"!=typeof sessionStorage&&(sessionStorage.setItem(e,this.jwtToken),this.logger.log("JWT token stored in sessionStorage")),this.logger.log("JWT token extracted from URL"),this.config.useBackendValidation?(this.logger.log("Using backend validation"),t=await this.validateWithBackend(this.jwtToken)):(this.logger.log("Using JWKS validation"),t=await this.validator.verify(this.jwtToken,"generalwisdom.com",this.config.applicationId||void 0)),this.logger.log("JWT verified successfully"),this.sessionData={sessionId:t.sessionId,applicationId:t.applicationId,userId:t.userId,orgId:t.orgId,startTime:t.startTime,durationMinutes:t.durationMinutes,iat:t.iat,exp:t.exp,iss:t.iss,sub:t.sub};const s=Math.floor(Date.now()/1e3),n=Math.max(0,this.sessionData.exp-s);if(n<=0)throw new v("Session has already expired","SESSION_EXPIRED");if(this.logger.log("Remaining time:",n,"seconds"),this.config.hooks?.onSessionStart){const e={sessionId:this.sessionData.sessionId,userId:this.sessionData.userId,email:t.email,orgId:this.sessionData.orgId,applicationId:this.sessionData.applicationId,durationMinutes:this.sessionData.durationMinutes,expiresAt:this.sessionData.exp,jwt:this.jwtToken};await this.executeHook("onSessionStart",this.config.hooks.onSessionStart,e,!0),this.logger.log("Application auth synchronized with marketplace session")}if(this.timer=new ke(n,this.config.warningThresholdSeconds,{onSessionWarning:e=>{if(this.config.hooks?.onSessionWarning){const t={sessionId:this.sessionData.sessionId,userId:this.sessionData.userId,remainingSeconds:e.remainingSeconds};this.executeHook("onSessionWarning",this.config.hooks.onSessionWarning,t,!1).catch(e=>this.logger.error("onSessionWarning hook failed:",e))}this.showWarningModal(e.remainingSeconds),this.events.onSessionWarning?.(e)},onSessionEnd:()=>{this.endReason="expired",this.endSession()}},this.config.debug),this.config.enableHeartbeat&&this.jwtToken&&(this.heartbeat=new Te(this.sessionData.sessionId,this.config.apiEndpoint,this.jwtToken,e=>{this.timer?.updateRemainingTime(e)},e=>{this.logger.error("Heartbeat error:",e),this.events.onError?.(e)},this.config.heartbeatIntervalSeconds,this.config.debug)),this.config.enableTabSync&&(this.tabSync=new Ie(this.sessionData.sessionId,e=>this.handleTabSyncMessage(e),this.config.debug)),this.config.pauseOnHidden&&this.initializeVisibilityHandling(),this.config.autoStart&&(this.timer.start(),this.logger.log("Timer started automatically"),this.config.enableHeartbeat&&this.heartbeat)){!this.tabSync||this.tabSync.isMasterTab()?(this.heartbeat.start(),this.logger.log("Heartbeat started (master tab)")):this.logger.log("Heartbeat not started (slave tab)")}return this.events.onSessionStart?.(this.sessionData),this.logger.info("Session initialized successfully"),this.sessionData}catch(e){this.logger.error("Initialization failed:",e);const t=e instanceof v?e:new v(e instanceof Error?e.message:"Unknown error","INITIALIZATION_ERROR");throw this.events.onError?.(t),t}}async validateWithBackend(e){const t=await fetch(`${this.config.apiEndpoint}/sessions/validate`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({session_jwt:e})});if(!t.ok)throw new v("Backend validation failed","BACKEND_VALIDATION_FAILED",t.status);const s=await t.json();if(!s.valid)throw new v(s.error||"Session validation failed","SESSION_INVALID");return k.decode(e)}handleTabSyncMessage(e){switch(this.logger.log("Tab sync message:",e.type),e.type){case"pause":this.timer?.pause();break;case"resume":this.timer?.resume();break;case"end":this.endSession();break;case"timer_update":void 0!==e.remainingSeconds&&this.timer?.updateRemainingTime(e.remainingSeconds)}}initializeVisibilityHandling(){document.addEventListener("visibilitychange",()=>{document.hidden?(this.logger.log("Tab hidden, pausing timer"),this.pauseTimer()):(this.logger.log("Tab visible, resuming timer"),this.resumeTimer())}),this.logger.log("Visibility API handler initialized")}startTimer(){if(!this.timer)throw new v("SDK not initialized. Call initialize() first.","NOT_INITIALIZED");this.timer.start(),this.tabSync?.broadcast("resume"),this.logger.info("Timer started manually")}pauseTimer(){this.timer?.pause(),this.tabSync?.broadcast("pause"),this.logger.info("Timer paused")}resumeTimer(){this.timer?.resume(),this.tabSync?.broadcast("resume"),this.logger.info("Timer resumed")}async extendSession(e){if(!this.sessionData||!this.jwtToken)throw new v("No active session","NO_SESSION");this.logger.info("Extending session by",e,"minutes");try{const t=await fetch(`${this.config.apiEndpoint}/sessions/${this.sessionData.sessionId}/renew`,{method:"PUT",headers:{Authorization:`Bearer ${this.jwtToken}`,"Content-Type":"application/json"},body:JSON.stringify({additional_minutes:e})});if(!t.ok)throw new v("Session extension failed","EXTENSION_FAILED",t.status);const s=await t.json();this.sessionData.exp=s.new_expires_at;const n=Math.floor(Date.now()/1e3),i=s.new_expires_at-n;if(this.timer?.updateRemainingTime(i),this.tabSync?.broadcast("timer_update",{remainingSeconds:i}),this.config.hooks?.onSessionExtend){const t={sessionId:this.sessionData.sessionId,userId:this.sessionData.userId,additionalMinutes:e,newExpiresAt:s.new_expires_at};await this.executeHook("onSessionExtend",this.config.hooks.onSessionExtend,t,!1)}this.logger.info("Session extended successfully")}catch(t){this.logger.error("Failed to extend session:",t);const e=t instanceof v?t:new v(t instanceof Error?t.message:"Extension failed","EXTENSION_ERROR");throw this.events.onError?.(e),e}}async completeSession(e){if(!this.sessionData||!this.jwtToken)throw new v("No active session","NO_SESSION");this.logger.info("Completing session...");try{const t=await fetch(`${this.config.apiEndpoint}/sessions/${this.sessionData.sessionId}/complete`,{method:"POST",headers:{Authorization:`Bearer ${this.jwtToken}`,"Content-Type":"application/json"},body:JSON.stringify({actual_usage_minutes:e,metadata:{}})});if(!t.ok)throw new v("Session completion failed","COMPLETION_FAILED",t.status);const s=await t.json();this.logger.info("Session completed:",s),this.endSession()}catch(t){this.logger.error("Failed to complete session:",t);const e=t instanceof v?t:new v(t instanceof Error?t.message:"Completion failed","COMPLETION_ERROR");throw this.events.onError?.(e),e}}async endSession(){this.logger.info("Ending session...");const e={sessionId:this.sessionData?.sessionId||"",userId:this.sessionData?.userId||"",reason:this.endReason,actualDurationMinutes:this.calculateActualDuration()};if(this.config.hooks?.onSessionEnd)try{await this.executeHook("onSessionEnd",this.config.hooks.onSessionEnd,e,!1),this.logger.log("Application auth cleanup completed")}catch(t){this.logger.error("onSessionEnd hook error (continuing anyway):",t)}this.timer?.stop(),this.heartbeat?.stop(),this.tabSync?.broadcast("end"),"undefined"!=typeof sessionStorage&&(sessionStorage.removeItem("gw_marketplace_jwt"),this.logger.log("JWT token cleared from storage")),this.events.onSessionEnd?.(),this.logger.info("Session ended"),"undefined"!=typeof window&&(this.modal||(this.modal=new Re(this.config.themeMode||"light",this.config.customStyles)),this.modal.showEndingMessage(()=>{window.location.href=this.config.marketplaceUrl},3e3))}showWarningModal(e){this.modal||(this.modal=new Re(this.config.themeMode||"light",this.config.customStyles)),this.modal.show({remainingSeconds:e,onExtend:async()=>{try{await this.extendSession(15),this.modal?.hide(),this.logger.log("Session extended successfully from modal")}catch(e){this.logger.error("Extension failed, redirecting to marketplace:",e);const t=`${this.config.marketplaceUrl}extend-session?sessionId=${this.sessionData?.sessionId}`;"undefined"!=typeof window&&(this.modal||(this.modal=new Re(this.config.themeMode||"light",this.config.customStyles)),this.modal.showEndingMessage(()=>{window.location.href=t},3e3))}},onEnd:()=>{this.endSession()}})}getSessionData(){return this.sessionData}getRemainingTime(){return this.timer?.getRemainingSeconds()??0}getFormattedTime(){return this.timer?.getFormattedTime()??"0:00"}getFormattedTimeWithHours(){return this.timer?.getFormattedTimeWithHours()??"0:00:00"}isTimerRunning(){return this.timer?.isRunning()??!1}destroy(){this.logger.info("Destroying SDK instance..."),this.timer?.stop(),this.heartbeat?.stop(),this.tabSync?.destroy(),this.modal?.hide(),"undefined"!=typeof sessionStorage&&(sessionStorage.removeItem("gw_marketplace_jwt"),this.logger.log("JWT token cleared from storage")),this.sessionData=null,this.jwtToken=null}}e.HeartbeatManager=Te,e.JWKSValidator=ve,e.JWTParser=k,e.Logger=Ee,e.MarketplaceSDK=De,e.SDKError=v,e.SessionHeader=class{constructor(e="auto"){this.container=null,this.updateInterval=null,this.timeDisplay=null,this.mounted=!1;const t="dark"===e||"auto"===e&&this.detectDarkMode();this.theme=$e(t)}detectDarkMode(){return!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-color-scheme: dark)").matches}mount(e,t){this.mounted&&this.unmount();const s="string"==typeof e?document.querySelector(e):e;if(!s)return;this.getTimeCallback=t.getTime,this.onExtendCallback=t.onExtend,this.onEndCallback=t.onEnd,this.container=document.createElement("div"),this.container.id="gw-session-header";const n=t.position||"right",i="left"===n?"flex-start":"center"===n?"center":"flex-end";this.container.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: ${i};\n gap: ${this.theme.spacing.gap.md};\n padding: ${this.theme.spacing.padding.sm} ${this.theme.spacing.padding.md};\n background-color: ${this.theme.colors.card};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${this.theme.spacing.borderRadius.md};\n font-family: ${this.theme.typography.fontFamily};\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);\n `;const o=document.createElement("div");o.style.cssText=`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.gap.sm};\n color: ${this.theme.colors.foreground};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n `;const r=document.createElement("span");r.textContent="⏱️",r.style.fontSize=this.theme.typography.fontSize.base,this.timeDisplay=document.createElement("span"),this.timeDisplay.id="gw-session-time",this.timeDisplay.textContent=this.getTimeCallback?.()||"--:--",this.timeDisplay.style.cssText="\n font-variant-numeric: tabular-nums;\n min-width: 50px;\n text-align: center;\n ",o.appendChild(r),o.appendChild(this.timeDisplay),this.container.appendChild(o);const a=document.createElement("div");if(a.style.cssText=`\n display: flex;\n gap: ${this.theme.spacing.gap.sm};\n `,this.onExtendCallback){const e=document.createElement("button");e.textContent="Extend",e.style.cssText=`\n padding: ${this.theme.spacing.padding.sm};\n background-color: ${this.theme.colors.success};\n color: ${this.theme.colors.successForeground};\n border: none;\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n font-family: ${this.theme.typography.fontFamily};\n cursor: pointer;\n transition: opacity 0.2s;\n `,e.addEventListener("mouseenter",()=>{e.style.opacity="0.9"}),e.addEventListener("mouseleave",()=>{e.style.opacity="1"}),e.addEventListener("click",()=>{this.onExtendCallback?.()}),a.appendChild(e)}if(this.onEndCallback){const e=document.createElement("button");e.textContent="End",e.style.cssText=`\n padding: ${this.theme.spacing.padding.sm};\n background-color: ${this.theme.colors.secondary};\n color: ${this.theme.colors.secondaryForeground};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n font-family: ${this.theme.typography.fontFamily};\n cursor: pointer;\n transition: opacity 0.2s;\n `,e.addEventListener("mouseenter",()=>{e.style.opacity="0.9"}),e.addEventListener("mouseleave",()=>{e.style.opacity="1"}),e.addEventListener("click",()=>{this.onEndCallback?.()}),a.appendChild(e)}a.children.length>0&&this.container.appendChild(a),s.appendChild(this.container),this.mounted=!0,this.startUpdating()}startUpdating(){this.updateInterval&&clearInterval(this.updateInterval),this.updateInterval=window.setInterval(()=>{if(this.timeDisplay&&this.getTimeCallback){const e=this.getTimeCallback();this.timeDisplay.textContent=e;const[t]=e.split(":").map(Number);!isNaN(t)&&t<5?(this.timeDisplay.style.color=this.theme.colors.destructive,this.timeDisplay.style.fontWeight=this.theme.typography.fontWeight.bold):(this.timeDisplay.style.color=this.theme.colors.foreground,this.timeDisplay.style.fontWeight=this.theme.typography.fontWeight.medium)}},1e3)}unmount(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null,this.timeDisplay=null,this.mounted=!1}isMounted(){return this.mounted}updateTheme(e){const t="dark"===e||"auto"===e&&this.detectDarkMode();if(this.theme=$e(t),this.mounted&&this.container&&this.container.parentElement){const e=this.container.parentElement,t={getTime:this.getTimeCallback,onExtend:this.onExtendCallback,onEnd:this.onEndCallback};this.unmount(),this.mount(e,t)}}},e.TabSyncManager=Ie,e.TimerManager=ke,e.WarningModal=Re,e.darkTheme=Ae,e.default=De,e.extractTokenFromURL=Ce,e.generateCSSVariables=function(e){return`\n --gw-background: ${e.colors.background};\n --gw-foreground: ${e.colors.foreground};\n --gw-card: ${e.colors.card};\n --gw-card-foreground: ${e.colors.cardForeground};\n --gw-primary: ${e.colors.primary};\n --gw-primary-foreground: ${e.colors.primaryForeground};\n --gw-secondary: ${e.colors.secondary};\n --gw-secondary-foreground: ${e.colors.secondaryForeground};\n --gw-muted: ${e.colors.muted};\n --gw-muted-foreground: ${e.colors.mutedForeground};\n --gw-accent: ${e.colors.accent};\n --gw-accent-foreground: ${e.colors.accentForeground};\n --gw-destructive: ${e.colors.destructive};\n --gw-destructive-foreground: ${e.colors.destructiveForeground};\n --gw-success: ${e.colors.success};\n --gw-success-foreground: ${e.colors.successForeground};\n --gw-border: ${e.colors.border};\n --gw-input: ${e.colors.input};\n --gw-ring: ${e.colors.ring};\n `.trim()},e.getTheme=$e,e.isBrowser=function(){return"undefined"!=typeof window&&void 0!==window.document},e.lightTheme=xe,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).MarketplaceSDK={})}(this,function(e){"use strict";var t,s,n,i,o,r,a,c,h,d,l,g,u,p,m=Object.defineProperty,y=e=>{throw TypeError(e)},f=(e,t,s)=>((e,t,s)=>t in e?m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s),w=(e,t,s)=>t.has(e)||y("Cannot "+s),S=(e,t,s)=>(w(e,t,"read from private field"),s?s.call(e):t.get(e)),b=(e,t,s)=>t.has(e)?y("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,s),E=(e,t,s,n)=>(w(e,t,"write to private field"),n?n.call(e,s):t.set(e,s),s);class v extends Error{constructor(e,t,s){super(e),this.code=t,this.statusCode=s,this.name="SDKError",Error.captureStackTrace&&Error.captureStackTrace(this,v)}}class k{static decode(e){if(!e||"string"!=typeof e)throw new v("Invalid JWT token format","INVALID_TOKEN");const t=e.split(".");if(3!==t.length)throw new v("Malformed JWT token - expected 3 parts","MALFORMED_TOKEN");try{const e=t[1],s=this.base64UrlDecode(e);return JSON.parse(s)}catch(s){throw new v(`Failed to decode JWT payload: ${s instanceof Error?s.message:"Unknown error"}`,"DECODE_ERROR")}}static decodeHeader(e){if(!e||"string"!=typeof e)throw new v("Invalid JWT token format","INVALID_TOKEN");const t=e.split(".");if(3!==t.length)throw new v("Malformed JWT token - expected 3 parts","MALFORMED_TOKEN");try{const e=t[0],s=this.base64UrlDecode(e);return JSON.parse(s)}catch(s){throw new v(`Failed to decode JWT header: ${s instanceof Error?s.message:"Unknown error"}`,"DECODE_ERROR")}}static extractClaim(e,t){return this.decode(e)[t]}static isExpired(e){const t=this.decode(e).exp;return!!t&&Date.now()>=1e3*t}static getTimeRemaining(e){const t=this.decode(e).exp;if(!t)return 0;const s=t-Math.floor(Date.now()/1e3);return Math.max(0,s)}static base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const s=t.length%4;s&&(t+="=".repeat(4-s));try{if("undefined"!=typeof Buffer)return Buffer.from(t,"base64").toString("utf-8");if("undefined"!=typeof atob)return atob(t);throw new Error("No base64 decoding available")}catch(n){throw new v("Invalid base64 encoding","ENCODING_ERROR")}}}const T=new TextEncoder,I=new TextDecoder;function x(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof e?e:I.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=I.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return function(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);const t=atob(e),s=new Uint8Array(t.length);for(let n=0;n<t.length;n++)s[n]=t.charCodeAt(n);return s}(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}class A extends Error{constructor(e,t){super(e,t),f(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}f(A,"code","ERR_JOSE_GENERIC");class R extends A{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),f(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),f(this,"claim"),f(this,"reason"),f(this,"payload"),this.claim=s,this.reason=n,this.payload=t}}f(R,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class $ extends A{constructor(e,t,s="unspecified",n="unspecified"){super(e,{cause:{claim:s,reason:n,payload:t}}),f(this,"code","ERR_JWT_EXPIRED"),f(this,"claim"),f(this,"reason"),f(this,"payload"),this.claim=s,this.reason=n,this.payload=t}}f($,"code","ERR_JWT_EXPIRED");class C extends A{constructor(){super(...arguments),f(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}f(C,"code","ERR_JOSE_ALG_NOT_ALLOWED");class D extends A{constructor(){super(...arguments),f(this,"code","ERR_JOSE_NOT_SUPPORTED")}}f(D,"code","ERR_JOSE_NOT_SUPPORTED");class W extends A{constructor(){super(...arguments),f(this,"code","ERR_JWS_INVALID")}}f(W,"code","ERR_JWS_INVALID");class M extends A{constructor(){super(...arguments),f(this,"code","ERR_JWT_INVALID")}}f(M,"code","ERR_JWT_INVALID");class _ extends A{constructor(){super(...arguments),f(this,"code","ERR_JWKS_INVALID")}}f(_,"code","ERR_JWKS_INVALID");class K extends A{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),f(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}f(K,"code","ERR_JWKS_NO_MATCHING_KEY");class O extends(s=A,t=Symbol.asyncIterator,s){constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),f(this,t),f(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}f(O,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class P extends A{constructor(e="request timed out",t){super(e,t),f(this,"code","ERR_JWKS_TIMEOUT")}}f(P,"code","ERR_JWKS_TIMEOUT");class H extends A{constructor(e="signature verification failed",t){super(e,t),f(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}function j(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function J(e,t){return e.name===t}function N(e){return parseInt(e.name.slice(4),10)}function L(e,t,s){switch(t){case"HS256":case"HS384":case"HS512":{if(!J(e.algorithm,"HMAC"))throw j("HMAC");const s=parseInt(t.slice(2),10);if(N(e.algorithm.hash)!==s)throw j(`SHA-${s}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!J(e.algorithm,"RSASSA-PKCS1-v1_5"))throw j("RSASSA-PKCS1-v1_5");const s=parseInt(t.slice(2),10);if(N(e.algorithm.hash)!==s)throw j(`SHA-${s}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!J(e.algorithm,"RSA-PSS"))throw j("RSA-PSS");const s=parseInt(t.slice(2),10);if(N(e.algorithm.hash)!==s)throw j(`SHA-${s}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":if(!J(e.algorithm,"Ed25519"))throw j("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":if(!J(e.algorithm,t))throw j(t);break;case"ES256":case"ES384":case"ES512":{if(!J(e.algorithm,"ECDSA"))throw j("ECDSA");const s=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!==s)throw j(s,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(e,t){if(!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}(e,s)}function U(e,t,...s){if((s=s.filter(Boolean)).length>2){const t=s.pop();e+=`one of type ${s.join(", ")}, or ${t}.`}else 2===s.length?e+=`one of type ${s[0]} or ${s[1]}.`:e+=`of type ${s[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}f(H,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function F(e,t,...s){return U(`Key for the ${e} algorithm must be `,t,...s)}function z(e){return"CryptoKey"===e?.[Symbol.toStringTag]}function B(e){return"KeyObject"===e?.[Symbol.toStringTag]}const V=e=>z(e)||B(e);const G=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 s=e;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(e)===s};const q=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:s}=function(e){let t,s;switch(e.kty){case"AKP":switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},s=e.priv?["sign"]:["verify"];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},s=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},s=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}`},s=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},s=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},s=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},s=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},s=e.d?["deriveBits"]:[];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},s=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},s=e.d?["deriveBits"]:[];break;default:throw new D('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new D('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:s}}(e),n={...e};return"AKP"!==n.kty&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??(!e.d&&!e.priv),e.key_ops??s)};function Y(e){return G(e)&&"string"==typeof e.kty}let X;const Z=async(e,t,s,n=!1)=>{X||(X=new WeakMap);let i=X.get(e);if(i?.[s])return i[s];const o=await q({...t,alg:s});return n&&Object.freeze(e),i?i[s]=o:X.set(e,{[s]:o}),o},Q=async(e,t)=>{if(e instanceof Uint8Array)return e;if(z(e))return e;if(B(e)){if("secret"===e.type)return e.export();if("toCryptoKey"in e&&"function"==typeof e.toCryptoKey)try{return((e,t)=>{X||(X=new WeakMap);let s=X.get(e);if(s?.[t])return s[t];const n="public"===e.type,i=!!n;let o;if("x25519"===e.asymmetricKeyType){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}o=e.toCryptoKey(e.asymmetricKeyType,i,n?[]:["deriveBits"])}if("ed25519"===e.asymmetricKeyType){if("EdDSA"!==t&&"Ed25519"!==t)throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");o=e.toCryptoKey(e.asymmetricKeyType,i,[n?"verify":"sign"])}if("rsa"===e.asymmetricKeyType){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},i,n?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},i,[n?"verify":"sign"])}if("ec"===e.asymmetricKeyType){const s=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!s)throw new TypeError("given KeyObject instance cannot be used for this algorithm");"ES256"===t&&"P-256"===s&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:s},i,[n?"verify":"sign"])),"ES384"===t&&"P-384"===s&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:s},i,[n?"verify":"sign"])),"ES512"===t&&"P-521"===s&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:s},i,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:s},i,n?[]:["deriveBits"]))}if(!o)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return s?s[t]=o:X.set(e,{[t]:o}),o})(e,t)}catch(s){if(s instanceof TypeError)throw s}let n=e.export({format:"jwk"});return Z(e,n,t)}if(Y(e))return e.k?x(e.k):Z(e,e,t,!0);throw new Error("unreachable")},ee=e=>e?.[Symbol.toStringTag],te=(e,t,s)=>{if(void 0!==t.use){let e;switch(s){case"sign":case"verify":e="sig";break;case"encrypt":case"decrypt":e="enc"}if(t.use!==e)throw new TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case"verify"===s:case"dir"===e:case e.includes("CBC-HS"):n=s;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):n=!e.includes("GCM")&&e.endsWith("KW")?"unwrapKey":s;break;case"encrypt"===s:n="wrapKey";break;case"decrypt"===s:n=e.startsWith("RSA")?"unwrapKey":"deriveBits"}if(n&&!1===t.key_ops?.includes?.(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},se=(e,t,s)=>{e.startsWith("HS")||"dir"===e||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?((e,t,s)=>{if(!(t instanceof Uint8Array)){if(Y(t)){if(function(e){return"oct"===e.kty&&"string"==typeof e.k}(t)&&te(e,t,s))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(!V(t))throw new TypeError(F(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==t.type)throw new TypeError(`${ee(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,s):((e,t,s)=>{if(Y(t))switch(s){case"decrypt":case"sign":if(function(e){return"oct"!==e.kty&&("AKP"===e.kty&&"string"==typeof e.priv||"string"==typeof e.d)}(t)&&te(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d&&void 0===e.priv}(t)&&te(e,t,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!V(t))throw new TypeError(F(e,t,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===t.type)throw new TypeError(`${ee(t)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===t.type)switch(s){case"sign":throw new TypeError(`${ee(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ee(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===t.type)switch(s){case"verify":throw new TypeError(`${ee(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ee(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,s)},ne=async(e,t,s)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(((e,...t)=>U("Key must be ",e,...t))(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[s])}return L(t,e,s),t},ie=async(e,t,s,n)=>{const i=await ne(e,t,"verify");((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:s}=t.algorithm;if("number"!=typeof s||s<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}})(e,i);const o=((e,t)=>{const s=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new D(`alg ${e} is not supported either by JOSE or your javascript runtime`)}})(e,i.algorithm);try{return await crypto.subtle.verify(o,i,s,n)}catch{return!1}};async function oe(e,t,s){if(!G(e))throw new W("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new W('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new W("JWS Protected Header incorrect type");if(void 0===e.payload)throw new W("JWS Payload missing");if("string"!=typeof e.signature)throw new W("JWS Signature missing or incorrect type");if(void 0!==e.header&&!G(e.header))throw new W("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=x(e.protected);n=JSON.parse(I.decode(t))}catch{throw new W("JWS Protected Header is invalid")}if(!((...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let s;for(const n of t){const e=Object.keys(n);if(s&&0!==s.size)for(const t of e){if(s.has(t))return!1;s.add(t)}else s=new Set(e)}return!0})(n,e.header))throw new W("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const i={...n,...e.header},o=((e,t,s,n,i)=>{if(void 0!==i.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 o;o=void 0!==s?new Map([...Object.entries(s),...t.entries()]):t;for(const r of n.crit){if(!o.has(r))throw new D(`Extension Header Parameter "${r}" is not recognized`);if(void 0===i[r])throw new e(`Extension Header Parameter "${r}" is missing`);if(o.get(r)&&void 0===n[r])throw new e(`Extension Header Parameter "${r}" MUST be integrity protected`)}return new Set(n.crit)})(W,new Map([["b64",!0]]),s?.crit,n,i);let r=!0;if(o.has("b64")&&(r=n.b64,"boolean"!=typeof r))throw new W('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=i;if("string"!=typeof a||!a)throw new W('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=s&&((e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)})("algorithms",s.algorithms);if(c&&!c.has(a))throw new C('"alg" (Algorithm) Header Parameter value not allowed');if(r){if("string"!=typeof e.payload)throw new W("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new W("JWS Payload must be a string or an Uint8Array instance");let h=!1;"function"==typeof t&&(t=await t(n,e),h=!0),se(a,t,"verify");const d=function(...e){const t=e.reduce((e,{length:t})=>e+t,0),s=new Uint8Array(t);let n=0;for(const i of e)s.set(i,n),n+=i.length;return s}(T.encode(e.protected??""),T.encode("."),"string"==typeof e.payload?T.encode(e.payload):e.payload);let l;try{l=x(e.signature)}catch{throw new W("Failed to base64url decode the signature")}const g=await Q(t,a);if(!(await ie(a,g,l,d)))throw new H;let u;if(r)try{u=x(e.payload)}catch{throw new W("Failed to base64url decode the payload")}else u="string"==typeof e.payload?T.encode(e.payload):e.payload;const p={payload:u};return void 0!==e.protected&&(p.protectedHeader=n),void 0!==e.header&&(p.unprotectedHeader=e.header),h?{...p,key:g}:p}const re=86400,ae=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ce=e=>{const t=ae.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const s=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*s);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*s);break;case"day":case"days":case"d":n=Math.round(s*re);break;case"week":case"weeks":case"w":n=Math.round(604800*s);break;default:n=Math.round(31557600*s)}return"-"===t[1]||"ago"===t[4]?-n:n},he=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`;function de(e,t,s={}){let n;try{n=JSON.parse(I.decode(t))}catch{}if(!G(n))throw new M("JWT Claims Set must be a top-level JSON object");const{typ:i}=s;if(i&&("string"!=typeof e.typ||he(e.typ)!==he(i)))throw new R('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:o=[],issuer:r,subject:a,audience:c,maxTokenAge:h}=s,d=[...o];void 0!==h&&d.push("iat"),void 0!==c&&d.push("aud"),void 0!==a&&d.push("sub"),void 0!==r&&d.push("iss");for(const f of new Set(d.reverse()))if(!(f in n))throw new R(`missing required "${f}" claim`,n,f,"missing");if(r&&!(Array.isArray(r)?r:[r]).includes(n.iss))throw new R('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new R('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(l=n.aud,g="string"==typeof c?[c]:c,!("string"==typeof l?g.includes(l):Array.isArray(l)&&g.some(Set.prototype.has.bind(new Set(l))))))throw new R('unexpected "aud" claim value',n,"aud","check_failed");var l,g;let u;switch(typeof s.clockTolerance){case"string":u=ce(s.clockTolerance);break;case"number":u=s.clockTolerance;break;case"undefined":u=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:p}=s,m=(y=p||new Date,Math.floor(y.getTime()/1e3));var y;if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new R('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new R('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>m+u)throw new R('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new R('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=m-u)throw new $('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=m-n.iat;if(e-u>("number"==typeof h?h:ce(h)))throw new $('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-u)throw new R('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function le(e,t,s){const n=await async function(e,t,s){if(e instanceof Uint8Array&&(e=I.decode(e)),"string"!=typeof e)throw new W("Compact JWS must be a string or Uint8Array");const{0:n,1:i,2:o,length:r}=e.split(".");if(3!==r)throw new W("Invalid Compact JWS");const a=await oe({payload:i,protected:n,signature:o},t,s),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}(e,t,s);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new M("JWTs MUST NOT use unencoded payload");const i={payload:de(n.protectedHeader,n.payload,s),protectedHeader:n.protectedHeader};return"function"==typeof t?{...i,key:n.key}:i}function ge(e){return G(e)}class ue{constructor(e){if(b(this,n),b(this,i,new WeakMap),!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(ge)}(e))throw new _("JSON Web Key Set malformed");E(this,n,structuredClone(e))}jwks(){return S(this,n)}async getKey(e,t){const{alg:s,kid:o}={...e,...t?.header},r=function(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new D('Unsupported "alg" value for a JSON Web Key Set')}}(s),a=S(this,n).keys.filter(e=>{let t=r===e.kty;if(t&&"string"==typeof o&&(t=o===e.kid),!t||"string"!=typeof e.alg&&"AKP"!==r||(t=s===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(s){case"ES256":t="P-256"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":case"EdDSA":t="Ed25519"===e.crv}return t}),{0:c,length:h}=a;if(0===h)throw new K;if(1!==h){const e=new O,t=S(this,i);throw e[Symbol.asyncIterator]=async function*(){for(const e of a)try{yield await pe(t,e,s)}catch{}},e}return pe(S(this,i),c,s)}}async function pe(e,t,s){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[s]){const e=await async function(e,t){if(!G(e))throw new TypeError("JWK must be an object");let s;switch(t??(t=e.alg),s??(s=e.ext),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return x(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new D('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return q({...e,alg:t,ext:s});case"AKP":if("string"!=typeof e.alg||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==t&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return q({...e,ext:s});case"EC":case"OKP":return q({...e,alg:t,ext:s});default:throw new D('Unsupported "kty" (Key Type) Parameter value')}}({...t,ext:!0},s);if(e instanceof Uint8Array||"public"!==e.type)throw new _("JSON Web Key Set members must be public keys");n[s]=e}return n[s]}function me(e){const t=new ue(e),s=async(e,s)=>t.getKey(e,s);return Object.defineProperties(s,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),s}let ye;if(n=new WeakMap,i=new WeakMap,"undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){ye=`${"jose"}/${"v6.1.0"}`}const fe=Symbol();const we=Symbol();class Se{constructor(e,t){if(b(this,o),b(this,r),b(this,a),b(this,c),b(this,h),b(this,d),b(this,l),b(this,g),b(this,u),b(this,p),!(e instanceof URL))throw new TypeError("url must be an instance of URL");var s,n;E(this,o,new URL(e.href)),E(this,r,"number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3),E(this,a,"number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4),E(this,c,"number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5),E(this,l,new Headers(t?.headers)),ye&&!S(this,l).has("User-Agent")&&S(this,l).set("User-Agent",ye),S(this,l).has("accept")||(S(this,l).set("accept","application/json"),S(this,l).append("accept","application/jwk-set+json")),E(this,g,t?.[fe]),void 0!==t?.[we]&&(E(this,p,t?.[we]),s=t?.[we],n=S(this,c),"object"==typeof s&&null!==s&&"uat"in s&&"number"==typeof s.uat&&!(Date.now()-s.uat>=n)&&"jwks"in s&&G(s.jwks)&&Array.isArray(s.jwks.keys)&&Array.prototype.every.call(s.jwks.keys,G)&&(E(this,h,S(this,p).uat),E(this,u,me(S(this,p).jwks))))}pendingFetch(){return!!S(this,d)}coolingDown(){return"number"==typeof S(this,h)&&Date.now()<S(this,h)+S(this,a)}fresh(){return"number"==typeof S(this,h)&&Date.now()<S(this,h)+S(this,c)}jwks(){return S(this,u)?.jwks()}async getKey(e,t){S(this,u)&&this.fresh()||await this.reload();try{return await S(this,u).call(this,e,t)}catch(s){if(s instanceof K&&!1===this.coolingDown())return await this.reload(),S(this,u).call(this,e,t);throw s}}async reload(){S(this,d)&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&E(this,d,void 0),S(this,d)||E(this,d,async function(e,t,s,n=fetch){const i=await n(e,{method:"GET",signal:s,redirect:"manual",headers:t}).catch(e=>{if("TimeoutError"===e.name)throw new P;throw e});if(200!==i.status)throw new A("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new A("Failed to parse the JSON Web Key Set HTTP response as JSON")}}(S(this,o).href,S(this,l),AbortSignal.timeout(S(this,r)),S(this,g)).then(e=>{E(this,u,me(e)),S(this,p)&&(S(this,p).uat=Date.now(),S(this,p).jwks=e),E(this,h,Date.now()),E(this,d,void 0)}).catch(e=>{throw E(this,d,void 0),e})),await S(this,d)}}function be(e,t){const s=new Se(e,t),n=async(e,t)=>s.getKey(e,t);return Object.defineProperties(n,{coolingDown:{get:()=>s.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>s.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>s.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>s.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>s.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}o=new WeakMap,r=new WeakMap,a=new WeakMap,c=new WeakMap,h=new WeakMap,d=new WeakMap,l=new WeakMap,g=new WeakMap,u=new WeakMap,p=new WeakMap;class Ee{constructor(e=!1,t="[MarketplaceSDK]"){this.debug=e,this.prefix=t}log(...e){this.debug}info(...e){this.debug}warn(...e){}error(...e){}}class ve{constructor(e,t=!1){this.jwksUri=e,this.logger=new Ee(t,"[JWKSValidator]");const s=this.jwksUri.startsWith("http")?new URL(this.jwksUri):new URL(this.jwksUri,"undefined"!=typeof window?window.location.origin:void 0);this.jwks=be(s),this.logger.info("Initialized with JWKS URI:",this.jwksUri)}async verify(e,t="generalwisdom.com",s){this.logger.log("Verifying JWT signature...");try{const n=(await le(e,this.jwks,{issuer:t,algorithms:["RS256"]})).payload,i=["sessionId","userId","orgId","applicationId","exp","iat"];for(const e of i)if(!(e in n))throw new v(`Missing required claim: ${e}`,"MISSING_CLAIM");if(s&&n.applicationId!==s)throw this.logger.error(`Application ID mismatch: expected ${s}, got ${n.applicationId}`),new v("Token is for a different application","APPLICATION_MISMATCH");const o={sessionId:n.sessionId,applicationId:n.applicationId,userId:n.userId,orgId:n.orgId,startTime:n.startTime,durationMinutes:n.durationMinutes,iat:n.iat,exp:n.exp,iss:n.iss,sub:n.sub};return this.logger.log("JWT verified successfully"),o}catch(n){if(this.logger.error("JWT verification failed:",n),n instanceof v)throw n;const e=n instanceof Error?n.message:"Unknown error",t=n instanceof Error?n.name:"Error";if("JWTExpired"===t||e.includes("expired"))throw new v("Session expired","SESSION_EXPIRED");if("JWSSignatureVerificationFailed"===t)throw new v("Invalid JWT signature","INVALID_SIGNATURE");if("JWTClaimValidationFailed"===t)throw new v(`JWT claim validation failed: ${e}`,"INVALID_CLAIM");throw new v(`JWT verification failed: ${e}`,"VERIFICATION_FAILED")}}updateJwksUri(e){this.jwksUri=e;const t=this.jwksUri.startsWith("http")?new URL(this.jwksUri):new URL(this.jwksUri,"undefined"!=typeof window?window.location.origin:void 0);this.jwks=be(t),this.logger.info("Updated JWKS URI:",this.jwksUri)}}class ke{constructor(e,t=300,s={},n=!1){this.intervalId=null,this.warningShown=!1,this.remainingSeconds=e,this.warningThreshold=t,this.events=s,this.logger=new Ee(n,"[TimerManager]"),this.logger.log("Initialized with duration:",e,"seconds")}start(){null===this.intervalId?(this.logger.log("Starting timer with",this.remainingSeconds,"seconds remaining"),this.intervalId=window.setInterval(()=>{this.remainingSeconds--,!this.warningShown&&this.remainingSeconds<=this.warningThreshold&&this.remainingSeconds>0&&(this.warningShown=!0,this.logger.warn("Warning threshold reached:",this.remainingSeconds,"seconds remaining"),this.events.onSessionWarning?.({remainingSeconds:this.remainingSeconds})),this.remainingSeconds<=0&&(this.logger.warn("Session expired"),this.stop(),this.events.onSessionEnd?.())},1e3)):this.logger.warn("Timer already running")}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.logger.log("Timer stopped"))}pause(){this.stop(),this.logger.log("Timer paused at:",this.remainingSeconds,"seconds")}resume(){null===this.intervalId&&this.remainingSeconds>0&&(this.start(),this.logger.log("Timer resumed at:",this.remainingSeconds,"seconds"))}getRemainingSeconds(){return this.remainingSeconds}getFormattedTime(){return`${Math.floor(this.remainingSeconds/60)}:${(this.remainingSeconds%60).toString().padStart(2,"0")}`}getFormattedTimeWithHours(){const e=Math.floor(this.remainingSeconds/3600),t=Math.floor(this.remainingSeconds%3600/60),s=this.remainingSeconds%60;return e>0?`${e}:${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:this.getFormattedTime()}isRunning(){return null!==this.intervalId}hasWarningBeenShown(){return this.warningShown}updateRemainingTime(e){this.remainingSeconds=e,this.logger.log("Remaining time updated to:",e,"seconds")}}class Te{constructor(e,t,s,n,i,o=30,r=!1){this.sessionId=e,this.apiEndpoint=t,this.token=s,this.onSync=n,this.onError=i,this.intervalId=null,this.failureCount=0,this.maxFailures=3,this.isEnabled=!1,this.heartbeatInterval=1e3*o,this.logger=new Ee(r,"[HeartbeatManager]"),this.logger.log("Initialized with",o,"second interval")}start(){null===this.intervalId?(this.isEnabled=!0,this.logger.log("Starting heartbeat for session:",this.sessionId),this.sendHeartbeat(),this.intervalId=window.setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)):this.logger.warn("Heartbeat already running")}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.isEnabled=!1,this.logger.log("Heartbeat stopped"))}async sendHeartbeat(){if(this.isEnabled){this.logger.log("Sending heartbeat...");try{const e=await fetch(`${this.apiEndpoint}/sessions/${this.sessionId}/heartbeat`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({timestamp:Date.now(),active:!0})});if(!e.ok)throw new v(`Heartbeat failed with status ${e.status}`,"HEARTBEAT_FAILED",e.status);const t=await e.json();this.failureCount=0,"number"==typeof t.remaining_seconds&&(this.logger.log("Server reports",t.remaining_seconds,"seconds remaining"),this.onSync?.(t.remaining_seconds)),this.logger.log("Heartbeat acknowledged")}catch(e){if(this.failureCount++,this.logger.error("Heartbeat failed:",e,`(${this.failureCount}/${this.maxFailures})`),this.failureCount>=this.maxFailures){this.logger.error("Max heartbeat failures reached, stopping"),this.stop();const t=e instanceof v?e:new v(e instanceof Error?e.message:"Heartbeat failed","HEARTBEAT_ERROR");this.onError?.(t)}}}}isRunning(){return null!==this.intervalId}getFailureCount(){return this.failureCount}updateInterval(e){const t=this.isRunning();t&&this.stop(),this.heartbeatInterval=1e3*e,this.logger.log("Heartbeat interval updated to",e,"seconds"),t&&this.start()}}class Ie{constructor(e,t,s=!1){this.sessionId=e,this.onMessage=t,this.channel=null,this.isMaster=!1,this.handleStorageEvent=e=>{if(e.key===this.storageKey&&e.newValue)try{const t=JSON.parse(e.newValue);this.handleMessage(t)}catch(t){this.logger.error("Failed to parse storage event:",t)}},this.storageKey=`gw_session_sync_${e}`,this.logger=new Ee(s,"[TabSyncManager]"),this.initialize()}initialize(){"undefined"!=typeof BroadcastChannel?(this.logger.log("Using BroadcastChannel for tab sync"),this.channel=new BroadcastChannel(`gw-session-${this.sessionId}`),this.channel.onmessage=e=>{this.handleMessage(e.data)}):(this.logger.log("Using localStorage for tab sync (fallback)"),window.addEventListener("storage",this.handleStorageEvent)),this.electMaster()}broadcast(e,t){const s={type:e,sessionId:this.sessionId,timestamp:Date.now(),...t};this.channel?(this.channel.postMessage(s),this.logger.log("Broadcasted:",e)):(localStorage.setItem(this.storageKey,JSON.stringify(s)),this.logger.log("Broadcasted via localStorage:",e))}handleMessage(e){e.sessionId===this.sessionId&&(this.logger.log("Received message:",e.type),this.onMessage(e))}electMaster(){const e=`gw_session_master_${this.sessionId}`;localStorage.getItem(e)?(this.logger.log("Another tab is master"),setInterval(()=>{const t=localStorage.getItem(e);if(t){Date.now()-parseInt(t)>1e4&&(this.logger.warn("Master tab appears dead, becoming master"),this.isMaster=!0,localStorage.setItem(e,Date.now().toString()))}},5e3)):(this.isMaster=!0,localStorage.setItem(e,Date.now().toString()),this.logger.log("Elected as master tab"),setInterval(()=>{this.isMaster&&localStorage.setItem(e,Date.now().toString())},5e3),window.addEventListener("beforeunload",()=>{this.isMaster&&(localStorage.removeItem(e),this.logger.log("Removed master status"))}))}isMasterTab(){return this.isMaster}destroy(){this.channel?(this.channel.close(),this.channel=null):window.removeEventListener("storage",this.handleStorageEvent),localStorage.removeItem(this.storageKey),this.isMaster&&localStorage.removeItem(`gw_session_master_${this.sessionId}`),this.logger.log("Tab sync destroyed")}}const xe={colors:{background:"hsl(0 0% 100%)",foreground:"hsl(222.2 84% 4.9%)",card:"hsl(0 0% 100%)",cardForeground:"hsl(222.2 84% 4.9%)",popover:"hsl(0 0% 100%)",popoverForeground:"hsl(222.2 84% 4.9%)",primary:"hsl(221.2 83.2% 53.3%)",primaryForeground:"hsl(210 40% 98%)",secondary:"hsl(210 40% 96.1%)",secondaryForeground:"hsl(222.2 47.4% 11.2%)",muted:"hsl(210 40% 96.1%)",mutedForeground:"hsl(215.4 16.3% 46.9%)",accent:"hsl(210 40% 96.1%)",accentForeground:"hsl(222.2 47.4% 11.2%)",destructive:"hsl(0 84.2% 60.2%)",destructiveForeground:"hsl(210 40% 98%)",success:"hsl(142 76% 36%)",successForeground:"hsl(0 0% 100%)",border:"hsl(214.3 31.8% 91.4%)",input:"hsl(214.3 31.8% 91.4%)",ring:"hsl(221.2 83.2% 53.3%)"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{xs:"12px",sm:"14px",base:"16px",lg:"18px",xl:"20px","2xl":"24px"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.75"}},spacing:{borderRadius:{sm:"4px",md:"6px",lg:"8px"},padding:{sm:"8px",md:"16px",lg:"24px",xl:"32px"},gap:{sm:"8px",md:"12px",lg:"16px"}}},Ae={colors:{background:"hsl(222.2 84% 4.9%)",foreground:"hsl(210 40% 98%)",card:"hsl(222.2 84% 4.9%)",cardForeground:"hsl(210 40% 98%)",popover:"hsl(222.2 84% 4.9%)",popoverForeground:"hsl(210 40% 98%)",primary:"hsl(217.2 91.2% 59.8%)",primaryForeground:"hsl(222.2 47.4% 11.2%)",secondary:"hsl(217.2 32.6% 17.5%)",secondaryForeground:"hsl(210 40% 98%)",muted:"hsl(217.2 32.6% 17.5%)",mutedForeground:"hsl(215 20.2% 65.1%)",accent:"hsl(217.2 32.6% 17.5%)",accentForeground:"hsl(210 40% 98%)",destructive:"hsl(0 62.8% 30.6%)",destructiveForeground:"hsl(210 40% 98%)",success:"hsl(142 71% 45%)",successForeground:"hsl(0 0% 100%)",border:"hsl(217.2 32.6% 17.5%)",input:"hsl(217.2 32.6% 17.5%)",ring:"hsl(224.3 76.3% 48%)"},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',fontSize:{xs:"12px",sm:"14px",base:"16px",lg:"18px",xl:"20px","2xl":"24px"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.75"}},spacing:{borderRadius:{sm:"4px",md:"6px",lg:"8px"},padding:{sm:"8px",md:"16px",lg:"24px",xl:"32px"},gap:{sm:"8px",md:"12px",lg:"16px"}}};function Re(e){if(void 0!==e)return e?Ae:xe;if("undefined"!=typeof window&&window.matchMedia){return window.matchMedia("(prefers-color-scheme: dark)").matches?Ae:xe}return xe}class $e{constructor(e="light",t){this.modal=null,this.legacyStyles=null,this.updateInterval=null,this.timeDisplay=null,this.startTime=0,this.initialSeconds=0,this.onEndCallback=void 0;const s="dark"===e||"auto"===e&&this.detectDarkMode();this.theme=Re(s),t&&(this.legacyStyles={backgroundColor:t.backgroundColor||"#ffffff",textColor:t.textColor||"#333333",primaryColor:t.primaryColor||"#007bff",borderRadius:t.borderRadius||"8px",fontFamily:t.fontFamily||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'})}detectDarkMode(){return!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-color-scheme: dark)").matches}show(e){this.hide(),this.modal=document.createElement("div"),this.modal.id="gw-session-warning-modal",this.modal.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 99999;\n font-family: ${this.legacyStyles?.fontFamily||this.theme.typography.fontFamily};\n `;const t=document.createElement("div"),s=this.legacyStyles?.backgroundColor||this.theme.colors.card,n=this.legacyStyles?.textColor||this.theme.colors.cardForeground,i=this.legacyStyles?.borderRadius||this.theme.spacing.borderRadius.lg;t.style.cssText=`\n background-color: ${s};\n color: ${n};\n border-radius: ${i};\n padding: ${this.theme.spacing.padding.lg};\n max-width: 400px;\n width: 90%;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border: 1px solid ${this.theme.colors.border};\n `,this.initialSeconds=e.remainingSeconds,this.startTime=Date.now(),this.onEndCallback=e.onEnd;const o=Math.floor(e.remainingSeconds/60),r=e.remainingSeconds%60;t.innerHTML=`\n <h2 style="margin: 0 0 ${this.theme.spacing.padding.md} 0; font-size: ${this.theme.typography.fontSize.xl}; font-weight: ${this.theme.typography.fontWeight.semibold}; color: ${n};">\n ⏱️ Time Running Low\n </h2>\n <p style="margin: 0 0 ${this.theme.spacing.padding.lg} 0; font-size: ${this.theme.typography.fontSize.base}; line-height: ${this.theme.typography.lineHeight.normal}; color: ${this.theme.colors.mutedForeground};">\n Your session will expire in <strong id="gw-time-display" style="color: ${n};">${o}:${r.toString().padStart(2,"0")}</strong>.\n </p>\n <div style="display: flex; gap: ${this.theme.spacing.gap.md}; justify-content: flex-end;">\n <button id="gw-dismiss-btn" style="\n padding: 10px 20px;\n background-color: ${this.theme.colors.secondary};\n color: ${this.theme.colors.secondaryForeground};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n cursor: pointer;\n transition: all 0.2s;\n font-family: ${this.theme.typography.fontFamily};\n ">\n Continue\n </button>\n ${e.onExtend?`<button id="gw-extend-btn" style="\n padding: 10px 20px;\n background-color: ${this.theme.colors.success};\n color: ${this.theme.colors.successForeground};\n border: none;\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n cursor: pointer;\n transition: all 0.2s;\n font-family: ${this.theme.typography.fontFamily};\n ">\n Extend Session\n </button>`:""}\n ${e.onEnd?`<button id="gw-end-btn" style="\n padding: 10px 20px;\n background-color: ${this.theme.colors.destructive};\n color: ${this.theme.colors.destructiveForeground};\n border: none;\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n cursor: pointer;\n transition: all 0.2s;\n font-family: ${this.theme.typography.fontFamily};\n ">\n End Session\n </button>`:""}\n </div>\n `,this.modal.appendChild(t),document.body.appendChild(this.modal);const a=document.getElementById("gw-extend-btn");a&&e.onExtend&&a.addEventListener("click",()=>{e.onExtend?.(),this.hide()});const c=document.getElementById("gw-dismiss-btn");c&&c.addEventListener("click",()=>{this.hide()});const h=document.getElementById("gw-end-btn");h&&e.onEnd&&h.addEventListener("click",()=>{e.onEnd?.()});t.querySelectorAll("button").forEach(e=>{e.addEventListener("mouseenter",()=>{e.style.opacity="0.9"}),e.addEventListener("mouseleave",()=>{e.style.opacity="1"}),e.addEventListener("focus",()=>{e.style.outline=`2px solid ${this.theme.colors.ring}`,e.style.outlineOffset="2px"}),e.addEventListener("blur",()=>{e.style.outline="none"})}),this.timeDisplay=document.getElementById("gw-time-display"),this.updateInterval=window.setInterval(()=>{const e=Math.floor((Date.now()-this.startTime)/1e3),t=Math.max(0,this.initialSeconds-e),s=Math.floor(t/60),n=t%60;this.timeDisplay&&(this.timeDisplay.textContent=`${s}:${n.toString().padStart(2,"0")}`),0===t&&(this.onEndCallback&&this.onEndCallback(),this.hide())},1e3)}hide(){null!==this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.modal&&this.modal.parentNode&&(this.modal.parentNode.removeChild(this.modal),this.modal=null,this.timeDisplay=null)}isShown(){return null!==this.modal}showEndingMessage(e,t=3e3){this.hide();const s=this.legacyStyles?.backgroundColor||this.theme.colors.card,n=this.legacyStyles?.textColor||this.theme.colors.cardForeground,i=this.legacyStyles?.borderRadius||this.theme.spacing.borderRadius.lg;this.modal=document.createElement("div"),this.modal.id="gw-session-ending-modal",this.modal.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 99999;\n font-family: ${this.legacyStyles?.fontFamily||this.theme.typography.fontFamily};\n animation: fadeIn 0.2s ease-in;\n `;const o=document.createElement("div");o.style.cssText=`\n background-color: ${s};\n color: ${n};\n border-radius: ${i};\n padding: ${this.theme.spacing.padding.xl};\n max-width: 400px;\n width: 90%;\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n text-align: center;\n animation: slideIn 0.3s ease-out;\n border: 1px solid ${this.theme.colors.border};\n `,o.innerHTML=`\n <div style="font-size: 48px; margin-bottom: ${this.theme.spacing.padding.lg};">⏱️</div>\n <h2 style="margin: 0 0 ${this.theme.spacing.padding.md} 0; font-size: ${this.theme.typography.fontSize["2xl"]}; font-weight: ${this.theme.typography.fontWeight.semibold}; color: ${this.theme.colors.destructive};">\n Session Ending\n </h2>\n <p style="margin: 0 0 ${this.theme.spacing.padding.lg} 0; font-size: ${this.theme.typography.fontSize.base}; line-height: ${this.theme.typography.lineHeight.normal}; color: ${this.theme.colors.mutedForeground};">\n Your session has expired.<br/>\n Redirecting to marketplace...\n </p>\n <div style="\n width: 100%;\n height: 4px;\n background: ${this.theme.colors.muted};\n border-radius: ${this.theme.spacing.borderRadius.sm};\n overflow: hidden;\n margin-top: ${this.theme.spacing.padding.lg};\n ">\n <div id="gw-progress-bar" style="\n width: 100%;\n height: 100%;\n background: linear-gradient(90deg, ${this.theme.colors.destructive}, ${this.theme.colors.primary});\n animation: progressBar ${t}ms linear forwards;\n "></div>\n </div>\n `;const r=document.createElement("style");r.textContent="\n @keyframes fadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n @keyframes slideIn {\n from { transform: translateY(-20px); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n @keyframes progressBar {\n from { width: 100%; }\n to { width: 0%; }\n }\n ",document.head.appendChild(r),this.modal.appendChild(o),document.body.appendChild(this.modal),setTimeout(()=>{this.hide(),e()},t)}}function Ce(e="gwSession",t){try{const s=t||("undefined"!=typeof window?window.location.href:"");if(!s)return null;const n=new URL(s);return n.searchParams.get(e)}catch(s){throw new v(`Failed to extract token from URL: ${s instanceof Error?s.message:"Unknown error"}`,"URL_PARSE_ERROR")}}class De{constructor(e){this.timer=null,this.heartbeat=null,this.tabSync=null,this.modal=null,this.events={},this.sessionData=null,this.jwtToken=null,this.endReason="manual",this.config={jwksUri:e.jwksUri||"https://api.generalwisdom.com/.well-known/jwks.json",jwtParamName:e.jwtParamName||"gwSession",apiEndpoint:e.apiEndpoint||"http://localhost:3000",debug:e.debug??!1,autoStart:e.autoStart??!0,warningThresholdSeconds:e.warningThresholdSeconds??300,customStyles:e.customStyles??{},themeMode:e.themeMode??"light",applicationId:e.applicationId??"",marketplaceUrl:e.marketplaceUrl??"https://d3p2yqofgy75sz.cloudfront.net/",enableHeartbeat:e.enableHeartbeat??!1,heartbeatIntervalSeconds:e.heartbeatIntervalSeconds??30,enableTabSync:e.enableTabSync??!1,pauseOnHidden:e.pauseOnHidden??!1,useBackendValidation:e.useBackendValidation??!1,hooks:e.hooks??{},hookTimeoutMs:e.hookTimeoutMs??5e3},this.validator=new ve(this.config.jwksUri,this.config.debug),this.logger=new Ee(this.config.debug,"[MarketplaceSDK]"),this.logger.info("SDK initialized with config:",{jwksUri:this.config.jwksUri,jwtParamName:this.config.jwtParamName,apiEndpoint:this.config.apiEndpoint,enableHeartbeat:this.config.enableHeartbeat,enableTabSync:this.config.enableTabSync,pauseOnHidden:this.config.pauseOnHidden})}on(e,t){this.events[e]=t,this.logger.log("Event handler registered:",e)}async executeHook(e,t,s,n=!0){if(!t)return;this.logger.log(`Calling ${e} hook`);const i=new Promise((t,s)=>setTimeout(()=>s(new v(`${e} hook timeout after ${this.config.hookTimeoutMs}ms`,"HOOK_TIMEOUT")),this.config.hookTimeoutMs));try{await Promise.race([Promise.resolve(t(s)),i]),this.logger.log(`${e} hook completed successfully`)}catch(o){if(this.logger.error(`${e} hook failed:`,o),n)throw new v(`${e} hook failed: ${o instanceof Error?o.message:"Unknown error"}`,"HOOK_ERROR");this.logger.warn(`${e} hook failed but continuing (lenient mode)`)}}calculateActualDuration(){if(!this.sessionData)return;const e=Math.floor(Date.now()/1e3)-this.sessionData.startTime;return Math.ceil(e/60)}async initialize(){this.logger.info("Initializing session...");try{const e="gw_marketplace_jwt";if(this.jwtToken=Ce(this.config.jwtParamName),this.jwtToken||"undefined"==typeof sessionStorage||(this.jwtToken=sessionStorage.getItem(e),this.jwtToken&&this.logger.log("JWT token retrieved from storage")),!this.jwtToken)throw new v(`No token found in URL parameter '${this.config.jwtParamName}' or storage`,"MISSING_TOKEN");let t;"undefined"!=typeof sessionStorage&&(sessionStorage.setItem(e,this.jwtToken),this.logger.log("JWT token stored in sessionStorage")),this.logger.log("JWT token extracted from URL"),this.config.useBackendValidation?(this.logger.log("Using backend validation"),t=await this.validateWithBackend(this.jwtToken)):(this.logger.log("Using JWKS validation"),t=await this.validator.verify(this.jwtToken,"generalwisdom.com",this.config.applicationId||void 0)),this.logger.log("JWT verified successfully"),this.sessionData={sessionId:t.sessionId,applicationId:t.applicationId,userId:t.userId,orgId:t.orgId,startTime:t.startTime,durationMinutes:t.durationMinutes,iat:t.iat,exp:t.exp,iss:t.iss,sub:t.sub};const s=Math.floor(Date.now()/1e3),n=Math.max(0,this.sessionData.exp-s);if(n<=0)throw new v("Session has already expired","SESSION_EXPIRED");if(this.logger.log("Remaining time:",n,"seconds"),this.config.hooks?.onSessionStart){const e={sessionId:this.sessionData.sessionId,userId:this.sessionData.userId,email:t.email,orgId:this.sessionData.orgId,applicationId:this.sessionData.applicationId,durationMinutes:this.sessionData.durationMinutes,expiresAt:this.sessionData.exp,jwt:this.jwtToken};await this.executeHook("onSessionStart",this.config.hooks.onSessionStart,e,!0),this.logger.log("Application auth synchronized with marketplace session")}if(this.timer=new ke(n,this.config.warningThresholdSeconds,{onSessionWarning:e=>{if(this.config.hooks?.onSessionWarning){const t={sessionId:this.sessionData.sessionId,userId:this.sessionData.userId,remainingSeconds:e.remainingSeconds};this.executeHook("onSessionWarning",this.config.hooks.onSessionWarning,t,!1).catch(e=>this.logger.error("onSessionWarning hook failed:",e))}this.showWarningModal(e.remainingSeconds),this.events.onSessionWarning?.(e)},onSessionEnd:()=>{this.endReason="expired",this.endSession()}},this.config.debug),this.config.enableHeartbeat&&this.jwtToken&&(this.heartbeat=new Te(this.sessionData.sessionId,this.config.apiEndpoint,this.jwtToken,e=>{this.timer?.updateRemainingTime(e)},e=>{this.logger.error("Heartbeat error:",e),this.events.onError?.(e)},this.config.heartbeatIntervalSeconds,this.config.debug)),this.config.enableTabSync&&(this.tabSync=new Ie(this.sessionData.sessionId,e=>this.handleTabSyncMessage(e),this.config.debug)),this.config.pauseOnHidden&&this.initializeVisibilityHandling(),this.config.autoStart&&(this.timer.start(),this.logger.log("Timer started automatically"),this.config.enableHeartbeat&&this.heartbeat)){!this.tabSync||this.tabSync.isMasterTab()?(this.heartbeat.start(),this.logger.log("Heartbeat started (master tab)")):this.logger.log("Heartbeat not started (slave tab)")}return this.events.onSessionStart?.(this.sessionData),this.logger.info("Session initialized successfully"),this.sessionData}catch(e){this.logger.error("Initialization failed:",e);const t=e instanceof v?e:new v(e instanceof Error?e.message:"Unknown error","INITIALIZATION_ERROR");throw this.events.onError?.(t),t}}async validateWithBackend(e){const t=await fetch(`${this.config.apiEndpoint}/sessions/validate`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({session_jwt:e})});if(!t.ok)throw new v("Backend validation failed","BACKEND_VALIDATION_FAILED",t.status);const s=await t.json();if(!s.valid)throw new v(s.error||"Session validation failed","SESSION_INVALID");return k.decode(e)}handleTabSyncMessage(e){switch(this.logger.log("Tab sync message:",e.type),e.type){case"pause":this.timer?.pause();break;case"resume":this.timer?.resume();break;case"end":this.endSession();break;case"timer_update":void 0!==e.remainingSeconds&&this.timer?.updateRemainingTime(e.remainingSeconds)}}initializeVisibilityHandling(){document.addEventListener("visibilitychange",()=>{document.hidden?(this.logger.log("Tab hidden, pausing timer"),this.pauseTimer()):(this.logger.log("Tab visible, resuming timer"),this.resumeTimer())}),this.logger.log("Visibility API handler initialized")}startTimer(){if(!this.timer)throw new v("SDK not initialized. Call initialize() first.","NOT_INITIALIZED");this.timer.start(),this.tabSync?.broadcast("resume"),this.logger.info("Timer started manually")}pauseTimer(){this.timer?.pause(),this.tabSync?.broadcast("pause"),this.logger.info("Timer paused")}resumeTimer(){this.timer?.resume(),this.tabSync?.broadcast("resume"),this.logger.info("Timer resumed")}async extendSession(e){if(!this.sessionData||!this.jwtToken)throw new v("No active session","NO_SESSION");this.logger.info("Extending session by",e,"minutes");try{const t=await fetch(`${this.config.apiEndpoint}/sessions/${this.sessionData.sessionId}/renew`,{method:"PUT",headers:{Authorization:`Bearer ${this.jwtToken}`,"Content-Type":"application/json"},body:JSON.stringify({additional_minutes:e})});if(!t.ok)throw new v("Session extension failed","EXTENSION_FAILED",t.status);const s=await t.json();this.sessionData.exp=s.new_expires_at;const n=Math.floor(Date.now()/1e3),i=s.new_expires_at-n;if(this.timer?.updateRemainingTime(i),this.tabSync?.broadcast("timer_update",{remainingSeconds:i}),this.config.hooks?.onSessionExtend){const t={sessionId:this.sessionData.sessionId,userId:this.sessionData.userId,additionalMinutes:e,newExpiresAt:s.new_expires_at};await this.executeHook("onSessionExtend",this.config.hooks.onSessionExtend,t,!1)}this.logger.info("Session extended successfully")}catch(t){this.logger.error("Failed to extend session:",t);const e=t instanceof v?t:new v(t instanceof Error?t.message:"Extension failed","EXTENSION_ERROR");throw this.events.onError?.(e),e}}async completeSession(e){if(!this.sessionData||!this.jwtToken)throw new v("No active session","NO_SESSION");this.logger.info("Completing session...");try{const t=await fetch(`${this.config.apiEndpoint}/sessions/${this.sessionData.sessionId}/complete`,{method:"POST",headers:{Authorization:`Bearer ${this.jwtToken}`,"Content-Type":"application/json"},body:JSON.stringify({actual_usage_minutes:e,metadata:{}})});if(!t.ok)throw new v("Session completion failed","COMPLETION_FAILED",t.status);const s=await t.json();this.logger.info("Session completed:",s),this.endSession()}catch(t){this.logger.error("Failed to complete session:",t);const e=t instanceof v?t:new v(t instanceof Error?t.message:"Completion failed","COMPLETION_ERROR");throw this.events.onError?.(e),e}}async endSession(){this.logger.info("Ending session...");const e={sessionId:this.sessionData?.sessionId||"",userId:this.sessionData?.userId||"",reason:this.endReason,actualDurationMinutes:this.calculateActualDuration()};if(this.config.hooks?.onSessionEnd)try{await this.executeHook("onSessionEnd",this.config.hooks.onSessionEnd,e,!1),this.logger.log("Application auth cleanup completed")}catch(t){this.logger.error("onSessionEnd hook error (continuing anyway):",t)}this.timer?.stop(),this.heartbeat?.stop(),this.tabSync?.broadcast("end"),"undefined"!=typeof sessionStorage&&(sessionStorage.removeItem("gw_marketplace_jwt"),this.logger.log("JWT token cleared from storage")),this.events.onSessionEnd?.(),this.logger.info("Session ended"),"undefined"!=typeof window&&(this.modal||(this.modal=new $e(this.config.themeMode||"light",this.config.customStyles)),this.modal.showEndingMessage(()=>{window.location.href=this.config.marketplaceUrl},3e3))}showWarningModal(e){this.modal||(this.modal=new $e(this.config.themeMode||"light",this.config.customStyles)),this.modal.show({remainingSeconds:e,onExtend:async()=>{try{await this.extendSession(15),this.modal?.hide(),this.logger.log("Session extended successfully from modal")}catch(e){this.logger.error("Extension failed, redirecting to marketplace:",e);const t=`${this.config.marketplaceUrl}extend-session?sessionId=${this.sessionData?.sessionId}`;"undefined"!=typeof window&&(this.modal||(this.modal=new $e(this.config.themeMode||"light",this.config.customStyles)),this.modal.showEndingMessage(()=>{window.location.href=t},3e3))}},onEnd:()=>{this.endSession()}})}getSessionData(){return this.sessionData}getRemainingTime(){return this.timer?.getRemainingSeconds()??0}getFormattedTime(){return this.timer?.getFormattedTime()??"0:00"}getFormattedTimeWithHours(){return this.timer?.getFormattedTimeWithHours()??"0:00:00"}isTimerRunning(){return this.timer?.isRunning()??!1}destroy(){this.logger.info("Destroying SDK instance..."),this.timer?.stop(),this.heartbeat?.stop(),this.tabSync?.destroy(),this.modal?.hide(),"undefined"!=typeof sessionStorage&&(sessionStorage.removeItem("gw_marketplace_jwt"),this.logger.log("JWT token cleared from storage")),this.sessionData=null,this.jwtToken=null}}e.HeartbeatManager=Te,e.JWKSValidator=ve,e.JWTParser=k,e.Logger=Ee,e.MarketplaceSDK=De,e.SDKError=v,e.SessionHeader=class{constructor(e="auto"){this.container=null,this.updateInterval=null,this.timeDisplay=null,this.mounted=!1;const t="dark"===e||"auto"===e&&this.detectDarkMode();this.theme=Re(t)}detectDarkMode(){return!("undefined"==typeof window||!window.matchMedia)&&window.matchMedia("(prefers-color-scheme: dark)").matches}mount(e,t){this.mounted&&this.unmount();const s="string"==typeof e?document.querySelector(e):e;if(!s)return;this.getTimeCallback=t.getTime,this.onExtendCallback=t.onExtend,this.onEndCallback=t.onEnd,this.container=document.createElement("div"),this.container.id="gw-session-header";const n=t.position||"right",i="left"===n?"flex-start":"center"===n?"center":"flex-end";this.container.style.cssText=`\n display: flex;\n align-items: center;\n justify-content: ${i};\n gap: ${this.theme.spacing.gap.md};\n padding: ${this.theme.spacing.padding.sm} ${this.theme.spacing.padding.md};\n background-color: ${this.theme.colors.card};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${this.theme.spacing.borderRadius.md};\n font-family: ${this.theme.typography.fontFamily};\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);\n `;const o=document.createElement("div");o.style.cssText=`\n display: flex;\n align-items: center;\n gap: ${this.theme.spacing.gap.sm};\n color: ${this.theme.colors.foreground};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n `;const r=document.createElement("span");r.textContent="⏱️",r.style.fontSize=this.theme.typography.fontSize.base,this.timeDisplay=document.createElement("span"),this.timeDisplay.id="gw-session-time",this.timeDisplay.textContent=this.getTimeCallback?.()||"--:--",this.timeDisplay.style.cssText="\n font-variant-numeric: tabular-nums;\n min-width: 50px;\n text-align: center;\n ",o.appendChild(r),o.appendChild(this.timeDisplay),this.container.appendChild(o);const a=document.createElement("div");if(a.style.cssText=`\n display: flex;\n gap: ${this.theme.spacing.gap.sm};\n `,this.onExtendCallback){const e=document.createElement("button");e.textContent="Extend",e.style.cssText=`\n padding: ${this.theme.spacing.padding.sm};\n background-color: ${this.theme.colors.success};\n color: ${this.theme.colors.successForeground};\n border: none;\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n font-family: ${this.theme.typography.fontFamily};\n cursor: pointer;\n transition: opacity 0.2s;\n `,e.addEventListener("mouseenter",()=>{e.style.opacity="0.9"}),e.addEventListener("mouseleave",()=>{e.style.opacity="1"}),e.addEventListener("click",()=>{this.onExtendCallback?.()}),a.appendChild(e)}if(this.onEndCallback){const e=document.createElement("button");e.textContent="End",e.style.cssText=`\n padding: ${this.theme.spacing.padding.sm};\n background-color: ${this.theme.colors.secondary};\n color: ${this.theme.colors.secondaryForeground};\n border: 1px solid ${this.theme.colors.border};\n border-radius: ${this.theme.spacing.borderRadius.sm};\n font-size: ${this.theme.typography.fontSize.sm};\n font-weight: ${this.theme.typography.fontWeight.medium};\n font-family: ${this.theme.typography.fontFamily};\n cursor: pointer;\n transition: opacity 0.2s;\n `,e.addEventListener("mouseenter",()=>{e.style.opacity="0.9"}),e.addEventListener("mouseleave",()=>{e.style.opacity="1"}),e.addEventListener("click",()=>{this.onEndCallback?.()}),a.appendChild(e)}a.children.length>0&&this.container.appendChild(a),s.appendChild(this.container),this.mounted=!0,this.startUpdating()}startUpdating(){this.updateInterval&&clearInterval(this.updateInterval),this.updateInterval=window.setInterval(()=>{if(this.timeDisplay&&this.getTimeCallback){const e=this.getTimeCallback();this.timeDisplay.textContent=e;const[t]=e.split(":").map(Number);!isNaN(t)&&t<5?(this.timeDisplay.style.color=this.theme.colors.destructive,this.timeDisplay.style.fontWeight=this.theme.typography.fontWeight.bold):(this.timeDisplay.style.color=this.theme.colors.foreground,this.timeDisplay.style.fontWeight=this.theme.typography.fontWeight.medium)}},1e3)}unmount(){this.updateInterval&&(clearInterval(this.updateInterval),this.updateInterval=null),this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.container=null,this.timeDisplay=null,this.mounted=!1}isMounted(){return this.mounted}updateTheme(e){const t="dark"===e||"auto"===e&&this.detectDarkMode();if(this.theme=Re(t),this.mounted&&this.container&&this.container.parentElement){const e=this.container.parentElement,t={getTime:this.getTimeCallback,onExtend:this.onExtendCallback,onEnd:this.onEndCallback};this.unmount(),this.mount(e,t)}}},e.TabSyncManager=Ie,e.TimerManager=ke,e.WarningModal=$e,e.darkTheme=Ae,e.default=De,e.extractTokenFromURL=Ce,e.generateCSSVariables=function(e){return`\n --gw-background: ${e.colors.background};\n --gw-foreground: ${e.colors.foreground};\n --gw-card: ${e.colors.card};\n --gw-card-foreground: ${e.colors.cardForeground};\n --gw-primary: ${e.colors.primary};\n --gw-primary-foreground: ${e.colors.primaryForeground};\n --gw-secondary: ${e.colors.secondary};\n --gw-secondary-foreground: ${e.colors.secondaryForeground};\n --gw-muted: ${e.colors.muted};\n --gw-muted-foreground: ${e.colors.mutedForeground};\n --gw-accent: ${e.colors.accent};\n --gw-accent-foreground: ${e.colors.accentForeground};\n --gw-destructive: ${e.colors.destructive};\n --gw-destructive-foreground: ${e.colors.destructiveForeground};\n --gw-success: ${e.colors.success};\n --gw-success-foreground: ${e.colors.successForeground};\n --gw-border: ${e.colors.border};\n --gw-input: ${e.colors.input};\n --gw-ring: ${e.colors.ring};\n `.trim()},e.getTheme=Re,e.isBrowser=function(){return"undefined"!=typeof window&&void 0!==window.document},e.lightTheme=xe,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
2
2
|
//# sourceMappingURL=marketplace-sdk.umd.js.map
|