sunuid-sdk 1.0.52 → 1.0.53

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.
@@ -7,5 +7,5 @@ var e,t,n="function"==typeof Symbol?Symbol:{},r=n.iterator||"@@iterator",o=n.toS
7
7
  * @version 1.0.0
8
8
  * @author SunuID Team
9
9
  * @license MIT
10
- */(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}!function(e,t){var o,i,c={apiUrl:(null===(t=e.SunuIDConfig)||void 0===t?void 0:t.apiUrl)||"https://api.sunuid.fayma.sn",clientId:null,secretId:null,type:2,partnerName:null,theme:"light",language:"fr",autoRefresh:!1,refreshInterval:3e4,autoInit:!1,onSuccess:null,onError:null,onStatusUpdate:null,onExpired:null,enableSecurityLogs:!0,validateInputs:!0,maxRetries:3,requestTimeout:1e4,secureInit:!1,secureInitUrl:null!==(o=e.SunuIDConfig)&&void 0!==o&&null!==(o=o.apiUrl)&&void 0!==o&&o.includes("api.sunuid.fayma.sn")?"https://api.sunuid.fayma.sn/secure-init.php":(null===(i=e.SunuIDConfig)||void 0===i||null===(i=i.apiUrl)||void 0===i?void 0:i.replace("/api",""))+"/secure-init.php"||"https://api.sunuid.fayma.sn/secure-init.php",token:null,forceRemoteServer:!0,useLocalFallback:!1,redirectAfterSuccess:null,verifySignature:!1,tokenMaxAge:300,onAuthenticationSuccess:null,onAuthenticationError:null,state:null},d=function(){return t=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=s(s({},c),t),this.qrCode=null,this.refreshTimer=null,this.isInitialized=!1,this.socket=null,this.initPromise=null,console.log("🔧 SDK SunuID créé - Appelez init() manuellement")},o=[{key:"init",value:(q=n(a().m(function e(){return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isInitialized){e.n=1;break}return console.log("⚠️ SDK déjà initialisé, ignoré"),e.a(2);case 1:if(!this.initPromise){e.n=2;break}return console.log("⚠️ Initialisation déjà en cours, attente..."),e.a(2,this.initPromise);case 2:if(!this._initInProgress){e.n=3;break}return console.log("⚠️ Initialisation en cours, ignoré"),e.a(2);case 3:return this._initInProgress=!0,this.initPromise=this._doInit(),e.p=4,e.n=5,this.initPromise;case 5:return e.p=5,this._initInProgress=!1,e.f(5);case 6:return e.a(2,this.initPromise)}},e,this,[[4,,5,6]])})),function(){return q.apply(this,arguments)})},{key:"_doInit",value:(D=n(a().m(function e(){var t;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(e.p=0,!this.handleCallback()){e.n=1;break}return console.log("✅ Callback traité, initialisation terminée"),e.a(2);case 1:if(!this.config.secureInit){e.n=3;break}return e.n=2,this.secureInit();case 2:e.n=4;break;case 3:this.config.validateInputs&&this.validateSecurityParams();case 4:return this.logSecurityEvent("SDK_INIT_START",{apiUrl:this.config.apiUrl,type:this.config.type,secureInit:this.config.secureInit}),e.n=5,this.fetchPartnerInfo();case 5:this.obfuscateCredentials(),this.isInitialized=!0,console.log("SunuID SDK initialisé avec succès"),console.log("📋 Configuration SDK:",{apiUrl:this.config.apiUrl,type:this.config.type,partnerName:this.config.partnerName,clientId:this.config.clientId?"***"+this.config.clientId.slice(-4):"null",secretId:this.config.secretId?"***"+this.config.secretId.slice(-4):"null",secureInit:this.config.secureInit,theme:this.config.theme}),this.logSecurityEvent("SDK_INIT_SUCCESS"),this.initWebSocket(),e.n=7;break;case 6:throw e.p=6,t=e.v,this.logSecurityEvent("SDK_INIT_ERROR",{error:t.message}),t;case 7:return e.a(2)}},e,this,[[0,6]])})),function(){return D.apply(this,arguments)})},{key:"secureInit",value:(T=n(a().m(function e(){var t,n,r,o,i;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,this.logSecurityEvent("SECURE_INIT_START"),t={type:this.config.type,partnerName:this.config.partnerName,theme:this.config.theme},e.n=1,fetch(this.config.secureInitUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});case 1:if((n=e.v).ok){e.n=2;break}throw new Error("Erreur HTTP: ".concat(n.status));case 2:return e.n=3,n.json();case 3:if(r=e.v,console.log("📋 Réponse initialisation sécurisée:",r),r.success){e.n=4;break}throw new Error(r.error||"Erreur lors de l'initialisation sécurisée");case 4:if(this.config.token=r.data.token,this.config.apiUrl=r.data.api_url,!(o=this.decodeSecureToken(r.data.token))){e.n=5;break}this.config.clientId=o.client_id,this.config.secretId=o.secret_id,e.n=6;break;case 5:throw new Error("Impossible de décoder le token sécurisé");case 6:this.config.expiresIn=r.data.expires_in,this.config.maxRequests=r.data.max_requests,this.config.requestCount=0,this.logSecurityEvent("SECURE_INIT_SUCCESS",{expiresIn:r.data.expires_in,maxRequests:r.data.max_requests}),console.log("✅ Initialisation sécurisée réussie"),e.n=8;break;case 7:throw e.p=7,i=e.v,this.logSecurityEvent("SECURE_INIT_ERROR",{error:i.message}),new Error("Échec de l'initialisation sécurisée: ".concat(i.message));case 8:return e.a(2)}},e,this,[[0,7]])})),function(){return T.apply(this,arguments)})},{key:"decodeSecureToken",value:function(e){try{var t=e.split(".");if(2!==t.length)return console.error("❌ Format de token invalide"),null;var n=u(t,2),r=n[0],o=(n[1],atob(r)),i=JSON.parse(o);return i.exp&&i.exp<Date.now()/1e3?(console.error("❌ Token expiré"),null):(console.log("✅ Token décodé avec succès"),i)}catch(e){return console.error("❌ Erreur décodage token:",e),null}}},{key:"initWebSocket",value:function(){var e=this;try{if("undefined"==typeof io)return console.warn("⚠️ Socket.IO non disponible, WebSocket sera initialisé plus tard"),void setTimeout(function(){return e.initWebSocket()},1e3);var t=this.getClientIP();this.socket?console.log("🌐 WebSocket déjà connecté"):(console.log("🌐 Initialisation Socket.IO..."),this.socket=io("wss://samasocket.fayma.sn:9443",{query:{token:this.config.clientId,type:"web",userId:this.config.clientId,username:t},transports:["websocket","polling"]}),this.socket.on("connect",function(){console.log("🌐 WebSocket connecté avec succès"),console.log("📊 Socket ID:",e.socket.id),e.socket.connected=!0}),this.socket.on("disconnect",function(t){console.log("❌ WebSocket déconnecté:",t),e.socket.connected=!1}),this.socket.on("connect_error",function(t){console.error("❌ Erreur connexion WebSocket:",t),e.socket.connected=!1}),this.socket.on("qr_status_update",function(t){console.log("📱 Mise à jour statut QR reçue:",t),e.handleQRStatusUpdate(t)}),this.socket.on("qr_scan_success",function(t){console.log("✅ Scan QR réussi reçu:",t),e.handleQRScanSuccess(t)}),this.socket.on("qr_expired",function(t){console.log("⏰ QR expiré reçu:",t),e.handleQRExpired(t)}),this.socket.on("qr_scan_initiated",function(t){console.log("🔍 QR Scan Initiated reçu:",t),e.showQRLoader()}),this.socket.on("message",function(t){console.log("📨 Message socket reçu:",t),t&&"qr_scan_initiated"===t.type&&(console.log("🔍 QR Scan Initiated détecté dans message:",t),e.showQRLoader())}),this.socket.onAny=this.socket.onAny||function(e,t){console.log("🌐 Socket Event [".concat(e,"]:"),t)},this.socket.onAny(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];console.log("🌐 Socket Event [".concat(e,"]:"),n)}))}catch(e){console.error("❌ Erreur initialisation WebSocket:",e)}}},{key:"getClientIP",value:function(){return"127.0.0.1"}},{key:"getTypeName",value:function(e){switch(e){case 1:return"KYC";case 2:return"AUTH";case 3:return"SIGNATURE";default:return"TYPE-".concat(e)}}},{key:"validateSecurityParams",value:function(){var e=[];if(this.config.clientId&&"string"==typeof this.config.clientId?this.config.clientId.length<10&&e.push("clientId trop court"):e.push("clientId invalide ou manquant"),this.config.secretId&&"string"==typeof this.config.secretId?this.config.secretId.length<32&&e.push("secretId trop court (minimum 32 caractères)"):e.push("secretId invalide ou manquant"),this.config.apiUrl&&this.isValidUrl(this.config.apiUrl)||e.push("apiUrl invalide"),[1,2,3].includes(this.config.type)||e.push("type invalide (doit être 1, 2 ou 3)"),e.length>0)throw this.logSecurityEvent("VALIDATION_ERROR",{errors:e}),new Error("Paramètres de sécurité invalides: ".concat(e.join(", ")));this.logSecurityEvent("VALIDATION_SUCCESS")}},{key:"isValidUrl",value:function(e){try{var t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol}catch(e){return!1}}},{key:"logSecurityEvent",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.config.enableSecurityLogs){var r={timestamp:(new Date).toISOString(),event:t,data:n,userAgent:navigator.userAgent,url:e.location.href};console.warn("🔒 [SECURITY]",r),e.SunuIDSecurityLogs||(e.SunuIDSecurityLogs=[]),e.SunuIDSecurityLogs.push(r)}}},{key:"obfuscateCredentials",value:function(){this.config.originalClientId=this.config.clientId,this.config.originalSecretId=this.config.secretId,this.config.clientId&&(this.config.clientIdDisplay=this.config.clientId.replace(/(.{3}).*(.{3})/,"$1***$2")),this.config.secretId&&(this.config.secretIdDisplay=this.config.secretId.replace(/(.{4}).*(.{4})/,"$1***$2"))}},{key:"sanitizeInput",value:function(e){return"string"!=typeof e?e:e.replace(/[<>]/g,"").replace(/javascript:/gi,"").trim()}},{key:"handleQRStatusUpdate",value:function(e){console.log("📱 QR Status Update:",e),this.config.onStatusUpdate&&this.config.onStatusUpdate(e)}},{key:"handleQRScanSuccess",value:function(e){console.log("✅ QR Scan Success reçu:",e);try{var t=this.extractAuthDataFromWebSocket(e);this.processAuthentication(t),this.showSuccessMessage(t),this.config.onSuccess&&this.config.onSuccess(t),console.log("✅ Authentification WebSocket traitée avec succès")}catch(t){console.error("❌ Erreur lors du traitement WebSocket:",t),this.config.onAuthenticationError&&this.config.onAuthenticationError(t,e)}}},{key:"handleQRExpired",value:function(e){console.log("⏰ QR Expired:",e),this.config.onExpired&&this.config.onExpired(e)}},{key:"emitWebSocketEvent",value:function(e,t){this.socket&&this.socket.connected?(this.socket.emit(e,t),console.log("📤 Événement WebSocket émis: ".concat(e),t)):console.warn("⚠️ WebSocket non connecté, impossible d'émettre l'événement:",e)}},{key:"getWebSocketStatus",value:function(){return this.socket?this.socket.connected?"connected":"disconnected":"not_initialized"}},{key:"forceWebSocketInit",value:function(){"undefined"==typeof io||this.socket||(console.log("🔄 Forçage de l'initialisation WebSocket..."),this.initWebSocket())}},{key:"generateQR",value:(Q=n(a().m(function t(){var n,r,o,i,c,l,u,d,f,p,h,g=arguments;return a().w(function(t){for(;;)switch(t.p=t.n){case 0:if(n=g.length>0&&void 0!==g[0]?g[0]:"sunuid-qr-container",r=g.length>1&&void 0!==g[1]?g[1]:{},!this.initPromise){t.n=2;break}return t.n=1,this.initPromise;case 1:this.initPromise=null;case 2:if(this.isInitialized){t.n=3;break}throw new Error("SunuID: SDK non initialisé");case 3:return console.log("🎯 generateQR appelé avec containerId:",n),console.log("🔍 Attente connexions API et WebSocket..."),t.p=4,t.n=5,this.waitForConnections(5e3);case 5:o=t.v,console.log("✅ Connexions prêtes:",o),t.n=7;break;case 6:throw t.p=6,p=t.v,console.error("❌ Erreur connexions:",p.message),new Error("Connexions non disponibles - Impossible de générer le QR code");case 7:return t.p=7,i=this.socket?this.socket.id:"timeout-socket-id",c=i,console.log("📄 Contenu QR préparé:",c),console.log("🔌 Socket ID:",i),l=this.config.partnerName||"Partner_unknown",t.n=8,this.makeRequest("/qr-generate",s({type:this.config.type,data:c,label:"".concat(this.getTypeName(this.config.type)," ").concat(l)},r));case 8:if(!(u=t.v).success){t.n=11;break}if(console.log("📋 Réponse QR API complète:",u),console.log("📋 Structure response.data:",u.data),(d=u.data.qrCodeUrl)&&d.startsWith("/")&&(d="".concat(this.config.apiUrl).concat(d)),d){t.n=10;break}if(console.warn("⚠️ qrCodeUrl non trouvé dans la réponse, recherche d'alternatives..."),!(d=u.data.qr_url||u.data.qrUrl||u.data.url||u.data.image_url||u.data.imageUrl)){t.n=9;break}console.log("✅ URL QR trouvée dans un champ alternatif:",d),t.n=10;break;case 9:throw console.error("❌ Aucune URL QR trouvée dans la réponse"),new Error("URL du QR code non trouvée dans la réponse API");case 10:return this.currentQRUrl=d,console.log("✅ QR code généré par API principale:",d),console.log("📄 Contenu QR final:",c),console.log("🏷️ Label QR:",u.data.label||"N/A"),console.log("🆔 Session ID:",u.data.sessionId||"N/A"),this.displayQRCode(n,d,this.config.type,r),this.startAutoRefresh(n,this.config.type,r),this.emitWebSocketEvent("qr_generated",{type:this.config.type,qrCodeUrl:d,socketId:i,qrContent:c,label:u.data.label,sessionId:u.data.sessionId,timestamp:Date.now()}),t.a(2,s(s({},u.data),{},{qrCodeUrl:d,qrContent:c,label:u.data.label,sessionId:u.data.sessionId}));case 11:throw new Error(u.message||"Erreur lors de la génération du QR code");case 12:t.n=14;break;case 13:throw t.p=13,h=t.v,console.error("Erreur API détectée:",h.message),console.error("Stack trace complet:",h.stack),console.error("Configuration SDK:",{apiUrl:this.config.apiUrl,type:this.config.type,secureInit:this.config.secureInit,clientId:this.config.clientId?"***"+this.config.clientId.slice(-4):"null",secretId:this.config.secretId?"***"+this.config.secretId.slice(-4):"null"}),this.config.useLocalFallback?(console.log("🔍 Vérification fallback local..."),console.log("🔍 Hostname:",e.location.hostname),console.log("🔍 Protocol:",e.location.protocol),console.log("🔍 URL complète:",e.location.href),f="localhost"===e.location.hostname||"127.0.0.1"===e.location.hostname||"file:"===e.location.protocol,console.log("🔍 Est local:",f),f?(console.log("🔄 Tentative fallback vers service QR local..."),console.log("❌ Fallback local non implémenté - utilisation serveur distant uniquement")):console.log("❌ Pas en local, pas de fallback")):console.log("🔒 Fallback local désactivé, utilisation serveur distant uniquement"),console.log('Affichage du message "Service non disponible" pour type '+this.config.type),this.displayServiceUnavailable(n,this.config.type),new Error("Service non disponible");case 14:return t.a(2)}},t,this,[[7,13],[4,6]])})),function(){return Q.apply(this,arguments)})},{key:"generateCustomQR",value:(C=n(a().m(function e(t,n){var r,o,i,c,l=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=l.length>2&&void 0!==l[2]?l[2]:{},!this.initPromise){e.n=2;break}return e.n=1,this.initPromise;case 1:this.initPromise=null;case 2:if(this.isInitialized){e.n=3;break}throw new Error("SunuID: SDK non initialisé");case 3:return e.p=3,e.n=4,this.makeRequest("/qr-generate",s({type:n},r));case 4:if(!(o=e.v).success){e.n=5;break}return i="".concat("https://sunuid.fayma.sn").concat(o.data.qrcode),this.displayQRCode(t,i,n,r),console.log("✅ QR code personnalisé généré par API principale:",i),console.log("📄 Code de session:",o.data.code),console.log("🆔 Service ID:",o.data.service_id),this.startAutoRefresh(t,n,r),e.a(2,s(s({},o.data),{},{qrCodeUrl:i,sessionId:o.data.service_id}));case 5:throw new Error(o.message||"Erreur lors de la génération du QR code");case 6:e.n=8;break;case 7:throw e.p=7,c=e.v,console.error("Erreur API détectée:",c.message),console.error("Stack trace complet:",c.stack),console.error("Configuration SDK (Custom):",{apiUrl:this.config.apiUrl,type:n,secureInit:this.config.secureInit,clientId:this.config.clientId?"***"+this.config.clientId.slice(-4):"null",secretId:this.config.secretId?"***"+this.config.secretId.slice(-4):"null"}),console.log('Affichage du message "Service non disponible" pour type '+n),this.displayServiceUnavailable(t,n),new Error("Service non disponible");case 8:return e.a(2)}},e,this,[[3,7]])})),function(e,t){return C.apply(this,arguments)})},{key:"generateAuthQR",value:(x=n(a().m(function e(t){var n,r=arguments;return a().w(function(e){for(;;)if(0===e.n)return n=r.length>1&&void 0!==r[1]?r[1]:{},e.a(2,this.generateQR(t,n))},e,this)})),function(e){return x.apply(this,arguments)})},{key:"generateKYCQR",value:(E=n(a().m(function e(t){var n,r,o=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return n=o.length>1&&void 0!==o[1]?o[1]:{},r=this.config.type,this.config.type=1,e.p=1,e.n=2,this.generateQR(t,n);case 2:return e.a(2,e.v);case 3:return e.p=3,this.config.type=r,e.f(3);case 4:return e.a(2)}},e,this,[[1,,3,4]])})),function(e){return E.apply(this,arguments)})},{key:"generateSignatureQR",value:(R=n(a().m(function e(t){var n,r,o=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return n=o.length>1&&void 0!==o[1]?o[1]:{},r=this.config.type,this.config.type=3,e.p=1,e.n=2,this.generateQR(t,n);case 2:return e.a(2,e.v);case 3:return e.p=3,this.config.type=r,e.f(3);case 4:return e.a(2)}},e,this,[[1,,3,4]])})),function(e){return R.apply(this,arguments)})},{key:"checkQRStatus",value:(w=n(a().m(function e(t){var n,r;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-status",{serviceId:t});case 2:if(!(n=e.v).success){e.n=3;break}return e.a(2,n.data);case 3:throw new Error(n.message||"Erreur lors de la vérification du statut");case 4:e.n=6;break;case 5:throw e.p=5,r=e.v,this.handleError(r),r;case 6:return e.a(2)}},e,this,[[1,5]])})),function(e){return w.apply(this,arguments)})},{key:"generateQRWithContent",value:(_=n(a().m(function t(n,r,o){var i,s,c,l=arguments;return a().w(function(t){for(;;)switch(t.p=t.n){case 0:if(i=l.length>3&&void 0!==l[3]?l[3]:{},console.log("🎨 Génération QR avec contenu:",n),t.p=1,"localhost"!==e.location.hostname&&"127.0.0.1"!==e.location.hostname&&"file:"!==e.location.protocol){t.n=3;break}return console.log("🏠 Utilisation service QR local..."),t.n=2,this.generateQRLocal(n,r,o,i);case 2:if(!(s=t.v)){t.n=3;break}return t.a(2,s);case 3:return console.log("🌐 Utilisation service QR distant..."),t.n=4,this.generateQRRemote(n,r,o,i);case 4:return t.a(2,t.v);case 5:return t.p=5,c=t.v,console.error("❌ Erreur génération QR:",c),this.displayQRContent(r,n,o,i),t.a(2,null)}},t,this,[[1,5]])})),function(e,t,n){return _.apply(this,arguments)})},{key:"generateQRLocal",value:(I=n(a().m(function e(t,n,r){var o,i,s,c,l,u=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return o=u.length>3&&void 0!==u[3]?u[3]:{},e.p=1,e.n=2,fetch("http://localhost:8000/api/generate/text",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"text=".concat(encodeURIComponent(t),"&size=300")});case 2:if(!(i=e.v).ok){e.n=4;break}return e.n=3,i.json();case 3:return s=e.v,c="data:image/png;base64,".concat(s.qrcode),this.displayQRCode(n,c,r,o),e.a(2,c);case 4:e.n=6;break;case 5:e.p=5,l=e.v,console.log("❌ Service QR local non disponible:",l.message);case 6:return e.a(2,null)}},e,this,[[1,5]])})),function(e,t,n){return I.apply(this,arguments)})},{key:"generateQRRemote",value:(S=n(a().m(function e(t,n,r){var o,i,s,c,l,u=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return o=u.length>3&&void 0!==u[3]?u[3]:{},e.p=1,e.n=2,fetch("https://api.sunuid.fayma.sn/qr-generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t,size:300,type:r})});case 2:if(!(i=e.v).ok){e.n=4;break}return e.n=3,i.json();case 3:return s=e.v,c="data:image/png;base64,".concat(s.qrcode),this.displayQRCode(n,c,r,o),e.a(2,c);case 4:e.n=6;break;case 5:e.p=5,l=e.v,console.error("❌ Erreur service QR distant:",l);case 6:return this.displayQRContent(n,t,r,o),e.a(2,null)}},e,this,[[1,5]])})),function(e,t,n){return S.apply(this,arguments)})},{key:"displayQRContent",value:function(e,t,n){var r=document.getElementById(e);if(!r)throw new Error("Conteneur avec l'ID \"".concat(e,'" non trouvé'));var o=this.getTypeName(n);r.innerHTML='\n <div class="sunuid-qr-code">\n <div class="sunuid-qr-header">\n <h3>'.concat(o,'</h3>\n </div>\n <div class="sunuid-qr-content" style="text-align: center; padding: 20px; background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; margin: 10px 0;">\n <p><strong>Contenu QR Code:</strong></p>\n <p style="font-family: monospace; font-size: 14px; word-break: break-all;">').concat(t,'</p>\n </div>\n <div class="sunuid-qr-instructions">\n <p>Contenu QR généré avec le format: {type}-{code}-{socketid}</p>\n </div>\n </div>\n '),console.log("✅ Contenu QR affiché:",t)}},{key:"displayQRCode",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=document.getElementById(e);if(!o)throw new Error("Conteneur avec l'ID \"".concat(e,'" non trouvé'));o.innerHTML="";var i=document.createElement("div");i.className="sunuid-qr-code";var s=this.getTypeName(n);i.innerHTML='\n <div class="sunuid-qr-header">\n <h3>'.concat(1===n?"Vérification KYC":2===n?"Authentification":3===n?"Signature":"Service Type "+n,'</h3>\n </div>\n <div class="sunuid-qr-image">\n <img src="').concat(t,'" alt="QR Code ').concat(s,'" style="max-width: 300px; border: 1px solid #ddd; border-radius: 5px;" />\n </div>\n \n '),o.appendChild(i),this.applyTheme(r.theme||this.config.theme),console.log("✅ QR code affiché:",t)}},{key:"generateCustomQRCode",value:(k=n(a().m(function e(t,n){var r,o;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(console.log("🎨 Début génération QR personnalisé..."),console.log("📄 Contenu:",t),console.log("🏷️ Label:",n),(r=document.getElementById("sunuid-qr-container"))||(r=document.getElementById("qr-container")),r){e.n=1;break}return console.error("❌ QR container not found"),e.a(2);case 1:return console.log("✅ QR container trouvé"),r.innerHTML='<div style="text-align: center; padding: 20px;"><p>Génération QR code...</p></div>',e.p=2,console.log("🎨 Tentative génération via API principale..."),e.n=3,this.generateQRPHP(t,n,r);case 3:console.log("✅ QR code généré avec succès"),e.n=5;break;case 4:e.p=4,o=e.v,console.error("❌ Erreur génération API:",o),console.log("⚠️ Affichage image par défaut"),this.displayDefaultQR(r,t,n);case 5:return e.a(2)}},e,this,[[2,4]])})),function(e,t){return k.apply(this,arguments)})},{key:"generateQRClientSide",value:(b=n(a().m(function e(t,n,r){var o,i,s=this;return a().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.ensureQRCodeLibrary();case 1:if("undefined"!=typeof QRCode){e.n=2;break}throw new Error("QRCode library non disponible");case 2:return(o=document.createElement("canvas")).width=300,o.height=320,(i=o.getContext("2d")).fillStyle="#FFFFFF",i.fillRect(0,0,300,320),e.a(2,new Promise(function(e,a){QRCode.toCanvas(o,t,{width:280,margin:10,color:{dark:"#000000",light:"#FFFFFF"}},function(t){if(t)a(t);else{i.fillStyle="#333333",i.font="bold 14px Arial",i.textAlign="center",i.fillText(n,150,305);var c=o.toDataURL("image/png");s.currentQRUrl=c,r.innerHTML='\n <div style="text-align: center; padding: 20px;">\n <img src="'.concat(c,'" alt="QR Code" style="max-width: 300px; border: 2px solid #ddd; border-radius: 10px;">\n </div>\n '),s.showQRInstructions(r),e()}})}))}},e,this)})),function(e,t,n){return b.apply(this,arguments)})},{key:"generateQRPHP",value:(m=n(a().m(function e(t,n,r){var o,i,s,c,l,u;return a().w(function(e){for(;;)switch(e.n){case 0:return o=this.config.forceRemoteServer||this.config.apiUrl.includes("api.sunuid.fayma.sn")?"https://api.sunuid.fayma.sn/qr-generate":this.config.apiUrl.includes("localhost")||this.config.apiUrl.includes("127.0.0.1")?"http://localhost:8000/api/generate/text":this.config.apiUrl+"/qr-generate",console.log("🔗 URL QR Generator:",o),o.includes("localhost:8000")?(s="application/x-www-form-urlencoded",i=new URLSearchParams({text:t,size:300,margin:10,foreground_color:"000000",background_color:"FFFFFF"})):(s="application/json",i=JSON.stringify({type:this.config.type,client_id:this.config.clientId,secret_id:this.config.secretId,content:t,label:n})),e.n=1,fetch(o,{method:"POST",headers:{"Content-Type":s,Accept:"application/json"},body:i});case 1:if((c=e.v).ok){e.n=2;break}throw new Error("Erreur HTTP: ".concat(c.status));case 2:return e.n=3,c.json();case 3:if((l=e.v).success){e.n=4;break}throw new Error("Erreur QR: ".concat(l.error));case 4:u=o.includes("localhost:8000")?l.data_uri:"".concat("https://sunuid.fayma.sn").concat(l.data.qrcode),this.currentQRUrl=u,r.innerHTML='\n <div style="text-align: center; padding: 20px;">\n <img src="'.concat(u,'" alt="QR Code" style="max-width: 300px; border: 2px solid #ddd; border-radius: 10px;">\n </div>\n '),this.showQRInstructions(r);case 5:return e.a(2)}},e,this)})),function(e,t,n){return m.apply(this,arguments)})},{key:"displayDefaultQR",value:function(e,t,n){e.innerHTML='\n <div style="text-align: center; padding: 20px; color: #666;">\n <div style="width: 300px; height: 300px; background: #f0f0f0; border: 2px solid #ddd; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto;">\n <div>\n <p style="font-size: 24px; margin: 0;">📱</p>\n <p style="font-size: 14px; margin: 10px 0 0 0;">QR Code</p>\n </div>\n </div>\n <p style="margin-top: 10px; font-size: 12px;">'.concat(n,'</p>\n <p style="font-size: 10px; color: #999; margin-top: 5px;">Contenu: ').concat(t,"</p>\n </div>\n ")}},{key:"ensureQRCodeLibrary",value:(y=n(a().m(function e(){return a().w(function(e){for(;;)switch(e.n){case 0:if("undefined"==typeof QRCode){e.n=1;break}return console.log("✅ QRCode library déjà disponible"),e.a(2,!0);case 1:return console.log("📦 Chargement QRCode library..."),e.a(2,new Promise(function(e,t){var n=document.createElement("script");n.src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/lib/browser.min.js",n.onload=function(){setTimeout(function(){"undefined"!=typeof QRCode?(console.log("✅ QRCode library chargée"),e(!0)):(console.error("❌ QRCode non disponible après chargement"),t(new Error("QRCode library non disponible après chargement")))},200)},n.onerror=function(){console.error("❌ Erreur chargement QRCode library"),t(new Error("Erreur chargement QRCode library"))},document.head.appendChild(n)}))}},e)})),function(){return y.apply(this,arguments)})},{key:"showQRInstructions",value:function(e){var t=e.parentElement.querySelector(".sunuid-qr-instructions"),n=e.parentElement.querySelector(".sunuid-qr-status");t&&(t.style.display="block",t.classList.add("sunuid-qr-ready")),n&&(n.style.display="block",n.classList.add("sunuid-qr-ready"))}},{key:"addLogoToCenter",value:function(e,t,n,r,o){try{var i=new Image;i.onload=function(){var o=40,s=t+(r-o)/2,a=n+(r-o)/2;e.fillStyle="white",e.fillRect(s-2,a-2,44,44),e.drawImage(i,s,a,o,o)},i.src="src/logoqr.png"}catch(e){console.warn("Logo non disponible:",e)}}},{key:"displayFallbackImage",value:function(){console.log("⚠️ Affichage de l'image de fallback");var e=document.getElementById("sunuid-qr-container");e&&(e.innerHTML='\n <div style="text-align: center; padding: 20px; color: #666;">\n <p>⚠️ Génération QR personnalisé non disponible</p>\n <p>Utilisation de l\'image par défaut</p>\n <p><strong>Debug:</strong> QRCode disponible: '.concat("undefined"!=typeof QRCode,"</p>\n <p><strong>Debug:</strong> Container trouvé: ").concat(null!==e,"</p>\n </div>\n "))}},{key:"displayServiceUnavailable",value:function(e,t){console.log("displayServiceUnavailable appelée pour ".concat(e,", type: ").concat(t));var n=document.getElementById(e);n?n.innerHTML='\n <div class="sunuid-service-unavailable" style="\n text-align: center;\n padding: 40px 20px;\n background: #f8f9fa;\n border: 2px dashed #dee2e6;\n border-radius: 10px;\n color: #6c757d;\n font-family: Arial, sans-serif;\n ">\n <div style="font-size: 48px; margin-bottom: 20px;">⚠️</div>\n <h3 style="margin: 0 0 10px 0; color: #495057;">Service Non Disponible</h3>\n <p style="margin: 0; font-size: 14px;">\n Le service d\'authentification est temporairement indisponible.<br>\n Veuillez réessayer plus tard.\n </p>\n <div style="margin-top: 20px; font-size: 12px; color: #adb5bd;">\n Type: '.concat(String(t).toUpperCase(),"\n </div>\n </div>\n "):console.error("Container ".concat(e," non trouvé"))}},{key:"refreshQR",value:(v=n(a().m(function e(t){var n,r,o,i,s=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(n=s.length>1&&void 0!==s[1]?s[1]:{},e.p=1,!this.currentQRUrl){e.n=3;break}return console.log("🔄 Vérification du statut du QR code existant..."),e.n=2,this.generateQR(t,n);case 2:return r=e.v,e.a(2,r);case 3:return console.log("🔄 Pas de QR code existant, génération d'un nouveau..."),e.n=4,this.generateQR(t,n);case 4:return o=e.v,e.a(2,o);case 5:e.n=7;break;case 6:throw e.p=6,i=e.v,console.error("Erreur lors du rafraîchissement:",i.message),this.displayServiceUnavailable(t,this.config.type),i;case 7:return e.a(2)}},e,this,[[1,6]])})),function(e){return v.apply(this,arguments)})},{key:"startAutoRefresh",value:function(e,t,r){var o=this;this.config.autoRefresh&&(this.refreshTimer&&(clearInterval(this.refreshTimer),console.log("🔄 Timer de rafraîchissement précédent arrêté")),this.refreshTimer=setInterval(n(a().m(function n(){var i;return a().w(function(n){for(;;)switch(n.p=n.n){case 0:return n.p=0,console.log("🔄 Rafraîchissement automatique du QR code..."),n.n=1,o.refreshQR(e,t,r);case 1:n.n=3;break;case 2:n.p=2,i=n.v,console.warn("Erreur lors du rafraîchissement automatique:",i);case 3:return n.a(2)}},n,null,[[0,2]])})),this.config.refreshInterval),console.log("🔄 Timer de rafraîchissement démarré (".concat(this.config.refreshInterval,"ms)")))}},{key:"makeRequest",value:(g=n(a().m(function t(n,r){var o,i,s,c,u,d,f,p,h,g=this;return a().w(function(t){for(;;)switch(t.n){case 0:if(this.isInitialized){t.n=1;break}throw this.logSecurityEvent("REQUEST_BEFORE_INIT",{endpoint:n}),new Error("SDK non initialisé");case 1:if(!this.config.secureInit){t.n=2;break}if(this.config.requestCount++,!(this.config.requestCount>this.config.maxRequests)){t.n=2;break}throw this.logSecurityEvent("API_REQUEST_LIMIT_EXCEEDED",{requestCount:this.config.requestCount,maxRequests:this.config.maxRequests}),new Error("Limite de requêtes dépassée");case 2:s=this.sanitizeRequestData(r),console.log("🔍 Debug makeRequest - endpoint:",n),console.log("🔍 Debug makeRequest - apiUrl:",this.config.apiUrl),console.log("🔍 Debug makeRequest - url:","".concat(this.config.apiUrl).concat(n)),console.log("🔍 Debug makeRequest - data:",JSON.stringify(s,null,2)),console.log("🔍 Debug makeRequest - secureInit:",this.config.secureInit),console.log("🔍 Debug makeRequest - isInitialized:",this.isInitialized),c=(null===(o=e.SunuIDConfig)||void 0===o||null===(o=o.endpoints)||void 0===o?void 0:o[n.replace("/","")])||n,u="".concat(this.config.apiUrl).concat(c),console.log("🔍 URL finale construite:",u),console.log("🔍 EndpointPath:",c),console.log("🔍 SunuIDConfig endpoints:",JSON.stringify(null===(i=e.SunuIDConfig)||void 0===i?void 0:i.endpoints)),this.logSecurityEvent("API_REQUEST_START",{endpoint:c,url:u,dataKeys:Object.keys(s),secureInit:this.config.secureInit}),d=0,f=this.config.maxRetries,p=a().m(function e(){var t,n,r,o,i,l,p,h;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,t=new AbortController,n=setTimeout(function(){return t.abort()},g.config.requestTimeout),r={"Content-Type":"application/json"},e.n=1,fetch(u,{method:"POST",headers:r,body:JSON.stringify(s),signal:t.signal});case 1:if(o=e.v,clearTimeout(n),o.ok){e.n=3;break}return e.n=2,o.text();case 2:i=e.v;try{l=JSON.parse(i)}catch(e){l={message:i}}throw g.logSecurityEvent("API_REQUEST_ERROR",{status:o.status,statusText:o.statusText,error:l.message}),new Error(l.message||"Erreur HTTP: ".concat(o.status));case 3:return e.n=4,o.json();case 4:return p=e.v,g.logSecurityEvent("API_REQUEST_SUCCESS",{endpoint:c,responseKeys:Object.keys(p)}),e.a(2,{v:p});case 5:if(e.p=5,h=e.v,d++,"AbortError"!==h.name){e.n=7;break}if(g.logSecurityEvent("API_REQUEST_TIMEOUT",{retryCount:d}),!(d>f)){e.n=6;break}throw new Error("Timeout de la requête API");case 6:return e.a(2,0);case 7:if(!(d>f)){e.n=8;break}throw g.logSecurityEvent("API_REQUEST_MAX_RETRIES",{retryCount:d,error:h.message}),h;case 8:return e.n=9,new Promise(function(e){return setTimeout(e,1e3*d)});case 9:return e.a(2)}},e,null,[[0,5]])});case 3:if(!(d<=f)){t.n=7;break}return t.d(l(p()),4);case 4:if(0!==(h=t.v)){t.n=5;break}return t.a(3,3);case 5:if(!h){t.n=6;break}return t.a(2,h.v);case 6:t.n=3;break;case 7:return t.a(2)}},t,this)})),function(e,t){return g.apply(this,arguments)})},{key:"sanitizeRequestData",value:function(e){for(var t={},n=0,r=Object.entries(e);n<r.length;n++){var o=u(r[n],2),i=o[0],s=o[1];"string"==typeof s?t[i]=this.sanitizeInput(s):"object"===f(s)&&null!==s?t[i]=this.sanitizeRequestData(s):t[i]=s}return t.client_id=this.config.originalClientId||this.config.clientId,t.secret_id=this.config.originalSecretId||this.config.secretId,console.log("🔍 Credentials dans sanitizeRequestData - clientId:",this.config.clientId),console.log("🔍 Credentials dans sanitizeRequestData - secretId:",this.config.secretId?"***"+this.config.secretId.slice(-4):"null"),console.log("🔍 Credentials dans sanitizeRequestData - sanitizedClientId:",t.client_id),console.log("🔍 Credentials dans sanitizeRequestData - sanitizedSecretId:",t.secret_id?"***"+t.secret_id.slice(-4):"null"),console.log("🔍 Credentials dans sanitizeRequestData - data complet:",JSON.stringify(t,null,2)),t}},{key:"generateRequestId",value:function(){return"req_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}},{key:"generateSessionCode",value:function(){var e=Date.now(),t=Math.random().toString(36).substr(2,9),n="".concat(e,"_").concat(t);return btoa(n)}},{key:"fetchPartnerInfo",value:(h=n(a().m(function e(){var t,n,r,o;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.makeRequest("/debug",{type:this.config.type,client_id:this.config.clientId,secret_id:this.config.secretId});case 1:t=e.v,console.log("📋 Réponse debug API:",t),t.success&&t.data?(n=t.data,r=null,n.partner_id?r=n.partner_id:n.authentication&&n.authentication.auth_test&&n.authentication.auth_test.partner_id?r=n.authentication.auth_test.partner_id:n.auth_test&&n.auth_test.partner_id&&(r=n.auth_test.partner_id),r?(this.config.partnerId=r,n.service_id?this.config.serviceId=n.service_id:this.config.serviceId=r,this.config.partnerName=21===r?"Fayma":"Partner_".concat(r),console.log("✅ Informations partenaire récupérées:",{partnerName:this.config.partnerName,partnerId:this.config.partnerId,serviceId:this.config.serviceId})):(console.warn("⚠️ Partner ID non trouvé dans la réponse, utilisation du partner_id par défaut"),this.config.partnerName="Partner_".concat(this.config.partnerId||"unknown"))):(console.warn("⚠️ Structure de réponse invalide, utilisation du partner_id par défaut"),this.config.partnerName="Partner_".concat(this.config.partnerId||"unknown")),e.n=3;break;case 2:e.p=2,o=e.v,console.warn("⚠️ Erreur lors de la récupération des informations du partenaire:",o.message),this.config.partnerName="Partner_unknown";case 3:return e.a(2)}},e,this,[[0,2]])})),function(){return h.apply(this,arguments)})},{key:"applyTheme",value:function(e){var t=document.querySelector(".sunuid-qr-code");t&&(t.className="sunuid-qr-code sunuid-theme-".concat(e))}},{key:"handleError",value:function(e){console.error("SunuID SDK Error:",e),this.config.onError&&this.config.onError(e)}},{key:"checkConnections",value:(p=n(a().m(function e(){var t,n,r,o;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return t={api:!1,websocket:!1,ready:!1},e.p=1,e.n=2,fetch(this.config.apiUrl+"/debug",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:this.config.type,client_id:this.config.clientId,secret_id:this.config.secretId})});case 2:if(!(n=e.v).ok){e.n=4;break}return e.n=3,n.json();case 3:r=e.v,t.api=!0===r.success,console.log("🔍 API Status:",t.api?"accessible":"inaccessible"),e.n=5;break;case 4:t.api=!1,console.log("🔍 API Status: HTTP",n.status);case 5:e.n=7;break;case 6:e.p=6,o=e.v,console.log("🔍 Test API échoué:",o.message),t.api=!1;case 7:return t.websocket=this.socket&&this.socket.connected,t.ready=t.api,e.a(2,t)}},e,this,[[1,6]])})),function(){return p.apply(this,arguments)})},{key:"waitForConnections",value:(d=n(a().m(function e(){var t,n,r,o=arguments;return a().w(function(e){for(;;)switch(e.n){case 0:t=o.length>0&&void 0!==o[0]?o[0]:5e3,n=Date.now();case 1:if(!(Date.now()-n<t)){e.n=5;break}return e.n=2,this.checkConnections();case 2:if(!(r=e.v).ready){e.n=3;break}return console.log("✅ Connexions prêtes"),e.a(2,r);case 3:return console.log("⏳ Attente connexions...",r),e.n=4,new Promise(function(e){return setTimeout(e,1e3)});case 4:e.n=1;break;case 5:throw new Error("Timeout connexions - Impossible de générer le QR code");case 6:return e.a(2)}},e,this)})),function(){return d.apply(this,arguments)})},{key:"getQRCode",value:function(){return this.currentQRUrl?this.currentQRUrl:null}},{key:"destroy",value:function(){this.stopAutoRefresh(),this.socket&&(this.socket.disconnect(),this.socket=null,console.log("🌐 WebSocket déconnecté")),this.isInitialized=!1,this.logSecurityEvent("SDK_DESTROY"),console.log("SunuID SDK détruit")}},{key:"stopAutoRefresh",value:function(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null,console.log("🔄 Timer de rafraîchissement arrêté"))}},{key:"getSecurityLogs",value:function(){return e.SunuIDSecurityLogs||[]}},{key:"clearSecurityLogs",value:function(){e.SunuIDSecurityLogs=[],this.logSecurityEvent("SECURITY_LOGS_CLEARED")}},{key:"showQRLoader",value:function(){console.log("🔄 Affichage du loader - Scan QR initié");for(var e=null,t=0,n=["qr-area","qr-container","sunuid-qr-container"];t<n.length;t++){var r=n[t];if(e=document.getElementById(r))break}e?(e.innerHTML='\n <div style="\n text-align: center;\n padding: 40px 20px;\n background: #f8f9fa;\n border: 2px solid #007bff;\n border-radius: 10px;\n color: #007bff;\n font-family: Arial, sans-serif;\n ">\n <div style="\n width: 60px;\n height: 60px;\n border: 4px solid #e3f2fd;\n border-top: 4px solid #007bff;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin: 0 auto 20px auto;\n "></div>\n <h3 style="margin: 0 0 10px 0; color: #007bff;">🔍 Scan en cours...</h3>\n <p style="margin: 0; font-size: 14px;">\n Veuillez patienter pendant la vérification de votre identité.\n </p>\n <div style="margin-top: 15px; font-size: 12px; color: #6c757d;">\n ⏱️ Traitement en cours...\n </div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n ',console.log("✅ Loader affiché avec succès")):console.warn("⚠️ Conteneur QR non trouvé pour afficher le loader")}},{key:"extractAuthDataFromWebSocket",value:function(e){if(console.log("🔍 Extraction des données d'authentification du WebSocket:",e),console.log("🔍 Structure complète de websocketData:",JSON.stringify(e,null,2)),e.token&&e.session_id)return console.log("✅ Données déjà au bon format (callback)"),e;if(e.responseData){console.log("✅ Format WebSocket détecté, extraction de responseData"),console.log("🔍 Contenu complet de responseData:",e.responseData),console.log("🔍 Clés disponibles dans responseData:",Object.keys(e.responseData));var t=e.responseData,n=t.data||t;console.log("🔍 Données d'authentification dans data:",n),console.log("🔍 Clés disponibles dans data:",Object.keys(n)),n.callback_data&&console.log("🔍 Contenu de callback_data:",n.callback_data),n.session_data&&console.log("🔍 Contenu de session_data:",n.session_data),n.user_data_sent&&console.log("🔍 Contenu de user_data_sent:",n.user_data_sent);var r={token:n.callback_data&&n.callback_data.jwt||n.jwt_token||n.token||n.auth_token||n.callback_data&&n.callback_data.token||n.session_data&&n.session_data.token||n.user_data_sent&&n.user_data_sent.token,session_id:n.session_id||n.sessionId||n.session||n.callback_data&&n.callback_data.session_id||n.session_data&&n.session_data.session_id,user_id:n.user_id||n.userId||n.user,partner_id:n.partner_id||n.partnerId||n.partner,type:n.type,timestamp:n.timestamp||t.timestamp||e.timestamp,signature:n.signature||n.callback_data&&n.callback_data.signature,user_info:n.user_info||n.userInfo||n.user_data||n.user_data_sent&&n.user_data_sent.user_info||n.session_data&&n.session_data.user_info,redirect_url:n.redirect_url||n.redirectUrl||n.redirect||n.session_data&&n.session_data.redirect_url};return console.log("📋 Données d'authentification extraites:",r),r}if(e.data){console.log("✅ Format WebSocket détecté, extraction directe de data"),console.log("🔍 Contenu complet de data:",e.data),console.log("🔍 Clés disponibles dans data:",Object.keys(e.data));var o=e.data;o.callback_data&&console.log("🔍 Contenu de callback_data:",o.callback_data),o.session_data&&console.log("🔍 Contenu de session_data:",o.session_data),o.user_data_sent&&console.log("🔍 Contenu de user_data_sent:",o.user_data_sent);var i={token:o.callback_data&&o.callback_data.jwt||o.jwt_token||o.token||o.auth_token||o.callback_data&&o.callback_data.token||o.session_data&&o.session_data.token||o.user_data_sent&&o.user_data_sent.token,session_id:o.session_id||o.sessionId||o.session||o.callback_data&&o.callback_data.session_id||o.session_data&&o.session_data.session_id,user_id:o.user_id||o.userId||o.user,partner_id:o.partner_id||o.partnerId||o.partner,type:o.type,timestamp:o.timestamp||e.timestamp,signature:o.signature||o.callback_data&&o.callback_data.signature,user_info:o.user_info||o.userInfo||o.user_data||o.user_data_sent&&o.user_data_sent.user_info||o.session_data&&o.session_data.user_info,redirect_url:o.redirect_url||o.redirectUrl||o.redirect||o.session_data&&o.session_data.redirect_url};return console.log("📋 Données d'authentification extraites:",i),i}return console.log("⚠️ Format non reconnu, tentative d'extraction directe"),{token:e.token||e.auth_token,session_id:e.session_id||e.sessionId,user_id:e.user_id||e.userId,partner_id:e.partner_id||e.partnerId,type:e.type,timestamp:e.timestamp,signature:e.signature,user_info:e.user_info||e.userInfo,redirect_url:e.redirect_url||e.redirectUrl}}},{key:"showSuccessMessage",value:function(e){console.log("✅ Affichage du message de succès");for(var t=null,n=0,r=["qr-area","qr-container","sunuid-qr-container"];n<r.length;n++){var o=r[n];if(t=document.getElementById(o))break}if(t){var i=e.user_info||{},s=i.name||i.username||"Utilisateur",a=i.email||"";t.innerHTML='\n <div style="\n text-align: center;\n padding: 40px 20px;\n background: #d4edda;\n border: 2px solid #28a745;\n border-radius: 10px;\n color: #155724;\n font-family: Arial, sans-serif;\n ">\n <div style="\n width: 60px;\n height: 60px;\n background: #28a745;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 20px auto;\n font-size: 30px;\n color: white;\n ">✅</div>\n <h3 style="margin: 0 0 10px 0; color: #155724;">🎉 Authentification réussie !</h3>\n <p style="margin: 0 0 15px 0; font-size: 16px; font-weight: bold;">\n Bienvenue, '.concat(s," !\n </p>\n ").concat(a?'<p style="margin: 0 0 15px 0; font-size: 14px; color: #6c757d;">'.concat(a,"</p>"):"",'\n <p style="margin: 0; font-size: 14px;">\n Votre identité a été vérifiée avec succès.\n </p>\n <div style="margin-top: 20px; font-size: 12px; color: #6c757d;">\n 🔄 Redirection en cours...\n </div>\n </div>\n '),console.log("✅ Message de succès affiché")}else console.warn("⚠️ Conteneur QR non trouvé pour afficher le message de succès")}},{key:"handleCallback",value:function(){var t=new URLSearchParams(e.location.search);if(t.has("token")&&t.has("session_id")){console.log("🔗 Callback SunuID détecté");var n={token:t.get("token"),state:t.get("state"),session_id:t.get("session_id"),user_id:t.get("user_id"),partner_id:t.get("partner_id"),type:t.get("type"),timestamp:t.get("timestamp"),signature:t.get("signature")};return console.log("📋 Données callback:",n),this.validateCallback(n),this.processAuthentication(n),!0}return!1}},{key:"validateCallback",value:function(e){if(console.log("🔒 Validation du callback..."),e.state&&e.state!==this.config.state)throw console.error("❌ État de sécurité invalide"),new Error("État de sécurité invalide");if(e.signature&&this.config.verifySignature&&!this.verifySignature(e))throw console.error("❌ Signature invalide"),new Error("Signature invalide");if(e.timestamp&&this.isExpired(e.timestamp))throw console.error("❌ Token expiré"),new Error("Token expiré");console.log("✅ Callback validé avec succès")}},{key:"processAuthentication",value:function(e){console.log("🔐 Traitement de l'authentification...");try{var t=this.decodeJWT(e.token),n={user_id:t.user_id||e.user_id,session_id:t.session_id||e.session_id,partner_id:t.partner_id||e.partner_id,type:t.type||e.type,iat:t.iat,exp:t.exp};console.log("👤 Données utilisateur:",n),this.emitWebSocketEvent("authentication_success",{userData:n,callbackData:e,timestamp:Date.now()}),this.config.onAuthenticationSuccess&&this.config.onAuthenticationSuccess(n,e),this.config.redirectAfterSuccess&&this.redirectAfterSuccess(n),console.log("✅ Authentification traitée avec succès")}catch(t){throw console.error("❌ Erreur lors du traitement:",t),this.config.onAuthenticationError&&this.config.onAuthenticationError(t,e),t}}},{key:"decodeJWT",value:function(e){try{var t=e.split(".");if(3!==t.length)throw new Error("Format JWT invalide");var n=t[1];return JSON.parse(atob(n))}catch(e){throw console.error("❌ Erreur décodage JWT:",e),new Error("Token JWT invalide")}}},{key:"verifySignature",value:function(e){var t=this.generateSignature(e);return e.signature===t}},{key:"generateSignature",value:function(e){var t="".concat(e.token,".").concat(e.state,".").concat(e.session_id,".").concat(e.timestamp);return btoa(t).slice(0,12)}},{key:"isExpired",value:function(e){return Math.floor(Date.now()/1e3)-parseInt(e)>(this.config.tokenMaxAge||300)}},{key:"redirectAfterSuccess",value:function(t){var n=this.config.redirectAfterSuccess;n=n.replace("{user_id}",t.user_id).replace("{session_id}",t.session_id).replace("{partner_id}",t.partner_id).replace("{type}",t.type),console.log("🔄 Redirection vers:",n),setTimeout(function(){e.location.href=n},100)}},{key:"generateState",value:function(){var e="sunuid_"+Date.now()+"_"+Math.random().toString(36).substr(2,9);return this.config.state=e,e}}],o&&r(t.prototype,o),i&&r(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,o,i,d,p,h,g,v,y,m,b,k,S,I,_,w,R,E,x,C,Q,T,D,q}();e.SunuID=d,e.sunuidInstance=null,e.initSunuID=function(t){try{return e.sunuidInstance=new d(t),e.sunuidInstance}catch(e){throw console.error("Erreur lors de l'initialisation de SunuID:",e),e}}}(window)}();
10
+ */(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}!function(e,t){var o,i,c={apiUrl:(null===(t=e.SunuIDConfig)||void 0===t?void 0:t.apiUrl)||"https://api.sunuid.fayma.sn",clientId:null,secretId:null,type:2,partnerName:null,theme:"light",language:"fr",autoRefresh:!1,refreshInterval:3e4,autoInit:!1,onSuccess:null,onError:null,onStatusUpdate:null,onExpired:null,enableSecurityLogs:!0,validateInputs:!0,maxRetries:3,requestTimeout:1e4,secureInit:!1,secureInitUrl:null!==(o=e.SunuIDConfig)&&void 0!==o&&null!==(o=o.apiUrl)&&void 0!==o&&o.includes("api.sunuid.fayma.sn")?"https://api.sunuid.fayma.sn/secure-init":(null===(i=e.SunuIDConfig)||void 0===i||null===(i=i.apiUrl)||void 0===i?void 0:i.replace("/api",""))+"/secure-init"||"https://api.sunuid.fayma.sn/secure-init",token:null,forceRemoteServer:!0,useLocalFallback:!1,redirectAfterSuccess:null,verifySignature:!1,tokenMaxAge:300,onAuthenticationSuccess:null,onAuthenticationError:null,state:null},d=function(){return t=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.config=s(s({},c),t),this.qrCode=null,this.refreshTimer=null,this.isInitialized=!1,this.socket=null,this.initPromise=null,console.log("🔧 SDK SunuID créé - Appelez init() manuellement")},o=[{key:"init",value:(q=n(a().m(function e(){return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(!this.isInitialized){e.n=1;break}return console.log("⚠️ SDK déjà initialisé, ignoré"),e.a(2);case 1:if(!this.initPromise){e.n=2;break}return console.log("⚠️ Initialisation déjà en cours, attente..."),e.a(2,this.initPromise);case 2:if(!this._initInProgress){e.n=3;break}return console.log("⚠️ Initialisation en cours, ignoré"),e.a(2);case 3:return this._initInProgress=!0,this.initPromise=this._doInit(),e.p=4,e.n=5,this.initPromise;case 5:return e.p=5,this._initInProgress=!1,e.f(5);case 6:return e.a(2,this.initPromise)}},e,this,[[4,,5,6]])})),function(){return q.apply(this,arguments)})},{key:"_doInit",value:(D=n(a().m(function e(){var t;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(e.p=0,!this.handleCallback()){e.n=1;break}return console.log("✅ Callback traité, initialisation terminée"),e.a(2);case 1:if(!this.config.secureInit){e.n=3;break}return e.n=2,this.secureInit();case 2:e.n=4;break;case 3:this.config.validateInputs&&this.validateSecurityParams();case 4:return this.logSecurityEvent("SDK_INIT_START",{apiUrl:this.config.apiUrl,type:this.config.type,secureInit:this.config.secureInit}),e.n=5,this.fetchPartnerInfo();case 5:this.obfuscateCredentials(),this.isInitialized=!0,console.log("SunuID SDK initialisé avec succès"),console.log("📋 Configuration SDK:",{apiUrl:this.config.apiUrl,type:this.config.type,partnerName:this.config.partnerName,clientId:this.config.clientId?"***"+this.config.clientId.slice(-4):"null",secretId:this.config.secretId?"***"+this.config.secretId.slice(-4):"null",secureInit:this.config.secureInit,theme:this.config.theme}),this.logSecurityEvent("SDK_INIT_SUCCESS"),this.initWebSocket(),e.n=7;break;case 6:throw e.p=6,t=e.v,this.logSecurityEvent("SDK_INIT_ERROR",{error:t.message}),t;case 7:return e.a(2)}},e,this,[[0,6]])})),function(){return D.apply(this,arguments)})},{key:"secureInit",value:(T=n(a().m(function e(){var t,n,r,o,i;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,this.logSecurityEvent("SECURE_INIT_START"),t={type:this.config.type,partnerName:this.config.partnerName,theme:this.config.theme},e.n=1,fetch(this.config.secureInitUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});case 1:if((n=e.v).ok){e.n=2;break}throw new Error("Erreur HTTP: ".concat(n.status));case 2:return e.n=3,n.json();case 3:if(r=e.v,console.log("📋 Réponse initialisation sécurisée:",r),r.success){e.n=4;break}throw new Error(r.error||"Erreur lors de l'initialisation sécurisée");case 4:if(this.config.token=r.data.token,this.config.apiUrl=r.data.api_url,!(o=this.decodeSecureToken(r.data.token))){e.n=5;break}this.config.clientId=o.client_id,this.config.secretId=o.secret_id,e.n=6;break;case 5:throw new Error("Impossible de décoder le token sécurisé");case 6:this.config.expiresIn=r.data.expires_in,this.config.maxRequests=r.data.max_requests,this.config.requestCount=0,this.logSecurityEvent("SECURE_INIT_SUCCESS",{expiresIn:r.data.expires_in,maxRequests:r.data.max_requests}),console.log("✅ Initialisation sécurisée réussie"),e.n=8;break;case 7:throw e.p=7,i=e.v,this.logSecurityEvent("SECURE_INIT_ERROR",{error:i.message}),new Error("Échec de l'initialisation sécurisée: ".concat(i.message));case 8:return e.a(2)}},e,this,[[0,7]])})),function(){return T.apply(this,arguments)})},{key:"decodeSecureToken",value:function(e){try{var t=e.split(".");if(2!==t.length)return console.error("❌ Format de token invalide"),null;var n=u(t,2),r=n[0],o=(n[1],atob(r)),i=JSON.parse(o);return i.exp&&i.exp<Date.now()/1e3?(console.error("❌ Token expiré"),null):(console.log("✅ Token décodé avec succès"),i)}catch(e){return console.error("❌ Erreur décodage token:",e),null}}},{key:"initWebSocket",value:function(){var e=this;try{if("undefined"==typeof io)return console.warn("⚠️ Socket.IO non disponible, WebSocket sera initialisé plus tard"),void setTimeout(function(){return e.initWebSocket()},1e3);var t=this.getClientIP();this.socket?console.log("🌐 WebSocket déjà connecté"):(console.log("🌐 Initialisation Socket.IO..."),this.socket=io("wss://samasocket.fayma.sn:9443",{query:{token:this.config.clientId,type:"web",userId:this.config.clientId,username:t},transports:["websocket","polling"]}),this.socket.on("connect",function(){console.log("🌐 WebSocket connecté avec succès"),console.log("📊 Socket ID:",e.socket.id),e.socket.connected=!0}),this.socket.on("disconnect",function(t){console.log("❌ WebSocket déconnecté:",t),e.socket.connected=!1}),this.socket.on("connect_error",function(t){console.error("❌ Erreur connexion WebSocket:",t),e.socket.connected=!1}),this.socket.on("qr_status_update",function(t){console.log("📱 Mise à jour statut QR reçue:",t),e.handleQRStatusUpdate(t)}),this.socket.on("qr_scan_success",function(t){console.log("✅ Scan QR réussi reçu:",t),e.handleQRScanSuccess(t)}),this.socket.on("qr_expired",function(t){console.log("⏰ QR expiré reçu:",t),e.handleQRExpired(t)}),this.socket.on("qr_scan_initiated",function(t){console.log("🔍 QR Scan Initiated reçu:",t),e.showQRLoader()}),this.socket.on("message",function(t){console.log("📨 Message socket reçu:",t),t&&"qr_scan_initiated"===t.type&&(console.log("🔍 QR Scan Initiated détecté dans message:",t),e.showQRLoader())}),this.socket.onAny=this.socket.onAny||function(e,t){console.log("🌐 Socket Event [".concat(e,"]:"),t)},this.socket.onAny(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];console.log("🌐 Socket Event [".concat(e,"]:"),n)}))}catch(e){console.error("❌ Erreur initialisation WebSocket:",e)}}},{key:"getClientIP",value:function(){return"127.0.0.1"}},{key:"getTypeName",value:function(e){switch(e){case 1:return"KYC";case 2:return"AUTH";case 3:return"SIGNATURE";default:return"TYPE-".concat(e)}}},{key:"validateSecurityParams",value:function(){var e=[];if(this.config.clientId&&"string"==typeof this.config.clientId?this.config.clientId.length<10&&e.push("clientId trop court"):e.push("clientId invalide ou manquant"),this.config.secretId&&"string"==typeof this.config.secretId?this.config.secretId.length<32&&e.push("secretId trop court (minimum 32 caractères)"):e.push("secretId invalide ou manquant"),this.config.apiUrl&&this.isValidUrl(this.config.apiUrl)||e.push("apiUrl invalide"),[1,2,3].includes(this.config.type)||e.push("type invalide (doit être 1, 2 ou 3)"),e.length>0)throw this.logSecurityEvent("VALIDATION_ERROR",{errors:e}),new Error("Paramètres de sécurité invalides: ".concat(e.join(", ")));this.logSecurityEvent("VALIDATION_SUCCESS")}},{key:"isValidUrl",value:function(e){try{var t=new URL(e);return"https:"===t.protocol||"http:"===t.protocol}catch(e){return!1}}},{key:"logSecurityEvent",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.config.enableSecurityLogs){var r={timestamp:(new Date).toISOString(),event:t,data:n,userAgent:navigator.userAgent,url:e.location.href};console.warn("🔒 [SECURITY]",r),e.SunuIDSecurityLogs||(e.SunuIDSecurityLogs=[]),e.SunuIDSecurityLogs.push(r)}}},{key:"obfuscateCredentials",value:function(){this.config.originalClientId=this.config.clientId,this.config.originalSecretId=this.config.secretId,this.config.clientId&&(this.config.clientIdDisplay=this.config.clientId.replace(/(.{3}).*(.{3})/,"$1***$2")),this.config.secretId&&(this.config.secretIdDisplay=this.config.secretId.replace(/(.{4}).*(.{4})/,"$1***$2"))}},{key:"sanitizeInput",value:function(e){return"string"!=typeof e?e:e.replace(/[<>]/g,"").replace(/javascript:/gi,"").trim()}},{key:"handleQRStatusUpdate",value:function(e){console.log("📱 QR Status Update:",e),this.config.onStatusUpdate&&this.config.onStatusUpdate(e)}},{key:"handleQRScanSuccess",value:function(e){console.log("✅ QR Scan Success reçu:",e);try{var t=this.extractAuthDataFromWebSocket(e);this.processAuthentication(t),this.showSuccessMessage(t),this.config.onSuccess&&this.config.onSuccess(t),console.log("✅ Authentification WebSocket traitée avec succès")}catch(t){console.error("❌ Erreur lors du traitement WebSocket:",t),this.config.onAuthenticationError&&this.config.onAuthenticationError(t,e)}}},{key:"handleQRExpired",value:function(e){console.log("⏰ QR Expired:",e),this.config.onExpired&&this.config.onExpired(e)}},{key:"emitWebSocketEvent",value:function(e,t){this.socket&&this.socket.connected?(this.socket.emit(e,t),console.log("📤 Événement WebSocket émis: ".concat(e),t)):console.warn("⚠️ WebSocket non connecté, impossible d'émettre l'événement:",e)}},{key:"getWebSocketStatus",value:function(){return this.socket?this.socket.connected?"connected":"disconnected":"not_initialized"}},{key:"forceWebSocketInit",value:function(){"undefined"==typeof io||this.socket||(console.log("🔄 Forçage de l'initialisation WebSocket..."),this.initWebSocket())}},{key:"generateQR",value:(Q=n(a().m(function t(){var n,r,o,i,c,l,u,d,f,p,h,g=arguments;return a().w(function(t){for(;;)switch(t.p=t.n){case 0:if(n=g.length>0&&void 0!==g[0]?g[0]:"sunuid-qr-container",r=g.length>1&&void 0!==g[1]?g[1]:{},!this.initPromise){t.n=2;break}return t.n=1,this.initPromise;case 1:this.initPromise=null;case 2:if(this.isInitialized){t.n=3;break}throw new Error("SunuID: SDK non initialisé");case 3:return console.log("🎯 generateQR appelé avec containerId:",n),console.log("🔍 Attente connexions API et WebSocket..."),t.p=4,t.n=5,this.waitForConnections(5e3);case 5:o=t.v,console.log("✅ Connexions prêtes:",o),t.n=7;break;case 6:throw t.p=6,p=t.v,console.error("❌ Erreur connexions:",p.message),new Error("Connexions non disponibles - Impossible de générer le QR code");case 7:return t.p=7,i=this.socket?this.socket.id:"timeout-socket-id",c=i,console.log("📄 Contenu QR préparé:",c),console.log("🔌 Socket ID:",i),l=this.config.partnerName||"Partner_unknown",t.n=8,this.makeRequest("/qr-generate",s({type:this.config.type,data:c,label:"".concat(this.getTypeName(this.config.type)," ").concat(l)},r));case 8:if(!(u=t.v).success){t.n=11;break}if(console.log("📋 Réponse QR API complète:",u),console.log("📋 Structure response.data:",u.data),(d=u.data.qrCodeUrl)&&d.startsWith("/")&&(d="".concat(this.config.apiUrl).concat(d)),d){t.n=10;break}if(console.warn("⚠️ qrCodeUrl non trouvé dans la réponse, recherche d'alternatives..."),!(d=u.data.qr_url||u.data.qrUrl||u.data.url||u.data.image_url||u.data.imageUrl)){t.n=9;break}console.log("✅ URL QR trouvée dans un champ alternatif:",d),t.n=10;break;case 9:throw console.error("❌ Aucune URL QR trouvée dans la réponse"),new Error("URL du QR code non trouvée dans la réponse API");case 10:return this.currentQRUrl=d,console.log("✅ QR code généré par API principale:",d),console.log("📄 Contenu QR final:",c),console.log("🏷️ Label QR:",u.data.label||"N/A"),console.log("🆔 Session ID:",u.data.sessionId||"N/A"),this.displayQRCode(n,d,this.config.type,r),this.startAutoRefresh(n,this.config.type,r),this.emitWebSocketEvent("qr_generated",{type:this.config.type,qrCodeUrl:d,socketId:i,qrContent:c,label:u.data.label,sessionId:u.data.sessionId,timestamp:Date.now()}),t.a(2,s(s({},u.data),{},{qrCodeUrl:d,qrContent:c,label:u.data.label,sessionId:u.data.sessionId}));case 11:throw new Error(u.message||"Erreur lors de la génération du QR code");case 12:t.n=14;break;case 13:throw t.p=13,h=t.v,console.error("Erreur API détectée:",h.message),console.error("Stack trace complet:",h.stack),console.error("Configuration SDK:",{apiUrl:this.config.apiUrl,type:this.config.type,secureInit:this.config.secureInit,clientId:this.config.clientId?"***"+this.config.clientId.slice(-4):"null",secretId:this.config.secretId?"***"+this.config.secretId.slice(-4):"null"}),this.config.useLocalFallback?(console.log("🔍 Vérification fallback local..."),console.log("🔍 Hostname:",e.location.hostname),console.log("🔍 Protocol:",e.location.protocol),console.log("🔍 URL complète:",e.location.href),f="localhost"===e.location.hostname||"127.0.0.1"===e.location.hostname||"file:"===e.location.protocol,console.log("🔍 Est local:",f),f?(console.log("🔄 Tentative fallback vers service QR local..."),console.log("❌ Fallback local non implémenté - utilisation serveur distant uniquement")):console.log("❌ Pas en local, pas de fallback")):console.log("🔒 Fallback local désactivé, utilisation serveur distant uniquement"),console.log('Affichage du message "Service non disponible" pour type '+this.config.type),this.displayServiceUnavailable(n,this.config.type),new Error("Service non disponible");case 14:return t.a(2)}},t,this,[[7,13],[4,6]])})),function(){return Q.apply(this,arguments)})},{key:"generateCustomQR",value:(C=n(a().m(function e(t,n){var r,o,i,c,l=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(r=l.length>2&&void 0!==l[2]?l[2]:{},!this.initPromise){e.n=2;break}return e.n=1,this.initPromise;case 1:this.initPromise=null;case 2:if(this.isInitialized){e.n=3;break}throw new Error("SunuID: SDK non initialisé");case 3:return e.p=3,e.n=4,this.makeRequest("/qr-generate",s({type:n},r));case 4:if(!(o=e.v).success){e.n=5;break}return i="".concat("https://sunuid.fayma.sn").concat(o.data.qrcode),this.displayQRCode(t,i,n,r),console.log("✅ QR code personnalisé généré par API principale:",i),console.log("📄 Code de session:",o.data.code),console.log("🆔 Service ID:",o.data.service_id),this.startAutoRefresh(t,n,r),e.a(2,s(s({},o.data),{},{qrCodeUrl:i,sessionId:o.data.service_id}));case 5:throw new Error(o.message||"Erreur lors de la génération du QR code");case 6:e.n=8;break;case 7:throw e.p=7,c=e.v,console.error("Erreur API détectée:",c.message),console.error("Stack trace complet:",c.stack),console.error("Configuration SDK (Custom):",{apiUrl:this.config.apiUrl,type:n,secureInit:this.config.secureInit,clientId:this.config.clientId?"***"+this.config.clientId.slice(-4):"null",secretId:this.config.secretId?"***"+this.config.secretId.slice(-4):"null"}),console.log('Affichage du message "Service non disponible" pour type '+n),this.displayServiceUnavailable(t,n),new Error("Service non disponible");case 8:return e.a(2)}},e,this,[[3,7]])})),function(e,t){return C.apply(this,arguments)})},{key:"generateAuthQR",value:(x=n(a().m(function e(t){var n,r=arguments;return a().w(function(e){for(;;)if(0===e.n)return n=r.length>1&&void 0!==r[1]?r[1]:{},e.a(2,this.generateQR(t,n))},e,this)})),function(e){return x.apply(this,arguments)})},{key:"generateKYCQR",value:(E=n(a().m(function e(t){var n,r,o=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return n=o.length>1&&void 0!==o[1]?o[1]:{},r=this.config.type,this.config.type=1,e.p=1,e.n=2,this.generateQR(t,n);case 2:return e.a(2,e.v);case 3:return e.p=3,this.config.type=r,e.f(3);case 4:return e.a(2)}},e,this,[[1,,3,4]])})),function(e){return E.apply(this,arguments)})},{key:"generateSignatureQR",value:(R=n(a().m(function e(t){var n,r,o=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return n=o.length>1&&void 0!==o[1]?o[1]:{},r=this.config.type,this.config.type=3,e.p=1,e.n=2,this.generateQR(t,n);case 2:return e.a(2,e.v);case 3:return e.p=3,this.config.type=r,e.f(3);case 4:return e.a(2)}},e,this,[[1,,3,4]])})),function(e){return R.apply(this,arguments)})},{key:"checkQRStatus",value:(w=n(a().m(function e(t){var n,r;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(this.isInitialized){e.n=1;break}throw new Error("SunuID: SDK non initialisé");case 1:return e.p=1,e.n=2,this.makeRequest("/qr-status",{serviceId:t});case 2:if(!(n=e.v).success){e.n=3;break}return e.a(2,n.data);case 3:throw new Error(n.message||"Erreur lors de la vérification du statut");case 4:e.n=6;break;case 5:throw e.p=5,r=e.v,this.handleError(r),r;case 6:return e.a(2)}},e,this,[[1,5]])})),function(e){return w.apply(this,arguments)})},{key:"generateQRWithContent",value:(_=n(a().m(function t(n,r,o){var i,s,c,l=arguments;return a().w(function(t){for(;;)switch(t.p=t.n){case 0:if(i=l.length>3&&void 0!==l[3]?l[3]:{},console.log("🎨 Génération QR avec contenu:",n),t.p=1,"localhost"!==e.location.hostname&&"127.0.0.1"!==e.location.hostname&&"file:"!==e.location.protocol){t.n=3;break}return console.log("🏠 Utilisation service QR local..."),t.n=2,this.generateQRLocal(n,r,o,i);case 2:if(!(s=t.v)){t.n=3;break}return t.a(2,s);case 3:return console.log("🌐 Utilisation service QR distant..."),t.n=4,this.generateQRRemote(n,r,o,i);case 4:return t.a(2,t.v);case 5:return t.p=5,c=t.v,console.error("❌ Erreur génération QR:",c),this.displayQRContent(r,n,o,i),t.a(2,null)}},t,this,[[1,5]])})),function(e,t,n){return _.apply(this,arguments)})},{key:"generateQRLocal",value:(I=n(a().m(function e(t,n,r){var o,i,s,c,l,u=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return o=u.length>3&&void 0!==u[3]?u[3]:{},e.p=1,e.n=2,fetch("http://localhost:8000/api/generate/text",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"text=".concat(encodeURIComponent(t),"&size=300")});case 2:if(!(i=e.v).ok){e.n=4;break}return e.n=3,i.json();case 3:return s=e.v,c="data:image/png;base64,".concat(s.qrcode),this.displayQRCode(n,c,r,o),e.a(2,c);case 4:e.n=6;break;case 5:e.p=5,l=e.v,console.log("❌ Service QR local non disponible:",l.message);case 6:return e.a(2,null)}},e,this,[[1,5]])})),function(e,t,n){return I.apply(this,arguments)})},{key:"generateQRRemote",value:(S=n(a().m(function e(t,n,r){var o,i,s,c,l,u=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return o=u.length>3&&void 0!==u[3]?u[3]:{},e.p=1,e.n=2,fetch("https://api.sunuid.fayma.sn/qr-generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t,size:300,type:r})});case 2:if(!(i=e.v).ok){e.n=4;break}return e.n=3,i.json();case 3:return s=e.v,c="data:image/png;base64,".concat(s.qrcode),this.displayQRCode(n,c,r,o),e.a(2,c);case 4:e.n=6;break;case 5:e.p=5,l=e.v,console.error("❌ Erreur service QR distant:",l);case 6:return this.displayQRContent(n,t,r,o),e.a(2,null)}},e,this,[[1,5]])})),function(e,t,n){return S.apply(this,arguments)})},{key:"displayQRContent",value:function(e,t,n){var r=document.getElementById(e);if(!r)throw new Error("Conteneur avec l'ID \"".concat(e,'" non trouvé'));var o=this.getTypeName(n);r.innerHTML='\n <div class="sunuid-qr-code">\n <div class="sunuid-qr-header">\n <h3>'.concat(o,'</h3>\n </div>\n <div class="sunuid-qr-content" style="text-align: center; padding: 20px; background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; margin: 10px 0;">\n <p><strong>Contenu QR Code:</strong></p>\n <p style="font-family: monospace; font-size: 14px; word-break: break-all;">').concat(t,'</p>\n </div>\n <div class="sunuid-qr-instructions">\n <p>Contenu QR généré avec le format: {type}-{code}-{socketid}</p>\n </div>\n </div>\n '),console.log("✅ Contenu QR affiché:",t)}},{key:"displayQRCode",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=document.getElementById(e);if(!o)throw new Error("Conteneur avec l'ID \"".concat(e,'" non trouvé'));o.innerHTML="";var i=document.createElement("div");i.className="sunuid-qr-code";var s=this.getTypeName(n);i.innerHTML='\n <div class="sunuid-qr-header">\n <h3>'.concat(1===n?"Vérification KYC":2===n?"Authentification":3===n?"Signature":"Service Type "+n,'</h3>\n </div>\n <div class="sunuid-qr-image">\n <img src="').concat(t,'" alt="QR Code ').concat(s,'" style="max-width: 300px; border: 1px solid #ddd; border-radius: 5px;" />\n </div>\n \n '),o.appendChild(i),this.applyTheme(r.theme||this.config.theme),console.log("✅ QR code affiché:",t)}},{key:"generateCustomQRCode",value:(k=n(a().m(function e(t,n){var r,o;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(console.log("🎨 Début génération QR personnalisé..."),console.log("📄 Contenu:",t),console.log("🏷️ Label:",n),(r=document.getElementById("sunuid-qr-container"))||(r=document.getElementById("qr-container")),r){e.n=1;break}return console.error("❌ QR container not found"),e.a(2);case 1:return console.log("✅ QR container trouvé"),r.innerHTML='<div style="text-align: center; padding: 20px;"><p>Génération QR code...</p></div>',e.p=2,console.log("🎨 Tentative génération via API principale..."),e.n=3,this.generateQRPHP(t,n,r);case 3:console.log("✅ QR code généré avec succès"),e.n=5;break;case 4:e.p=4,o=e.v,console.error("❌ Erreur génération API:",o),console.log("⚠️ Affichage image par défaut"),this.displayDefaultQR(r,t,n);case 5:return e.a(2)}},e,this,[[2,4]])})),function(e,t){return k.apply(this,arguments)})},{key:"generateQRClientSide",value:(b=n(a().m(function e(t,n,r){var o,i,s=this;return a().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,this.ensureQRCodeLibrary();case 1:if("undefined"!=typeof QRCode){e.n=2;break}throw new Error("QRCode library non disponible");case 2:return(o=document.createElement("canvas")).width=300,o.height=320,(i=o.getContext("2d")).fillStyle="#FFFFFF",i.fillRect(0,0,300,320),e.a(2,new Promise(function(e,a){QRCode.toCanvas(o,t,{width:280,margin:10,color:{dark:"#000000",light:"#FFFFFF"}},function(t){if(t)a(t);else{i.fillStyle="#333333",i.font="bold 14px Arial",i.textAlign="center",i.fillText(n,150,305);var c=o.toDataURL("image/png");s.currentQRUrl=c,r.innerHTML='\n <div style="text-align: center; padding: 20px;">\n <img src="'.concat(c,'" alt="QR Code" style="max-width: 300px; border: 2px solid #ddd; border-radius: 10px;">\n </div>\n '),s.showQRInstructions(r),e()}})}))}},e,this)})),function(e,t,n){return b.apply(this,arguments)})},{key:"generateQRPHP",value:(m=n(a().m(function e(t,n,r){var o,i,s,c,l,u;return a().w(function(e){for(;;)switch(e.n){case 0:return o=this.config.forceRemoteServer||this.config.apiUrl.includes("api.sunuid.fayma.sn")?"https://api.sunuid.fayma.sn/qr-generate":this.config.apiUrl.includes("localhost")||this.config.apiUrl.includes("127.0.0.1")?"http://localhost:8000/api/generate/text":this.config.apiUrl+"/qr-generate",console.log("🔗 URL QR Generator:",o),o.includes("localhost:8000")?(s="application/x-www-form-urlencoded",i=new URLSearchParams({text:t,size:300,margin:10,foreground_color:"000000",background_color:"FFFFFF"})):(s="application/json",i=JSON.stringify({type:this.config.type,client_id:this.config.clientId,secret_id:this.config.secretId,content:t,label:n})),e.n=1,fetch(o,{method:"POST",headers:{"Content-Type":s,Accept:"application/json"},body:i});case 1:if((c=e.v).ok){e.n=2;break}throw new Error("Erreur HTTP: ".concat(c.status));case 2:return e.n=3,c.json();case 3:if((l=e.v).success){e.n=4;break}throw new Error("Erreur QR: ".concat(l.error));case 4:u=o.includes("localhost:8000")?l.data_uri:"".concat("https://sunuid.fayma.sn").concat(l.data.qrcode),this.currentQRUrl=u,r.innerHTML='\n <div style="text-align: center; padding: 20px;">\n <img src="'.concat(u,'" alt="QR Code" style="max-width: 300px; border: 2px solid #ddd; border-radius: 10px;">\n </div>\n '),this.showQRInstructions(r);case 5:return e.a(2)}},e,this)})),function(e,t,n){return m.apply(this,arguments)})},{key:"displayDefaultQR",value:function(e,t,n){e.innerHTML='\n <div style="text-align: center; padding: 20px; color: #666;">\n <div style="width: 300px; height: 300px; background: #f0f0f0; border: 2px solid #ddd; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto;">\n <div>\n <p style="font-size: 24px; margin: 0;">📱</p>\n <p style="font-size: 14px; margin: 10px 0 0 0;">QR Code</p>\n </div>\n </div>\n <p style="margin-top: 10px; font-size: 12px;">'.concat(n,'</p>\n <p style="font-size: 10px; color: #999; margin-top: 5px;">Contenu: ').concat(t,"</p>\n </div>\n ")}},{key:"ensureQRCodeLibrary",value:(y=n(a().m(function e(){return a().w(function(e){for(;;)switch(e.n){case 0:if("undefined"==typeof QRCode){e.n=1;break}return console.log("✅ QRCode library déjà disponible"),e.a(2,!0);case 1:return console.log("📦 Chargement QRCode library..."),e.a(2,new Promise(function(e,t){var n=document.createElement("script");n.src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/lib/browser.min.js",n.onload=function(){setTimeout(function(){"undefined"!=typeof QRCode?(console.log("✅ QRCode library chargée"),e(!0)):(console.error("❌ QRCode non disponible après chargement"),t(new Error("QRCode library non disponible après chargement")))},200)},n.onerror=function(){console.error("❌ Erreur chargement QRCode library"),t(new Error("Erreur chargement QRCode library"))},document.head.appendChild(n)}))}},e)})),function(){return y.apply(this,arguments)})},{key:"showQRInstructions",value:function(e){var t=e.parentElement.querySelector(".sunuid-qr-instructions"),n=e.parentElement.querySelector(".sunuid-qr-status");t&&(t.style.display="block",t.classList.add("sunuid-qr-ready")),n&&(n.style.display="block",n.classList.add("sunuid-qr-ready"))}},{key:"addLogoToCenter",value:function(e,t,n,r,o){try{var i=new Image;i.onload=function(){var o=40,s=t+(r-o)/2,a=n+(r-o)/2;e.fillStyle="white",e.fillRect(s-2,a-2,44,44),e.drawImage(i,s,a,o,o)},i.src="src/logoqr.png"}catch(e){console.warn("Logo non disponible:",e)}}},{key:"displayFallbackImage",value:function(){console.log("⚠️ Affichage de l'image de fallback");var e=document.getElementById("sunuid-qr-container");e&&(e.innerHTML='\n <div style="text-align: center; padding: 20px; color: #666;">\n <p>⚠️ Génération QR personnalisé non disponible</p>\n <p>Utilisation de l\'image par défaut</p>\n <p><strong>Debug:</strong> QRCode disponible: '.concat("undefined"!=typeof QRCode,"</p>\n <p><strong>Debug:</strong> Container trouvé: ").concat(null!==e,"</p>\n </div>\n "))}},{key:"displayServiceUnavailable",value:function(e,t){console.log("displayServiceUnavailable appelée pour ".concat(e,", type: ").concat(t));var n=document.getElementById(e);n?n.innerHTML='\n <div class="sunuid-service-unavailable" style="\n text-align: center;\n padding: 40px 20px;\n background: #f8f9fa;\n border: 2px dashed #dee2e6;\n border-radius: 10px;\n color: #6c757d;\n font-family: Arial, sans-serif;\n ">\n <div style="font-size: 48px; margin-bottom: 20px;">⚠️</div>\n <h3 style="margin: 0 0 10px 0; color: #495057;">Service Non Disponible</h3>\n <p style="margin: 0; font-size: 14px;">\n Le service d\'authentification est temporairement indisponible.<br>\n Veuillez réessayer plus tard.\n </p>\n <div style="margin-top: 20px; font-size: 12px; color: #adb5bd;">\n Type: '.concat(String(t).toUpperCase(),"\n </div>\n </div>\n "):console.error("Container ".concat(e," non trouvé"))}},{key:"refreshQR",value:(v=n(a().m(function e(t){var n,r,o,i,s=arguments;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:if(n=s.length>1&&void 0!==s[1]?s[1]:{},e.p=1,!this.currentQRUrl){e.n=3;break}return console.log("🔄 Vérification du statut du QR code existant..."),e.n=2,this.generateQR(t,n);case 2:return r=e.v,e.a(2,r);case 3:return console.log("🔄 Pas de QR code existant, génération d'un nouveau..."),e.n=4,this.generateQR(t,n);case 4:return o=e.v,e.a(2,o);case 5:e.n=7;break;case 6:throw e.p=6,i=e.v,console.error("Erreur lors du rafraîchissement:",i.message),this.displayServiceUnavailable(t,this.config.type),i;case 7:return e.a(2)}},e,this,[[1,6]])})),function(e){return v.apply(this,arguments)})},{key:"startAutoRefresh",value:function(e,t,r){var o=this;this.config.autoRefresh&&(this.refreshTimer&&(clearInterval(this.refreshTimer),console.log("🔄 Timer de rafraîchissement précédent arrêté")),this.refreshTimer=setInterval(n(a().m(function n(){var i;return a().w(function(n){for(;;)switch(n.p=n.n){case 0:return n.p=0,console.log("🔄 Rafraîchissement automatique du QR code..."),n.n=1,o.refreshQR(e,t,r);case 1:n.n=3;break;case 2:n.p=2,i=n.v,console.warn("Erreur lors du rafraîchissement automatique:",i);case 3:return n.a(2)}},n,null,[[0,2]])})),this.config.refreshInterval),console.log("🔄 Timer de rafraîchissement démarré (".concat(this.config.refreshInterval,"ms)")))}},{key:"makeRequest",value:(g=n(a().m(function t(n,r){var o,i,s,c,u,d,f,p,h,g=this;return a().w(function(t){for(;;)switch(t.n){case 0:if(this.isInitialized){t.n=1;break}throw this.logSecurityEvent("REQUEST_BEFORE_INIT",{endpoint:n}),new Error("SDK non initialisé");case 1:if(!this.config.secureInit){t.n=2;break}if(this.config.requestCount++,!(this.config.requestCount>this.config.maxRequests)){t.n=2;break}throw this.logSecurityEvent("API_REQUEST_LIMIT_EXCEEDED",{requestCount:this.config.requestCount,maxRequests:this.config.maxRequests}),new Error("Limite de requêtes dépassée");case 2:s=this.sanitizeRequestData(r),console.log("🔍 Debug makeRequest - endpoint:",n),console.log("🔍 Debug makeRequest - apiUrl:",this.config.apiUrl),console.log("🔍 Debug makeRequest - url:","".concat(this.config.apiUrl).concat(n)),console.log("🔍 Debug makeRequest - data:",JSON.stringify(s,null,2)),console.log("🔍 Debug makeRequest - secureInit:",this.config.secureInit),console.log("🔍 Debug makeRequest - isInitialized:",this.isInitialized),c=(null===(o=e.SunuIDConfig)||void 0===o||null===(o=o.endpoints)||void 0===o?void 0:o[n.replace("/","")])||n,u="".concat(this.config.apiUrl).concat(c),console.log("🔍 URL finale construite:",u),console.log("🔍 EndpointPath:",c),console.log("🔍 SunuIDConfig endpoints:",JSON.stringify(null===(i=e.SunuIDConfig)||void 0===i?void 0:i.endpoints)),this.logSecurityEvent("API_REQUEST_START",{endpoint:c,url:u,dataKeys:Object.keys(s),secureInit:this.config.secureInit}),d=0,f=this.config.maxRetries,p=a().m(function e(){var t,n,r,o,i,l,p,h;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,t=new AbortController,n=setTimeout(function(){return t.abort()},g.config.requestTimeout),r={"Content-Type":"application/json"},e.n=1,fetch(u,{method:"POST",headers:r,body:JSON.stringify(s),signal:t.signal});case 1:if(o=e.v,clearTimeout(n),o.ok){e.n=3;break}return e.n=2,o.text();case 2:i=e.v;try{l=JSON.parse(i)}catch(e){l={message:i}}throw g.logSecurityEvent("API_REQUEST_ERROR",{status:o.status,statusText:o.statusText,error:l.message}),new Error(l.message||"Erreur HTTP: ".concat(o.status));case 3:return e.n=4,o.json();case 4:return p=e.v,g.logSecurityEvent("API_REQUEST_SUCCESS",{endpoint:c,responseKeys:Object.keys(p)}),e.a(2,{v:p});case 5:if(e.p=5,h=e.v,d++,"AbortError"!==h.name){e.n=7;break}if(g.logSecurityEvent("API_REQUEST_TIMEOUT",{retryCount:d}),!(d>f)){e.n=6;break}throw new Error("Timeout de la requête API");case 6:return e.a(2,0);case 7:if(!(d>f)){e.n=8;break}throw g.logSecurityEvent("API_REQUEST_MAX_RETRIES",{retryCount:d,error:h.message}),h;case 8:return e.n=9,new Promise(function(e){return setTimeout(e,1e3*d)});case 9:return e.a(2)}},e,null,[[0,5]])});case 3:if(!(d<=f)){t.n=7;break}return t.d(l(p()),4);case 4:if(0!==(h=t.v)){t.n=5;break}return t.a(3,3);case 5:if(!h){t.n=6;break}return t.a(2,h.v);case 6:t.n=3;break;case 7:return t.a(2)}},t,this)})),function(e,t){return g.apply(this,arguments)})},{key:"sanitizeRequestData",value:function(e){for(var t={},n=0,r=Object.entries(e);n<r.length;n++){var o=u(r[n],2),i=o[0],s=o[1];"string"==typeof s?t[i]=this.sanitizeInput(s):"object"===f(s)&&null!==s?t[i]=this.sanitizeRequestData(s):t[i]=s}return t.client_id=this.config.originalClientId||this.config.clientId,t.secret_id=this.config.originalSecretId||this.config.secretId,console.log("🔍 Credentials dans sanitizeRequestData - clientId:",this.config.clientId),console.log("🔍 Credentials dans sanitizeRequestData - secretId:",this.config.secretId?"***"+this.config.secretId.slice(-4):"null"),console.log("🔍 Credentials dans sanitizeRequestData - sanitizedClientId:",t.client_id),console.log("🔍 Credentials dans sanitizeRequestData - sanitizedSecretId:",t.secret_id?"***"+t.secret_id.slice(-4):"null"),console.log("🔍 Credentials dans sanitizeRequestData - data complet:",JSON.stringify(t,null,2)),t}},{key:"generateRequestId",value:function(){return"req_"+Date.now()+"_"+Math.random().toString(36).substr(2,9)}},{key:"generateSessionCode",value:function(){var e=Date.now(),t=Math.random().toString(36).substr(2,9),n="".concat(e,"_").concat(t);return btoa(n)}},{key:"fetchPartnerInfo",value:(h=n(a().m(function e(){var t,n,r,o;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.p=0,e.n=1,this.makeRequest("/debug",{type:this.config.type,client_id:this.config.clientId,secret_id:this.config.secretId});case 1:t=e.v,console.log("📋 Réponse debug API:",t),t.success&&t.data?(n=t.data,r=null,n.partner_id?r=n.partner_id:n.authentication&&n.authentication.auth_test&&n.authentication.auth_test.partner_id?r=n.authentication.auth_test.partner_id:n.auth_test&&n.auth_test.partner_id&&(r=n.auth_test.partner_id),r?(this.config.partnerId=r,n.service_id?this.config.serviceId=n.service_id:this.config.serviceId=r,this.config.partnerName=21===r?"Fayma":"Partner_".concat(r),console.log("✅ Informations partenaire récupérées:",{partnerName:this.config.partnerName,partnerId:this.config.partnerId,serviceId:this.config.serviceId})):(console.warn("⚠️ Partner ID non trouvé dans la réponse, utilisation du partner_id par défaut"),this.config.partnerName="Partner_".concat(this.config.partnerId||"unknown"))):(console.warn("⚠️ Structure de réponse invalide, utilisation du partner_id par défaut"),this.config.partnerName="Partner_".concat(this.config.partnerId||"unknown")),e.n=3;break;case 2:e.p=2,o=e.v,console.warn("⚠️ Erreur lors de la récupération des informations du partenaire:",o.message),this.config.partnerName="Partner_unknown";case 3:return e.a(2)}},e,this,[[0,2]])})),function(){return h.apply(this,arguments)})},{key:"applyTheme",value:function(e){var t=document.querySelector(".sunuid-qr-code");t&&(t.className="sunuid-qr-code sunuid-theme-".concat(e))}},{key:"handleError",value:function(e){console.error("SunuID SDK Error:",e),this.config.onError&&this.config.onError(e)}},{key:"checkConnections",value:(p=n(a().m(function e(){var t,n,r,o;return a().w(function(e){for(;;)switch(e.p=e.n){case 0:return t={api:!1,websocket:!1,ready:!1},e.p=1,e.n=2,fetch(this.config.apiUrl+"/debug",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:this.config.type,client_id:this.config.clientId,secret_id:this.config.secretId})});case 2:if(!(n=e.v).ok){e.n=4;break}return e.n=3,n.json();case 3:r=e.v,t.api=!0===r.success,console.log("🔍 API Status:",t.api?"accessible":"inaccessible"),e.n=5;break;case 4:t.api=!1,console.log("🔍 API Status: HTTP",n.status);case 5:e.n=7;break;case 6:e.p=6,o=e.v,console.log("🔍 Test API échoué:",o.message),t.api=!1;case 7:return t.websocket=this.socket&&this.socket.connected,t.ready=t.api,e.a(2,t)}},e,this,[[1,6]])})),function(){return p.apply(this,arguments)})},{key:"waitForConnections",value:(d=n(a().m(function e(){var t,n,r,o=arguments;return a().w(function(e){for(;;)switch(e.n){case 0:t=o.length>0&&void 0!==o[0]?o[0]:5e3,n=Date.now();case 1:if(!(Date.now()-n<t)){e.n=5;break}return e.n=2,this.checkConnections();case 2:if(!(r=e.v).ready){e.n=3;break}return console.log("✅ Connexions prêtes"),e.a(2,r);case 3:return console.log("⏳ Attente connexions...",r),e.n=4,new Promise(function(e){return setTimeout(e,1e3)});case 4:e.n=1;break;case 5:throw new Error("Timeout connexions - Impossible de générer le QR code");case 6:return e.a(2)}},e,this)})),function(){return d.apply(this,arguments)})},{key:"getQRCode",value:function(){return this.currentQRUrl?this.currentQRUrl:null}},{key:"destroy",value:function(){this.stopAutoRefresh(),this.socket&&(this.socket.disconnect(),this.socket=null,console.log("🌐 WebSocket déconnecté")),this.isInitialized=!1,this.logSecurityEvent("SDK_DESTROY"),console.log("SunuID SDK détruit")}},{key:"stopAutoRefresh",value:function(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null,console.log("🔄 Timer de rafraîchissement arrêté"))}},{key:"getSecurityLogs",value:function(){return e.SunuIDSecurityLogs||[]}},{key:"clearSecurityLogs",value:function(){e.SunuIDSecurityLogs=[],this.logSecurityEvent("SECURITY_LOGS_CLEARED")}},{key:"showQRLoader",value:function(){console.log("🔄 Affichage du loader - Scan QR initié");for(var e=null,t=0,n=["qr-area","qr-container","sunuid-qr-container"];t<n.length;t++){var r=n[t];if(e=document.getElementById(r))break}e?(e.innerHTML='\n <div style="\n text-align: center;\n padding: 40px 20px;\n background: #f8f9fa;\n border: 2px solid #007bff;\n border-radius: 10px;\n color: #007bff;\n font-family: Arial, sans-serif;\n ">\n <div style="\n width: 60px;\n height: 60px;\n border: 4px solid #e3f2fd;\n border-top: 4px solid #007bff;\n border-radius: 50%;\n animation: spin 1s linear infinite;\n margin: 0 auto 20px auto;\n "></div>\n <h3 style="margin: 0 0 10px 0; color: #007bff;">🔍 Scan en cours...</h3>\n <p style="margin: 0; font-size: 14px;">\n Veuillez patienter pendant la vérification de votre identité.\n </p>\n <div style="margin-top: 15px; font-size: 12px; color: #6c757d;">\n ⏱️ Traitement en cours...\n </div>\n </div>\n <style>\n @keyframes spin {\n 0% { transform: rotate(0deg); }\n 100% { transform: rotate(360deg); }\n }\n </style>\n ',console.log("✅ Loader affiché avec succès")):console.warn("⚠️ Conteneur QR non trouvé pour afficher le loader")}},{key:"extractAuthDataFromWebSocket",value:function(e){if(console.log("🔍 Extraction des données d'authentification du WebSocket:",e),console.log("🔍 Structure complète de websocketData:",JSON.stringify(e,null,2)),e.token&&e.session_id)return console.log("✅ Données déjà au bon format (callback)"),e;if(e.responseData){console.log("✅ Format WebSocket détecté, extraction de responseData"),console.log("🔍 Contenu complet de responseData:",e.responseData),console.log("🔍 Clés disponibles dans responseData:",Object.keys(e.responseData));var t=e.responseData,n=t.data||t;console.log("🔍 Données d'authentification dans data:",n),console.log("🔍 Clés disponibles dans data:",Object.keys(n)),n.callback_data&&console.log("🔍 Contenu de callback_data:",n.callback_data),n.session_data&&console.log("🔍 Contenu de session_data:",n.session_data),n.user_data_sent&&console.log("🔍 Contenu de user_data_sent:",n.user_data_sent);var r={token:n.callback_data&&n.callback_data.jwt||n.jwt_token||n.token||n.auth_token||n.callback_data&&n.callback_data.token||n.session_data&&n.session_data.token||n.user_data_sent&&n.user_data_sent.token,session_id:n.session_id||n.sessionId||n.session||n.callback_data&&n.callback_data.session_id||n.session_data&&n.session_data.session_id,user_id:n.user_id||n.userId||n.user,partner_id:n.partner_id||n.partnerId||n.partner,type:n.type,timestamp:n.timestamp||t.timestamp||e.timestamp,signature:n.signature||n.callback_data&&n.callback_data.signature,user_info:n.user_info||n.userInfo||n.user_data||n.user_data_sent&&n.user_data_sent.user_info||n.session_data&&n.session_data.user_info,redirect_url:n.redirect_url||n.redirectUrl||n.redirect||n.session_data&&n.session_data.redirect_url};return console.log("📋 Données d'authentification extraites:",r),r}if(e.data){console.log("✅ Format WebSocket détecté, extraction directe de data"),console.log("🔍 Contenu complet de data:",e.data),console.log("🔍 Clés disponibles dans data:",Object.keys(e.data));var o=e.data;o.callback_data&&console.log("🔍 Contenu de callback_data:",o.callback_data),o.session_data&&console.log("🔍 Contenu de session_data:",o.session_data),o.user_data_sent&&console.log("🔍 Contenu de user_data_sent:",o.user_data_sent);var i={token:o.callback_data&&o.callback_data.jwt||o.jwt_token||o.token||o.auth_token||o.callback_data&&o.callback_data.token||o.session_data&&o.session_data.token||o.user_data_sent&&o.user_data_sent.token,session_id:o.session_id||o.sessionId||o.session||o.callback_data&&o.callback_data.session_id||o.session_data&&o.session_data.session_id,user_id:o.user_id||o.userId||o.user,partner_id:o.partner_id||o.partnerId||o.partner,type:o.type,timestamp:o.timestamp||e.timestamp,signature:o.signature||o.callback_data&&o.callback_data.signature,user_info:o.user_info||o.userInfo||o.user_data||o.user_data_sent&&o.user_data_sent.user_info||o.session_data&&o.session_data.user_info,redirect_url:o.redirect_url||o.redirectUrl||o.redirect||o.session_data&&o.session_data.redirect_url};return console.log("📋 Données d'authentification extraites:",i),i}return console.log("⚠️ Format non reconnu, tentative d'extraction directe"),{token:e.token||e.auth_token,session_id:e.session_id||e.sessionId,user_id:e.user_id||e.userId,partner_id:e.partner_id||e.partnerId,type:e.type,timestamp:e.timestamp,signature:e.signature,user_info:e.user_info||e.userInfo,redirect_url:e.redirect_url||e.redirectUrl}}},{key:"showSuccessMessage",value:function(e){console.log("✅ Affichage du message de succès");for(var t=null,n=0,r=["qr-area","qr-container","sunuid-qr-container"];n<r.length;n++){var o=r[n];if(t=document.getElementById(o))break}if(t){var i=e.user_info||{},s=i.name||i.username||"Utilisateur",a=i.email||"";t.innerHTML='\n <div style="\n text-align: center;\n padding: 40px 20px;\n background: #d4edda;\n border: 2px solid #28a745;\n border-radius: 10px;\n color: #155724;\n font-family: Arial, sans-serif;\n ">\n <div style="\n width: 60px;\n height: 60px;\n background: #28a745;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 20px auto;\n font-size: 30px;\n color: white;\n ">✅</div>\n <h3 style="margin: 0 0 10px 0; color: #155724;">🎉 Authentification réussie !</h3>\n <p style="margin: 0 0 15px 0; font-size: 16px; font-weight: bold;">\n Bienvenue, '.concat(s," !\n </p>\n ").concat(a?'<p style="margin: 0 0 15px 0; font-size: 14px; color: #6c757d;">'.concat(a,"</p>"):"",'\n <p style="margin: 0; font-size: 14px;">\n Votre identité a été vérifiée avec succès.\n </p>\n <div style="margin-top: 20px; font-size: 12px; color: #6c757d;">\n 🔄 Redirection en cours...\n </div>\n </div>\n '),console.log("✅ Message de succès affiché")}else console.warn("⚠️ Conteneur QR non trouvé pour afficher le message de succès")}},{key:"handleCallback",value:function(){var t=new URLSearchParams(e.location.search);if(t.has("token")&&t.has("session_id")){console.log("🔗 Callback SunuID détecté");var n={token:t.get("token"),state:t.get("state"),session_id:t.get("session_id"),user_id:t.get("user_id"),partner_id:t.get("partner_id"),type:t.get("type"),timestamp:t.get("timestamp"),signature:t.get("signature")};return console.log("📋 Données callback:",n),this.validateCallback(n),this.processAuthentication(n),!0}return!1}},{key:"validateCallback",value:function(e){if(console.log("🔒 Validation du callback..."),e.state&&e.state!==this.config.state)throw console.error("❌ État de sécurité invalide"),new Error("État de sécurité invalide");if(e.signature&&this.config.verifySignature&&!this.verifySignature(e))throw console.error("❌ Signature invalide"),new Error("Signature invalide");if(e.timestamp&&this.isExpired(e.timestamp))throw console.error("❌ Token expiré"),new Error("Token expiré");console.log("✅ Callback validé avec succès")}},{key:"processAuthentication",value:function(e){console.log("🔐 Traitement de l'authentification...");try{var t=this.decodeJWT(e.token),n={user_id:t.user_id||e.user_id,session_id:t.session_id||e.session_id,partner_id:t.partner_id||e.partner_id,type:t.type||e.type,iat:t.iat,exp:t.exp};console.log("👤 Données utilisateur:",n),this.emitWebSocketEvent("authentication_success",{userData:n,callbackData:e,timestamp:Date.now()}),this.config.onAuthenticationSuccess&&this.config.onAuthenticationSuccess(n,e),this.config.redirectAfterSuccess&&this.redirectAfterSuccess(n),console.log("✅ Authentification traitée avec succès")}catch(t){throw console.error("❌ Erreur lors du traitement:",t),this.config.onAuthenticationError&&this.config.onAuthenticationError(t,e),t}}},{key:"decodeJWT",value:function(e){try{var t=e.split(".");if(3!==t.length)throw new Error("Format JWT invalide");var n=t[1];return JSON.parse(atob(n))}catch(e){throw console.error("❌ Erreur décodage JWT:",e),new Error("Token JWT invalide")}}},{key:"verifySignature",value:function(e){var t=this.generateSignature(e);return e.signature===t}},{key:"generateSignature",value:function(e){var t="".concat(e.token,".").concat(e.state,".").concat(e.session_id,".").concat(e.timestamp);return btoa(t).slice(0,12)}},{key:"isExpired",value:function(e){return Math.floor(Date.now()/1e3)-parseInt(e)>(this.config.tokenMaxAge||300)}},{key:"redirectAfterSuccess",value:function(t){var n=this.config.redirectAfterSuccess;n=n.replace("{user_id}",t.user_id).replace("{session_id}",t.session_id).replace("{partner_id}",t.partner_id).replace("{type}",t.type),console.log("🔄 Redirection vers:",n),setTimeout(function(){e.location.href=n},100)}},{key:"generateState",value:function(){var e="sunuid_"+Date.now()+"_"+Math.random().toString(36).substr(2,9);return this.config.state=e,e}}],o&&r(t.prototype,o),i&&r(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,o,i,d,p,h,g,v,y,m,b,k,S,I,_,w,R,E,x,C,Q,T,D,q}();e.SunuID=d,e.sunuidInstance=null,e.initSunuID=function(t){try{return e.sunuidInstance=new d(t),e.sunuidInstance}catch(e){throw console.error("Erreur lors de l'initialisation de SunuID:",e),e}}}(window)}();
11
11
  //# sourceMappingURL=sunuid-sdk.min.js.map